blob: f40c325bbfe69f0195be803b82b8604d79e93868 [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;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002064 c->u->u_private = s->v.ClassDef.name;
2065 Py_INCREF(c->u->u_private);
2066 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 if (!str || !compiler_nameop(c, str, Load)) {
2068 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002069 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002071 }
2072
2073 Py_DECREF(str);
2074 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 if (!str || !compiler_nameop(c, str, Store)) {
2076 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002077 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 }
2080 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002082 if (!compiler_body(c, s->v.ClassDef.body)) {
2083 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002085 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002087 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2088 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002090 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 if (co == NULL)
2092 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002094 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002095 Py_DECREF(co);
2096
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 ADDOP_I(c, CALL_FUNCTION, 0);
2098 ADDOP(c, BUILD_CLASS);
2099 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2100 return 0;
2101 return 1;
2102}
2103
2104static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002105compiler_ifexp(struct compiler *c, expr_ty e)
2106{
2107 basicblock *end, *next;
2108
2109 assert(e->kind == IfExp_kind);
2110 end = compiler_new_block(c);
2111 if (end == NULL)
2112 return 0;
2113 next = compiler_new_block(c);
2114 if (next == NULL)
2115 return 0;
2116 VISIT(c, expr, e->v.IfExp.test);
2117 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2118 ADDOP(c, POP_TOP);
2119 VISIT(c, expr, e->v.IfExp.body);
2120 ADDOP_JREL(c, JUMP_FORWARD, end);
2121 compiler_use_next_block(c, next);
2122 ADDOP(c, POP_TOP);
2123 VISIT(c, expr, e->v.IfExp.orelse);
2124 compiler_use_next_block(c, end);
2125 return 1;
2126}
2127
2128static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129compiler_lambda(struct compiler *c, expr_ty e)
2130{
2131 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002132 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 arguments_ty args = e->v.Lambda.args;
2134 assert(e->kind == Lambda_kind);
2135
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002136 if (!name) {
2137 name = PyString_InternFromString("<lambda>");
2138 if (!name)
2139 return 0;
2140 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141
2142 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002143 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2145 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002146
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002147 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148 compiler_arguments(c, args);
2149
2150 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002151 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2152 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002154 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 if (co == NULL)
2156 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002158 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002159 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160
2161 return 1;
2162}
2163
2164static int
2165compiler_print(struct compiler *c, stmt_ty s)
2166{
2167 int i, n;
2168 bool dest;
2169
2170 assert(s->kind == Print_kind);
2171 n = asdl_seq_LEN(s->v.Print.values);
2172 dest = false;
2173 if (s->v.Print.dest) {
2174 VISIT(c, expr, s->v.Print.dest);
2175 dest = true;
2176 }
2177 for (i = 0; i < n; i++) {
2178 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2179 if (dest) {
2180 ADDOP(c, DUP_TOP);
2181 VISIT(c, expr, e);
2182 ADDOP(c, ROT_TWO);
2183 ADDOP(c, PRINT_ITEM_TO);
2184 }
2185 else {
2186 VISIT(c, expr, e);
2187 ADDOP(c, PRINT_ITEM);
2188 }
2189 }
2190 if (s->v.Print.nl) {
2191 if (dest)
2192 ADDOP(c, PRINT_NEWLINE_TO)
2193 else
2194 ADDOP(c, PRINT_NEWLINE)
2195 }
2196 else if (dest)
2197 ADDOP(c, POP_TOP);
2198 return 1;
2199}
2200
2201static int
2202compiler_if(struct compiler *c, stmt_ty s)
2203{
2204 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00002205 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002206 assert(s->kind == If_kind);
2207 end = compiler_new_block(c);
2208 if (end == NULL)
2209 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002210 next = compiler_new_block(c);
2211 if (next == NULL)
2212 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00002213
2214 constant = expr_constant(s->v.If.test);
2215 /* constant = 0: "if 0"
2216 * constant = 1: "if 1", "if 2", ...
2217 * constant = -1: rest */
2218 if (constant == 0) {
2219 if (s->v.If.orelse)
2220 VISIT_SEQ(c, stmt, s->v.If.orelse);
2221 } else if (constant == 1) {
2222 VISIT_SEQ(c, stmt, s->v.If.body);
2223 } else {
2224 VISIT(c, expr, s->v.If.test);
2225 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2226 ADDOP(c, POP_TOP);
2227 VISIT_SEQ(c, stmt, s->v.If.body);
2228 ADDOP_JREL(c, JUMP_FORWARD, end);
2229 compiler_use_next_block(c, next);
2230 ADDOP(c, POP_TOP);
2231 if (s->v.If.orelse)
2232 VISIT_SEQ(c, stmt, s->v.If.orelse);
2233 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 compiler_use_next_block(c, end);
2235 return 1;
2236}
2237
2238static int
2239compiler_for(struct compiler *c, stmt_ty s)
2240{
2241 basicblock *start, *cleanup, *end;
2242
2243 start = compiler_new_block(c);
2244 cleanup = compiler_new_block(c);
2245 end = compiler_new_block(c);
2246 if (start == NULL || end == NULL || cleanup == NULL)
2247 return 0;
2248 ADDOP_JREL(c, SETUP_LOOP, end);
2249 if (!compiler_push_fblock(c, LOOP, start))
2250 return 0;
2251 VISIT(c, expr, s->v.For.iter);
2252 ADDOP(c, GET_ITER);
2253 compiler_use_next_block(c, start);
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002254 /* for expressions must be traced on each iteration,
2255 so we need to set an extra line number. */
Neal Norwitz4ffedad2006-08-04 04:58:47 +00002256 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257 ADDOP_JREL(c, FOR_ITER, cleanup);
2258 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002259 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2261 compiler_use_next_block(c, cleanup);
2262 ADDOP(c, POP_BLOCK);
2263 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002264 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 compiler_use_next_block(c, end);
2266 return 1;
2267}
2268
2269static int
2270compiler_while(struct compiler *c, stmt_ty s)
2271{
2272 basicblock *loop, *orelse, *end, *anchor = NULL;
2273 int constant = expr_constant(s->v.While.test);
2274
Amaury Forgeot d'Arcf1a71782008-01-24 23:42:08 +00002275 if (constant == 0) {
2276 if (s->v.While.orelse)
2277 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 return 1;
Amaury Forgeot d'Arcf1a71782008-01-24 23:42:08 +00002279 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 loop = compiler_new_block(c);
2281 end = compiler_new_block(c);
2282 if (constant == -1) {
2283 anchor = compiler_new_block(c);
2284 if (anchor == NULL)
2285 return 0;
2286 }
2287 if (loop == NULL || end == NULL)
2288 return 0;
2289 if (s->v.While.orelse) {
2290 orelse = compiler_new_block(c);
2291 if (orelse == NULL)
2292 return 0;
2293 }
2294 else
2295 orelse = NULL;
2296
2297 ADDOP_JREL(c, SETUP_LOOP, end);
2298 compiler_use_next_block(c, loop);
2299 if (!compiler_push_fblock(c, LOOP, loop))
2300 return 0;
2301 if (constant == -1) {
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002302 /* while expressions must be traced on each iteration,
2303 so we need to set an extra line number. */
2304 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 VISIT(c, expr, s->v.While.test);
2306 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2307 ADDOP(c, POP_TOP);
2308 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002309 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2311
2312 /* XXX should the two POP instructions be in a separate block
2313 if there is no else clause ?
2314 */
2315
2316 if (constant == -1) {
2317 compiler_use_next_block(c, anchor);
2318 ADDOP(c, POP_TOP);
2319 ADDOP(c, POP_BLOCK);
2320 }
2321 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00002322 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002323 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324 compiler_use_next_block(c, end);
2325
2326 return 1;
2327}
2328
2329static int
2330compiler_continue(struct compiler *c)
2331{
2332 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Georg Brandl74284b92006-10-08 07:06:29 +00002333 static const char IN_FINALLY_ERROR_MSG[] =
2334 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 int i;
2336
2337 if (!c->u->u_nfblocks)
2338 return compiler_error(c, LOOP_ERROR_MSG);
2339 i = c->u->u_nfblocks - 1;
2340 switch (c->u->u_fblock[i].fb_type) {
2341 case LOOP:
2342 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2343 break;
2344 case EXCEPT:
2345 case FINALLY_TRY:
Georg Brandl74284b92006-10-08 07:06:29 +00002346 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2347 /* Prevent try: ... finally:
2348 try: continue ... or
2349 try: ... except: continue */
2350 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2351 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353 if (i == -1)
2354 return compiler_error(c, LOOP_ERROR_MSG);
2355 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2356 break;
2357 case FINALLY_END:
Georg Brandl74284b92006-10-08 07:06:29 +00002358 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359 }
2360
2361 return 1;
2362}
2363
2364/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2365
2366 SETUP_FINALLY L
2367 <code for body>
2368 POP_BLOCK
2369 LOAD_CONST <None>
2370 L: <code for finalbody>
2371 END_FINALLY
2372
2373 The special instructions use the block stack. Each block
2374 stack entry contains the instruction that created it (here
2375 SETUP_FINALLY), the level of the value stack at the time the
2376 block stack entry was created, and a label (here L).
2377
2378 SETUP_FINALLY:
2379 Pushes the current value stack level and the label
2380 onto the block stack.
2381 POP_BLOCK:
2382 Pops en entry from the block stack, and pops the value
2383 stack until its level is the same as indicated on the
2384 block stack. (The label is ignored.)
2385 END_FINALLY:
2386 Pops a variable number of entries from the *value* stack
2387 and re-raises the exception they specify. The number of
2388 entries popped depends on the (pseudo) exception type.
2389
2390 The block stack is unwound when an exception is raised:
2391 when a SETUP_FINALLY entry is found, the exception is pushed
2392 onto the value stack (and the exception condition is cleared),
2393 and the interpreter jumps to the label gotten from the block
2394 stack.
2395*/
2396
2397static int
2398compiler_try_finally(struct compiler *c, stmt_ty s)
2399{
2400 basicblock *body, *end;
2401 body = compiler_new_block(c);
2402 end = compiler_new_block(c);
2403 if (body == NULL || end == NULL)
2404 return 0;
2405
2406 ADDOP_JREL(c, SETUP_FINALLY, end);
2407 compiler_use_next_block(c, body);
2408 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2409 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002410 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411 ADDOP(c, POP_BLOCK);
2412 compiler_pop_fblock(c, FINALLY_TRY, body);
2413
2414 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2415 compiler_use_next_block(c, end);
2416 if (!compiler_push_fblock(c, FINALLY_END, end))
2417 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002418 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419 ADDOP(c, END_FINALLY);
2420 compiler_pop_fblock(c, FINALLY_END, end);
2421
2422 return 1;
2423}
2424
2425/*
2426 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2427 (The contents of the value stack is shown in [], with the top
2428 at the right; 'tb' is trace-back info, 'val' the exception's
2429 associated value, and 'exc' the exception.)
2430
2431 Value stack Label Instruction Argument
2432 [] SETUP_EXCEPT L1
2433 [] <code for S>
2434 [] POP_BLOCK
2435 [] JUMP_FORWARD L0
2436
2437 [tb, val, exc] L1: DUP )
2438 [tb, val, exc, exc] <evaluate E1> )
2439 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2440 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2441 [tb, val, exc, 1] POP )
2442 [tb, val, exc] POP
2443 [tb, val] <assign to V1> (or POP if no V1)
2444 [tb] POP
2445 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002446 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447
2448 [tb, val, exc, 0] L2: POP
2449 [tb, val, exc] DUP
2450 .............................etc.......................
2451
2452 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002453 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454
2455 [] L0: <next statement>
2456
2457 Of course, parts are not generated if Vi or Ei is not present.
2458*/
2459static int
2460compiler_try_except(struct compiler *c, stmt_ty s)
2461{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002462 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 int i, n;
2464
2465 body = compiler_new_block(c);
2466 except = compiler_new_block(c);
2467 orelse = compiler_new_block(c);
2468 end = compiler_new_block(c);
2469 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2470 return 0;
2471 ADDOP_JREL(c, SETUP_EXCEPT, except);
2472 compiler_use_next_block(c, body);
2473 if (!compiler_push_fblock(c, EXCEPT, body))
2474 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002475 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 ADDOP(c, POP_BLOCK);
2477 compiler_pop_fblock(c, EXCEPT, body);
2478 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2479 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2480 compiler_use_next_block(c, except);
2481 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002482 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 s->v.TryExcept.handlers, i);
2484 if (!handler->type && i < n-1)
2485 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002486 c->u->u_lineno_set = false;
2487 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 except = compiler_new_block(c);
2489 if (except == NULL)
2490 return 0;
2491 if (handler->type) {
2492 ADDOP(c, DUP_TOP);
2493 VISIT(c, expr, handler->type);
2494 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2495 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2496 ADDOP(c, POP_TOP);
2497 }
2498 ADDOP(c, POP_TOP);
2499 if (handler->name) {
2500 VISIT(c, expr, handler->name);
2501 }
2502 else {
2503 ADDOP(c, POP_TOP);
2504 }
2505 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002506 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 ADDOP_JREL(c, JUMP_FORWARD, end);
2508 compiler_use_next_block(c, except);
2509 if (handler->type)
2510 ADDOP(c, POP_TOP);
2511 }
2512 ADDOP(c, END_FINALLY);
2513 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002514 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515 compiler_use_next_block(c, end);
2516 return 1;
2517}
2518
2519static int
2520compiler_import_as(struct compiler *c, identifier name, identifier asname)
2521{
2522 /* The IMPORT_NAME opcode was already generated. This function
2523 merely needs to bind the result to a name.
2524
2525 If there is a dot in name, we need to split it and emit a
2526 LOAD_ATTR for each name.
2527 */
2528 const char *src = PyString_AS_STRING(name);
2529 const char *dot = strchr(src, '.');
2530 if (dot) {
2531 /* Consume the base module name to get the first attribute */
2532 src = dot + 1;
2533 while (dot) {
2534 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002535 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002537 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002539 if (!attr)
2540 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002542 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 src = dot + 1;
2544 }
2545 }
2546 return compiler_nameop(c, asname, Store);
2547}
2548
2549static int
2550compiler_import(struct compiler *c, stmt_ty s)
2551{
2552 /* The Import node stores a module name like a.b.c as a single
2553 string. This is convenient for all cases except
2554 import a.b.c as d
2555 where we need to parse that string to extract the individual
2556 module names.
2557 XXX Perhaps change the representation to make this case simpler?
2558 */
2559 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002562 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002563 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002564 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565
Neal Norwitzcbce2802006-04-03 06:26:32 +00002566 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002567 level = PyInt_FromLong(0);
2568 else
2569 level = PyInt_FromLong(-1);
2570
2571 if (level == NULL)
2572 return 0;
2573
2574 ADDOP_O(c, LOAD_CONST, level, consts);
2575 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2577 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2578
2579 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002580 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002581 if (!r)
2582 return r;
2583 }
2584 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 identifier tmp = alias->name;
2586 const char *base = PyString_AS_STRING(alias->name);
2587 char *dot = strchr(base, '.');
2588 if (dot)
2589 tmp = PyString_FromStringAndSize(base,
2590 dot - base);
2591 r = compiler_nameop(c, tmp, Store);
2592 if (dot) {
2593 Py_DECREF(tmp);
2594 }
2595 if (!r)
2596 return r;
2597 }
2598 }
2599 return 1;
2600}
2601
2602static int
2603compiler_from_import(struct compiler *c, stmt_ty s)
2604{
2605 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606
2607 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002608 PyObject *level;
2609
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610 if (!names)
2611 return 0;
2612
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002613 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002614 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002615 level = PyInt_FromLong(-1);
2616 else
2617 level = PyInt_FromLong(s->v.ImportFrom.level);
2618
2619 if (!level) {
2620 Py_DECREF(names);
2621 return 0;
2622 }
2623
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624 /* build up the names */
2625 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002626 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 Py_INCREF(alias->name);
2628 PyTuple_SET_ITEM(names, i, alias->name);
2629 }
2630
2631 if (s->lineno > c->c_future->ff_lineno) {
2632 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2633 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002634 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 Py_DECREF(names);
2636 return compiler_error(c,
2637 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002638 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639
2640 }
2641 }
2642
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002643 ADDOP_O(c, LOAD_CONST, level, consts);
2644 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002646 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2648 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002649 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 identifier store_name;
2651
2652 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2653 assert(n == 1);
2654 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002655 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 }
2657
2658 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2659 store_name = alias->name;
2660 if (alias->asname)
2661 store_name = alias->asname;
2662
2663 if (!compiler_nameop(c, store_name, Store)) {
2664 Py_DECREF(names);
2665 return 0;
2666 }
2667 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002668 /* remove imported module */
2669 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 return 1;
2671}
2672
2673static int
2674compiler_assert(struct compiler *c, stmt_ty s)
2675{
2676 static PyObject *assertion_error = NULL;
2677 basicblock *end;
2678
2679 if (Py_OptimizeFlag)
2680 return 1;
2681 if (assertion_error == NULL) {
2682 assertion_error = PyString_FromString("AssertionError");
2683 if (assertion_error == NULL)
2684 return 0;
2685 }
2686 VISIT(c, expr, s->v.Assert.test);
2687 end = compiler_new_block(c);
2688 if (end == NULL)
2689 return 0;
2690 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2691 ADDOP(c, POP_TOP);
2692 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2693 if (s->v.Assert.msg) {
2694 VISIT(c, expr, s->v.Assert.msg);
2695 ADDOP_I(c, RAISE_VARARGS, 2);
2696 }
2697 else {
2698 ADDOP_I(c, RAISE_VARARGS, 1);
2699 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002700 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 ADDOP(c, POP_TOP);
2702 return 1;
2703}
2704
2705static int
2706compiler_visit_stmt(struct compiler *c, stmt_ty s)
2707{
2708 int i, n;
2709
Jeremy Hylton12603c42006-04-01 16:18:02 +00002710 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 c->u->u_lineno = s->lineno;
2712 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002713
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002715 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002717 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 if (c->u->u_ste->ste_type != FunctionBlock)
2721 return compiler_error(c, "'return' outside function");
2722 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 VISIT(c, expr, s->v.Return.value);
2724 }
2725 else
2726 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2727 ADDOP(c, RETURN_VALUE);
2728 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002729 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002730 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002732 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 n = asdl_seq_LEN(s->v.Assign.targets);
2734 VISIT(c, expr, s->v.Assign.value);
2735 for (i = 0; i < n; i++) {
2736 if (i < n - 1)
2737 ADDOP(c, DUP_TOP);
2738 VISIT(c, expr,
2739 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2740 }
2741 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002742 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002744 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002746 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002748 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002750 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002752 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753 n = 0;
2754 if (s->v.Raise.type) {
2755 VISIT(c, expr, s->v.Raise.type);
2756 n++;
2757 if (s->v.Raise.inst) {
2758 VISIT(c, expr, s->v.Raise.inst);
2759 n++;
2760 if (s->v.Raise.tback) {
2761 VISIT(c, expr, s->v.Raise.tback);
2762 n++;
2763 }
2764 }
2765 }
2766 ADDOP_I(c, RAISE_VARARGS, n);
2767 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002768 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002770 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002772 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002774 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002776 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002778 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779 VISIT(c, expr, s->v.Exec.body);
2780 if (s->v.Exec.globals) {
2781 VISIT(c, expr, s->v.Exec.globals);
2782 if (s->v.Exec.locals) {
2783 VISIT(c, expr, s->v.Exec.locals);
2784 } else {
2785 ADDOP(c, DUP_TOP);
2786 }
2787 } else {
2788 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2789 ADDOP(c, DUP_TOP);
2790 }
2791 ADDOP(c, EXEC_STMT);
2792 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002793 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002795 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002797 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798 ADDOP(c, PRINT_EXPR);
2799 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002800 else if (s->v.Expr.value->kind != Str_kind &&
2801 s->v.Expr.value->kind != Num_kind) {
2802 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002803 ADDOP(c, POP_TOP);
2804 }
2805 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002806 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002808 case Break_kind:
Georg Brandla5fe3ef2006-10-08 07:12:23 +00002809 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002810 return compiler_error(c, "'break' outside loop");
2811 ADDOP(c, BREAK_LOOP);
2812 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002813 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 case With_kind:
2816 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817 }
2818 return 1;
2819}
2820
2821static int
2822unaryop(unaryop_ty op)
2823{
2824 switch (op) {
2825 case Invert:
2826 return UNARY_INVERT;
2827 case Not:
2828 return UNARY_NOT;
2829 case UAdd:
2830 return UNARY_POSITIVE;
2831 case USub:
2832 return UNARY_NEGATIVE;
2833 }
2834 return 0;
2835}
2836
2837static int
2838binop(struct compiler *c, operator_ty op)
2839{
2840 switch (op) {
2841 case Add:
2842 return BINARY_ADD;
2843 case Sub:
2844 return BINARY_SUBTRACT;
2845 case Mult:
2846 return BINARY_MULTIPLY;
2847 case Div:
2848 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2849 return BINARY_TRUE_DIVIDE;
2850 else
2851 return BINARY_DIVIDE;
2852 case Mod:
2853 return BINARY_MODULO;
2854 case Pow:
2855 return BINARY_POWER;
2856 case LShift:
2857 return BINARY_LSHIFT;
2858 case RShift:
2859 return BINARY_RSHIFT;
2860 case BitOr:
2861 return BINARY_OR;
2862 case BitXor:
2863 return BINARY_XOR;
2864 case BitAnd:
2865 return BINARY_AND;
2866 case FloorDiv:
2867 return BINARY_FLOOR_DIVIDE;
2868 }
2869 return 0;
2870}
2871
2872static int
2873cmpop(cmpop_ty op)
2874{
2875 switch (op) {
2876 case Eq:
2877 return PyCmp_EQ;
2878 case NotEq:
2879 return PyCmp_NE;
2880 case Lt:
2881 return PyCmp_LT;
2882 case LtE:
2883 return PyCmp_LE;
2884 case Gt:
2885 return PyCmp_GT;
2886 case GtE:
2887 return PyCmp_GE;
2888 case Is:
2889 return PyCmp_IS;
2890 case IsNot:
2891 return PyCmp_IS_NOT;
2892 case In:
2893 return PyCmp_IN;
2894 case NotIn:
2895 return PyCmp_NOT_IN;
2896 }
2897 return PyCmp_BAD;
2898}
2899
2900static int
2901inplace_binop(struct compiler *c, operator_ty op)
2902{
2903 switch (op) {
2904 case Add:
2905 return INPLACE_ADD;
2906 case Sub:
2907 return INPLACE_SUBTRACT;
2908 case Mult:
2909 return INPLACE_MULTIPLY;
2910 case Div:
2911 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2912 return INPLACE_TRUE_DIVIDE;
2913 else
2914 return INPLACE_DIVIDE;
2915 case Mod:
2916 return INPLACE_MODULO;
2917 case Pow:
2918 return INPLACE_POWER;
2919 case LShift:
2920 return INPLACE_LSHIFT;
2921 case RShift:
2922 return INPLACE_RSHIFT;
2923 case BitOr:
2924 return INPLACE_OR;
2925 case BitXor:
2926 return INPLACE_XOR;
2927 case BitAnd:
2928 return INPLACE_AND;
2929 case FloorDiv:
2930 return INPLACE_FLOOR_DIVIDE;
2931 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002932 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002933 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 return 0;
2935}
2936
2937static int
2938compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2939{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002940 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2942
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002943 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002944 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 /* XXX AugStore isn't used anywhere! */
2946
2947 /* First check for assignment to __debug__. Param? */
2948 if ((ctx == Store || ctx == AugStore || ctx == Del)
2949 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2950 return compiler_error(c, "can not assign to __debug__");
2951 }
2952
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002953 mangled = _Py_Mangle(c->u->u_private, name);
2954 if (!mangled)
2955 return 0;
2956
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957 op = 0;
2958 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002959 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 switch (scope) {
2961 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002962 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 optype = OP_DEREF;
2964 break;
2965 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002966 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 optype = OP_DEREF;
2968 break;
2969 case LOCAL:
2970 if (c->u->u_ste->ste_type == FunctionBlock)
2971 optype = OP_FAST;
2972 break;
2973 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002974 if (c->u->u_ste->ste_type == FunctionBlock &&
2975 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 optype = OP_GLOBAL;
2977 break;
2978 case GLOBAL_EXPLICIT:
2979 optype = OP_GLOBAL;
2980 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002981 default:
2982 /* scope can be 0 */
2983 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 }
2985
2986 /* XXX Leave assert here, but handle __doc__ and the like better */
2987 assert(scope || PyString_AS_STRING(name)[0] == '_');
2988
2989 switch (optype) {
2990 case OP_DEREF:
2991 switch (ctx) {
2992 case Load: op = LOAD_DEREF; break;
2993 case Store: op = STORE_DEREF; break;
2994 case AugLoad:
2995 case AugStore:
2996 break;
2997 case Del:
2998 PyErr_Format(PyExc_SyntaxError,
2999 "can not delete variable '%s' referenced "
3000 "in nested scope",
3001 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003002 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003005 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003006 PyErr_SetString(PyExc_SystemError,
3007 "param invalid for deref variable");
3008 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009 }
3010 break;
3011 case OP_FAST:
3012 switch (ctx) {
3013 case Load: op = LOAD_FAST; break;
3014 case Store: op = STORE_FAST; break;
3015 case Del: op = DELETE_FAST; break;
3016 case AugLoad:
3017 case AugStore:
3018 break;
3019 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003020 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003021 PyErr_SetString(PyExc_SystemError,
3022 "param invalid for local variable");
3023 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003025 ADDOP_O(c, op, mangled, varnames);
3026 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 return 1;
3028 case OP_GLOBAL:
3029 switch (ctx) {
3030 case Load: op = LOAD_GLOBAL; break;
3031 case Store: op = STORE_GLOBAL; break;
3032 case Del: op = DELETE_GLOBAL; break;
3033 case AugLoad:
3034 case AugStore:
3035 break;
3036 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003037 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003038 PyErr_SetString(PyExc_SystemError,
3039 "param invalid for global variable");
3040 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041 }
3042 break;
3043 case OP_NAME:
3044 switch (ctx) {
3045 case Load: op = LOAD_NAME; break;
3046 case Store: op = STORE_NAME; break;
3047 case Del: op = DELETE_NAME; break;
3048 case AugLoad:
3049 case AugStore:
3050 break;
3051 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003052 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003053 PyErr_SetString(PyExc_SystemError,
3054 "param invalid for name variable");
3055 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 }
3057 break;
3058 }
3059
3060 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003061 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00003062 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003063 if (arg < 0)
3064 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00003065 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003066}
3067
3068static int
3069compiler_boolop(struct compiler *c, expr_ty e)
3070{
3071 basicblock *end;
3072 int jumpi, i, n;
3073 asdl_seq *s;
3074
3075 assert(e->kind == BoolOp_kind);
3076 if (e->v.BoolOp.op == And)
3077 jumpi = JUMP_IF_FALSE;
3078 else
3079 jumpi = JUMP_IF_TRUE;
3080 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00003081 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082 return 0;
3083 s = e->v.BoolOp.values;
3084 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00003085 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003087 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 ADDOP_JREL(c, jumpi, end);
3089 ADDOP(c, POP_TOP)
3090 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003091 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092 compiler_use_next_block(c, end);
3093 return 1;
3094}
3095
3096static int
3097compiler_list(struct compiler *c, expr_ty e)
3098{
3099 int n = asdl_seq_LEN(e->v.List.elts);
3100 if (e->v.List.ctx == Store) {
3101 ADDOP_I(c, UNPACK_SEQUENCE, n);
3102 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003103 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104 if (e->v.List.ctx == Load) {
3105 ADDOP_I(c, BUILD_LIST, n);
3106 }
3107 return 1;
3108}
3109
3110static int
3111compiler_tuple(struct compiler *c, expr_ty e)
3112{
3113 int n = asdl_seq_LEN(e->v.Tuple.elts);
3114 if (e->v.Tuple.ctx == Store) {
3115 ADDOP_I(c, UNPACK_SEQUENCE, n);
3116 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003117 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118 if (e->v.Tuple.ctx == Load) {
3119 ADDOP_I(c, BUILD_TUPLE, n);
3120 }
3121 return 1;
3122}
3123
3124static int
3125compiler_compare(struct compiler *c, expr_ty e)
3126{
3127 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003128 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003129
3130 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3131 VISIT(c, expr, e->v.Compare.left);
3132 n = asdl_seq_LEN(e->v.Compare.ops);
3133 assert(n > 0);
3134 if (n > 1) {
3135 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003136 if (cleanup == NULL)
3137 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00003138 VISIT(c, expr,
3139 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140 }
3141 for (i = 1; i < n; i++) {
3142 ADDOP(c, DUP_TOP);
3143 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003145 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00003146 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3148 NEXT_BLOCK(c);
3149 ADDOP(c, POP_TOP);
3150 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00003151 VISIT(c, expr,
3152 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003153 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003154 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003156 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157 if (n > 1) {
3158 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003159 if (end == NULL)
3160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161 ADDOP_JREL(c, JUMP_FORWARD, end);
3162 compiler_use_next_block(c, cleanup);
3163 ADDOP(c, ROT_TWO);
3164 ADDOP(c, POP_TOP);
3165 compiler_use_next_block(c, end);
3166 }
3167 return 1;
3168}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00003169#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170
3171static int
3172compiler_call(struct compiler *c, expr_ty e)
3173{
3174 int n, code = 0;
3175
3176 VISIT(c, expr, e->v.Call.func);
3177 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003178 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003180 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3182 }
3183 if (e->v.Call.starargs) {
3184 VISIT(c, expr, e->v.Call.starargs);
3185 code |= 1;
3186 }
3187 if (e->v.Call.kwargs) {
3188 VISIT(c, expr, e->v.Call.kwargs);
3189 code |= 2;
3190 }
3191 switch (code) {
3192 case 0:
3193 ADDOP_I(c, CALL_FUNCTION, n);
3194 break;
3195 case 1:
3196 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3197 break;
3198 case 2:
3199 ADDOP_I(c, CALL_FUNCTION_KW, n);
3200 break;
3201 case 3:
3202 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3203 break;
3204 }
3205 return 1;
3206}
3207
3208static int
3209compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003210 asdl_seq *generators, int gen_index,
3211 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212{
3213 /* generate code for the iterator, then each of the ifs,
3214 and then write to the element */
3215
3216 comprehension_ty l;
3217 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003218 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219
3220 start = compiler_new_block(c);
3221 skip = compiler_new_block(c);
3222 if_cleanup = compiler_new_block(c);
3223 anchor = compiler_new_block(c);
3224
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003225 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3226 anchor == NULL)
3227 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228
Anthony Baxter7b782b62006-04-11 12:01:56 +00003229 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 VISIT(c, expr, l->iter);
3231 ADDOP(c, GET_ITER);
3232 compiler_use_next_block(c, start);
3233 ADDOP_JREL(c, FOR_ITER, anchor);
3234 NEXT_BLOCK(c);
3235 VISIT(c, expr, l->target);
3236
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003237 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 n = asdl_seq_LEN(l->ifs);
3239 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003240 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003241 VISIT(c, expr, e);
3242 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3243 NEXT_BLOCK(c);
3244 ADDOP(c, POP_TOP);
3245 }
3246
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003247 if (++gen_index < asdl_seq_LEN(generators))
3248 if (!compiler_listcomp_generator(c, tmpname,
3249 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003252 /* only append after the last for generator */
3253 if (gen_index >= asdl_seq_LEN(generators)) {
3254 if (!compiler_nameop(c, tmpname, Load))
3255 return 0;
3256 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003257 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003258
3259 compiler_use_next_block(c, skip);
3260 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 for (i = 0; i < n; i++) {
3262 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 if (i == 0)
3264 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265 ADDOP(c, POP_TOP);
3266 }
3267 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3268 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003269 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003271 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272 return 0;
3273
3274 return 1;
3275}
3276
3277static int
3278compiler_listcomp(struct compiler *c, expr_ty e)
3279{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003281 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282 static identifier append;
3283 asdl_seq *generators = e->v.ListComp.generators;
3284
3285 assert(e->kind == ListComp_kind);
3286 if (!append) {
3287 append = PyString_InternFromString("append");
3288 if (!append)
3289 return 0;
3290 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003291 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 if (!tmp)
3293 return 0;
3294 ADDOP_I(c, BUILD_LIST, 0);
3295 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003297 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3298 e->v.ListComp.elt);
3299 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 return rc;
3301}
3302
3303static int
3304compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003305 asdl_seq *generators, int gen_index,
3306 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307{
3308 /* generate code for the iterator, then each of the ifs,
3309 and then write to the element */
3310
3311 comprehension_ty ge;
3312 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003313 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314
3315 start = compiler_new_block(c);
3316 skip = compiler_new_block(c);
3317 if_cleanup = compiler_new_block(c);
3318 anchor = compiler_new_block(c);
3319 end = compiler_new_block(c);
3320
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003321 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 anchor == NULL || end == NULL)
3323 return 0;
3324
Anthony Baxter7b782b62006-04-11 12:01:56 +00003325 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326 ADDOP_JREL(c, SETUP_LOOP, end);
3327 if (!compiler_push_fblock(c, LOOP, start))
3328 return 0;
3329
3330 if (gen_index == 0) {
3331 /* Receive outermost iter as an implicit argument */
3332 c->u->u_argcount = 1;
3333 ADDOP_I(c, LOAD_FAST, 0);
3334 }
3335 else {
3336 /* Sub-iter - calculate on the fly */
3337 VISIT(c, expr, ge->iter);
3338 ADDOP(c, GET_ITER);
3339 }
3340 compiler_use_next_block(c, start);
3341 ADDOP_JREL(c, FOR_ITER, anchor);
3342 NEXT_BLOCK(c);
3343 VISIT(c, expr, ge->target);
3344
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003345 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346 n = asdl_seq_LEN(ge->ifs);
3347 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003348 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349 VISIT(c, expr, e);
3350 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3351 NEXT_BLOCK(c);
3352 ADDOP(c, POP_TOP);
3353 }
3354
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003355 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003356 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3357 return 0;
3358
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003359 /* only append after the last 'for' generator */
3360 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003361 VISIT(c, expr, elt);
3362 ADDOP(c, YIELD_VALUE);
3363 ADDOP(c, POP_TOP);
3364
3365 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003366 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003367 for (i = 0; i < n; i++) {
3368 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003369 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003370 compiler_use_next_block(c, if_cleanup);
3371
3372 ADDOP(c, POP_TOP);
3373 }
3374 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3375 compiler_use_next_block(c, anchor);
3376 ADDOP(c, POP_BLOCK);
3377 compiler_pop_fblock(c, LOOP, start);
3378 compiler_use_next_block(c, end);
3379
3380 return 1;
3381}
3382
3383static int
3384compiler_genexp(struct compiler *c, expr_ty e)
3385{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003386 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387 PyCodeObject *co;
3388 expr_ty outermost_iter = ((comprehension_ty)
3389 (asdl_seq_GET(e->v.GeneratorExp.generators,
3390 0)))->iter;
3391
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003392 if (!name) {
3393 name = PyString_FromString("<genexpr>");
3394 if (!name)
3395 return 0;
3396 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397
3398 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3399 return 0;
3400 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3401 e->v.GeneratorExp.elt);
3402 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003403 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003404 if (co == NULL)
3405 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003406
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003407 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003408 Py_DECREF(co);
3409
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003410 VISIT(c, expr, outermost_iter);
3411 ADDOP(c, GET_ITER);
3412 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003413
3414 return 1;
3415}
3416
3417static int
3418compiler_visit_keyword(struct compiler *c, keyword_ty k)
3419{
3420 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3421 VISIT(c, expr, k->value);
3422 return 1;
3423}
3424
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003425/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003426 whether they are true or false.
3427
3428 Return values: 1 for true, 0 for false, -1 for non-constant.
3429 */
3430
3431static int
3432expr_constant(expr_ty e)
3433{
3434 switch (e->kind) {
3435 case Num_kind:
3436 return PyObject_IsTrue(e->v.Num.n);
3437 case Str_kind:
3438 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00003439 case Name_kind:
3440 /* __debug__ is not assignable, so we can optimize
3441 * it away in if and while statements */
3442 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3443 "__debug__") == 0)
3444 return ! Py_OptimizeFlag;
3445 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446 default:
3447 return -1;
3448 }
3449}
3450
Guido van Rossumc2e20742006-02-27 22:32:47 +00003451/*
3452 Implements the with statement from PEP 343.
3453
3454 The semantics outlined in that PEP are as follows:
3455
3456 with EXPR as VAR:
3457 BLOCK
3458
3459 It is implemented roughly as:
3460
Guido van Rossumda5b7012006-05-02 19:47:52 +00003461 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003462 exit = context.__exit__ # not calling it
3463 value = context.__enter__()
3464 try:
3465 VAR = value # if VAR present in the syntax
3466 BLOCK
3467 finally:
3468 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003469 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003470 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003471 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003472 exit(*exc)
3473 */
3474static int
3475compiler_with(struct compiler *c, stmt_ty s)
3476{
Guido van Rossumda5b7012006-05-02 19:47:52 +00003477 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003478 basicblock *block, *finally;
3479 identifier tmpexit, tmpvalue = NULL;
3480
3481 assert(s->kind == With_kind);
3482
Guido van Rossumc2e20742006-02-27 22:32:47 +00003483 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003484 enter_attr = PyString_InternFromString("__enter__");
3485 if (!enter_attr)
3486 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003487 }
3488 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003489 exit_attr = PyString_InternFromString("__exit__");
3490 if (!exit_attr)
3491 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003492 }
3493
3494 block = compiler_new_block(c);
3495 finally = compiler_new_block(c);
3496 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003497 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003498
3499 /* Create a temporary variable to hold context.__exit__ */
3500 tmpexit = compiler_new_tmpname(c);
3501 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003502 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003503 PyArena_AddPyObject(c->c_arena, tmpexit);
3504
3505 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003507 We need to do this rather than preserving it on the stack
3508 because SETUP_FINALLY remembers the stack level.
3509 We need to do the assignment *inside* the try/finally
3510 so that context.__exit__() is called when the assignment
3511 fails. But we need to call context.__enter__() *before*
3512 the try/finally so that if it fails we won't call
3513 context.__exit__().
3514 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003515 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003516 if (tmpvalue == NULL)
3517 return 0;
3518 PyArena_AddPyObject(c->c_arena, tmpvalue);
3519 }
3520
Guido van Rossumda5b7012006-05-02 19:47:52 +00003521 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003522 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003523
3524 /* Squirrel away context.__exit__ */
3525 ADDOP(c, DUP_TOP);
3526 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3527 if (!compiler_nameop(c, tmpexit, Store))
3528 return 0;
3529
3530 /* Call context.__enter__() */
3531 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3532 ADDOP_I(c, CALL_FUNCTION, 0);
3533
3534 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003535 /* Store it in tmpvalue */
3536 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003537 return 0;
3538 }
3539 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003540 /* Discard result from context.__enter__() */
3541 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003542 }
3543
3544 /* Start the try block */
3545 ADDOP_JREL(c, SETUP_FINALLY, finally);
3546
3547 compiler_use_next_block(c, block);
3548 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003549 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003550 }
3551
3552 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003553 /* Bind saved result of context.__enter__() to VAR */
3554 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003555 !compiler_nameop(c, tmpvalue, Del))
3556 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003557 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003558 }
3559
3560 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003561 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003562
3563 /* End of try block; start the finally block */
3564 ADDOP(c, POP_BLOCK);
3565 compiler_pop_fblock(c, FINALLY_TRY, block);
3566
3567 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3568 compiler_use_next_block(c, finally);
3569 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003570 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003571
3572 /* Finally block starts; push tmpexit and issue our magic opcode. */
3573 if (!compiler_nameop(c, tmpexit, Load) ||
3574 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003575 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003576 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003577
3578 /* Finally block ends. */
3579 ADDOP(c, END_FINALLY);
3580 compiler_pop_fblock(c, FINALLY_END, finally);
3581 return 1;
3582}
3583
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584static int
3585compiler_visit_expr(struct compiler *c, expr_ty e)
3586{
3587 int i, n;
3588
Jeremy Hylton12603c42006-04-01 16:18:02 +00003589 /* If expr e has a different line number than the last expr/stmt,
3590 set a new line number for the next instruction.
3591 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 if (e->lineno > c->u->u_lineno) {
3593 c->u->u_lineno = e->lineno;
3594 c->u->u_lineno_set = false;
3595 }
3596 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003597 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003599 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 VISIT(c, expr, e->v.BinOp.left);
3601 VISIT(c, expr, e->v.BinOp.right);
3602 ADDOP(c, binop(c, e->v.BinOp.op));
3603 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003604 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 VISIT(c, expr, e->v.UnaryOp.operand);
3606 ADDOP(c, unaryop(e->v.UnaryOp.op));
3607 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003608 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003610 case IfExp_kind:
3611 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003612 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 /* XXX get rid of arg? */
3614 ADDOP_I(c, BUILD_MAP, 0);
3615 n = asdl_seq_LEN(e->v.Dict.values);
3616 /* We must arrange things just right for STORE_SUBSCR.
3617 It wants the stack to look like (value) (dict) (key) */
3618 for (i = 0; i < n; i++) {
3619 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003620 VISIT(c, expr,
3621 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003623 VISIT(c, expr,
3624 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625 ADDOP(c, STORE_SUBSCR);
3626 }
3627 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003628 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003629 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003630 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 return compiler_genexp(c, e);
3632 case Yield_kind:
3633 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003634 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635 /*
3636 for (i = 0; i < c->u->u_nfblocks; i++) {
3637 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3638 return compiler_error(
3639 c, "'yield' not allowed in a 'try' "
3640 "block with a 'finally' clause");
3641 }
3642 */
3643 if (e->v.Yield.value) {
3644 VISIT(c, expr, e->v.Yield.value);
3645 }
3646 else {
3647 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3648 }
3649 ADDOP(c, YIELD_VALUE);
3650 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003651 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003653 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003655 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 VISIT(c, expr, e->v.Repr.value);
3657 ADDOP(c, UNARY_CONVERT);
3658 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003659 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3661 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003662 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3664 break;
3665 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003666 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667 if (e->v.Attribute.ctx != AugStore)
3668 VISIT(c, expr, e->v.Attribute.value);
3669 switch (e->v.Attribute.ctx) {
3670 case AugLoad:
3671 ADDOP(c, DUP_TOP);
3672 /* Fall through to load */
3673 case Load:
3674 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3675 break;
3676 case AugStore:
3677 ADDOP(c, ROT_TWO);
3678 /* Fall through to save */
3679 case Store:
3680 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3681 break;
3682 case Del:
3683 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3684 break;
3685 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003686 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003687 PyErr_SetString(PyExc_SystemError,
3688 "param invalid in attribute expression");
3689 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 }
3691 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003692 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003693 switch (e->v.Subscript.ctx) {
3694 case AugLoad:
3695 VISIT(c, expr, e->v.Subscript.value);
3696 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3697 break;
3698 case Load:
3699 VISIT(c, expr, e->v.Subscript.value);
3700 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3701 break;
3702 case AugStore:
3703 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3704 break;
3705 case Store:
3706 VISIT(c, expr, e->v.Subscript.value);
3707 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3708 break;
3709 case Del:
3710 VISIT(c, expr, e->v.Subscript.value);
3711 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3712 break;
3713 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003714 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003715 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003716 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003717 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718 }
3719 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003720 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3722 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003723 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003724 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003725 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726 return compiler_tuple(c, e);
3727 }
3728 return 1;
3729}
3730
3731static int
3732compiler_augassign(struct compiler *c, stmt_ty s)
3733{
3734 expr_ty e = s->v.AugAssign.target;
3735 expr_ty auge;
3736
3737 assert(s->kind == AugAssign_kind);
3738
3739 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003740 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003742 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003743 if (auge == NULL)
3744 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745 VISIT(c, expr, auge);
3746 VISIT(c, expr, s->v.AugAssign.value);
3747 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3748 auge->v.Attribute.ctx = AugStore;
3749 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 break;
3751 case Subscript_kind:
3752 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003753 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003754 if (auge == NULL)
3755 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756 VISIT(c, expr, auge);
3757 VISIT(c, expr, s->v.AugAssign.value);
3758 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003759 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003761 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003763 if (!compiler_nameop(c, e->v.Name.id, Load))
3764 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765 VISIT(c, expr, s->v.AugAssign.value);
3766 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3767 return compiler_nameop(c, e->v.Name.id, Store);
3768 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003769 PyErr_Format(PyExc_SystemError,
3770 "invalid node type (%d) for augmented assignment",
3771 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003772 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 }
3774 return 1;
3775}
3776
3777static int
3778compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3779{
3780 struct fblockinfo *f;
Neal Norwitz2f0940b2006-10-28 21:38:43 +00003781 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3782 PyErr_SetString(PyExc_SystemError,
3783 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784 return 0;
Neal Norwitz2f0940b2006-10-28 21:38:43 +00003785 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 f = &c->u->u_fblock[c->u->u_nfblocks++];
3787 f->fb_type = t;
3788 f->fb_block = b;
3789 return 1;
3790}
3791
3792static void
3793compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3794{
3795 struct compiler_unit *u = c->u;
3796 assert(u->u_nfblocks > 0);
3797 u->u_nfblocks--;
3798 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3799 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3800}
3801
Georg Brandla5fe3ef2006-10-08 07:12:23 +00003802static int
3803compiler_in_loop(struct compiler *c) {
3804 int i;
3805 struct compiler_unit *u = c->u;
3806 for (i = 0; i < u->u_nfblocks; ++i) {
3807 if (u->u_fblock[i].fb_type == LOOP)
3808 return 1;
3809 }
3810 return 0;
3811}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812/* Raises a SyntaxError and returns 0.
3813 If something goes wrong, a different exception may be raised.
3814*/
3815
3816static int
3817compiler_error(struct compiler *c, const char *errstr)
3818{
3819 PyObject *loc;
3820 PyObject *u = NULL, *v = NULL;
3821
3822 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3823 if (!loc) {
3824 Py_INCREF(Py_None);
3825 loc = Py_None;
3826 }
3827 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3828 Py_None, loc);
3829 if (!u)
3830 goto exit;
3831 v = Py_BuildValue("(zO)", errstr, u);
3832 if (!v)
3833 goto exit;
3834 PyErr_SetObject(PyExc_SyntaxError, v);
3835 exit:
3836 Py_DECREF(loc);
3837 Py_XDECREF(u);
3838 Py_XDECREF(v);
3839 return 0;
3840}
3841
3842static int
3843compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003844 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003845{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003846 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003848 /* XXX this code is duplicated */
3849 switch (ctx) {
3850 case AugLoad: /* fall through to Load */
3851 case Load: op = BINARY_SUBSCR; break;
3852 case AugStore:/* fall through to Store */
3853 case Store: op = STORE_SUBSCR; break;
3854 case Del: op = DELETE_SUBSCR; break;
3855 case Param:
3856 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003857 "invalid %s kind %d in subscript\n",
3858 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003859 return 0;
3860 }
3861 if (ctx == AugLoad) {
3862 ADDOP_I(c, DUP_TOPX, 2);
3863 }
3864 else if (ctx == AugStore) {
3865 ADDOP(c, ROT_THREE);
3866 }
3867 ADDOP(c, op);
3868 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003869}
3870
3871static int
3872compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3873{
3874 int n = 2;
3875 assert(s->kind == Slice_kind);
3876
3877 /* only handles the cases where BUILD_SLICE is emitted */
3878 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003879 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880 }
3881 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003882 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003884
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003886 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887 }
3888 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003889 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890 }
3891
3892 if (s->v.Slice.step) {
3893 n++;
3894 VISIT(c, expr, s->v.Slice.step);
3895 }
3896 ADDOP_I(c, BUILD_SLICE, n);
3897 return 1;
3898}
3899
3900static int
3901compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3902{
3903 int op = 0, slice_offset = 0, stack_count = 0;
3904
3905 assert(s->v.Slice.step == NULL);
3906 if (s->v.Slice.lower) {
3907 slice_offset++;
3908 stack_count++;
3909 if (ctx != AugStore)
3910 VISIT(c, expr, s->v.Slice.lower);
3911 }
3912 if (s->v.Slice.upper) {
3913 slice_offset += 2;
3914 stack_count++;
3915 if (ctx != AugStore)
3916 VISIT(c, expr, s->v.Slice.upper);
3917 }
3918
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003919 if (ctx == AugLoad) {
3920 switch (stack_count) {
3921 case 0: ADDOP(c, DUP_TOP); break;
3922 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3923 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3924 }
3925 }
3926 else if (ctx == AugStore) {
3927 switch (stack_count) {
3928 case 0: ADDOP(c, ROT_TWO); break;
3929 case 1: ADDOP(c, ROT_THREE); break;
3930 case 2: ADDOP(c, ROT_FOUR); break;
3931 }
3932 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933
3934 switch (ctx) {
3935 case AugLoad: /* fall through to Load */
3936 case Load: op = SLICE; break;
3937 case AugStore:/* fall through to Store */
3938 case Store: op = STORE_SLICE; break;
3939 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003940 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003941 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003942 PyErr_SetString(PyExc_SystemError,
3943 "param invalid in simple slice");
3944 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945 }
3946
3947 ADDOP(c, op + slice_offset);
3948 return 1;
3949}
3950
3951static int
3952compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3953 expr_context_ty ctx)
3954{
3955 switch (s->kind) {
3956 case Ellipsis_kind:
3957 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3958 break;
3959 case Slice_kind:
3960 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003961 case Index_kind:
3962 VISIT(c, expr, s->v.Index.value);
3963 break;
3964 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003965 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003966 PyErr_SetString(PyExc_SystemError,
3967 "extended slice invalid in nested slice");
3968 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003969 }
3970 return 1;
3971}
3972
3973
3974static int
3975compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3976{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003977 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003978 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003979 case Index_kind:
3980 kindname = "index";
3981 if (ctx != AugStore) {
3982 VISIT(c, expr, s->v.Index.value);
3983 }
3984 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003985 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003986 kindname = "ellipsis";
3987 if (ctx != AugStore) {
3988 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3989 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003990 break;
3991 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003992 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003993 if (!s->v.Slice.step)
3994 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003995 if (ctx != AugStore) {
3996 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003997 return 0;
3998 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003999 break;
4000 case ExtSlice_kind:
4001 kindname = "extended slice";
4002 if (ctx != AugStore) {
4003 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
4004 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00004005 slice_ty sub = (slice_ty)asdl_seq_GET(
4006 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004007 if (!compiler_visit_nested_slice(c, sub, ctx))
4008 return 0;
4009 }
4010 ADDOP_I(c, BUILD_TUPLE, n);
4011 }
4012 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00004013 default:
4014 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004015 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00004016 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004018 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004019}
4020
4021/* do depth-first search of basic block graph, starting with block.
4022 post records the block indices in post-order.
4023
4024 XXX must handle implicit jumps from one block to next
4025*/
4026
4027static void
4028dfs(struct compiler *c, basicblock *b, struct assembler *a)
4029{
4030 int i;
4031 struct instr *instr = NULL;
4032
4033 if (b->b_seen)
4034 return;
4035 b->b_seen = 1;
4036 if (b->b_next != NULL)
4037 dfs(c, b->b_next, a);
4038 for (i = 0; i < b->b_iused; i++) {
4039 instr = &b->b_instr[i];
4040 if (instr->i_jrel || instr->i_jabs)
4041 dfs(c, instr->i_target, a);
4042 }
4043 a->a_postorder[a->a_nblocks++] = b;
4044}
4045
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004046static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004047stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4048{
4049 int i;
4050 struct instr *instr;
4051 if (b->b_seen || b->b_startdepth >= depth)
4052 return maxdepth;
4053 b->b_seen = 1;
4054 b->b_startdepth = depth;
4055 for (i = 0; i < b->b_iused; i++) {
4056 instr = &b->b_instr[i];
4057 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
4058 if (depth > maxdepth)
4059 maxdepth = depth;
4060 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4061 if (instr->i_jrel || instr->i_jabs) {
4062 maxdepth = stackdepth_walk(c, instr->i_target,
4063 depth, maxdepth);
4064 if (instr->i_opcode == JUMP_ABSOLUTE ||
4065 instr->i_opcode == JUMP_FORWARD) {
4066 goto out; /* remaining code is dead */
4067 }
4068 }
4069 }
4070 if (b->b_next)
4071 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
4072out:
4073 b->b_seen = 0;
4074 return maxdepth;
4075}
4076
4077/* Find the flow path that needs the largest stack. We assume that
4078 * cycles in the flow graph have no net effect on the stack depth.
4079 */
4080static int
4081stackdepth(struct compiler *c)
4082{
4083 basicblock *b, *entryblock;
4084 entryblock = NULL;
4085 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4086 b->b_seen = 0;
4087 b->b_startdepth = INT_MIN;
4088 entryblock = b;
4089 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00004090 if (!entryblock)
4091 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004092 return stackdepth_walk(c, entryblock, 0, 0);
4093}
4094
4095static int
4096assemble_init(struct assembler *a, int nblocks, int firstlineno)
4097{
4098 memset(a, 0, sizeof(struct assembler));
4099 a->a_lineno = firstlineno;
4100 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4101 if (!a->a_bytecode)
4102 return 0;
4103 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4104 if (!a->a_lnotab)
4105 return 0;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004106 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
4107 PyErr_NoMemory();
4108 return 0;
4109 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004111 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004112 if (!a->a_postorder) {
4113 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004115 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116 return 1;
4117}
4118
4119static void
4120assemble_free(struct assembler *a)
4121{
4122 Py_XDECREF(a->a_bytecode);
4123 Py_XDECREF(a->a_lnotab);
4124 if (a->a_postorder)
4125 PyObject_Free(a->a_postorder);
4126}
4127
4128/* Return the size of a basic block in bytes. */
4129
4130static int
4131instrsize(struct instr *instr)
4132{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004133 if (!instr->i_hasarg)
4134 return 1;
4135 if (instr->i_oparg > 0xffff)
4136 return 6;
4137 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138}
4139
4140static int
4141blocksize(basicblock *b)
4142{
4143 int i;
4144 int size = 0;
4145
4146 for (i = 0; i < b->b_iused; i++)
4147 size += instrsize(&b->b_instr[i]);
4148 return size;
4149}
4150
4151/* All about a_lnotab.
4152
4153c_lnotab is an array of unsigned bytes disguised as a Python string.
4154It is used to map bytecode offsets to source code line #s (when needed
4155for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004156
Tim Peters2a7f3842001-06-09 09:26:21 +00004157The array is conceptually a list of
4158 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004159pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004160
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004161 byte code offset source code line number
4162 0 1
4163 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004164 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004165 350 307
4166 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004167
4168The first trick is that these numbers aren't stored, only the increments
4169from one row to the next (this doesn't really work, but it's a start):
4170
4171 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4172
4173The second trick is that an unsigned byte can't hold negative values, or
4174values larger than 255, so (a) there's a deep assumption that byte code
4175offsets and their corresponding line #s both increase monotonically, and (b)
4176if at least one column jumps by more than 255 from one row to the next, more
4177than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004178from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004179part. A user of c_lnotab desiring to find the source line number
4180corresponding to a bytecode address A should do something like this
4181
4182 lineno = addr = 0
4183 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004184 addr += addr_incr
4185 if addr > A:
4186 return lineno
4187 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004188
4189In order for this to work, when the addr field increments by more than 255,
4190the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00004191increment is < 256. So, in the example above, assemble_lnotab (it used
4192to be called com_set_lineno) should not (as was actually done until 2.2)
4193expand 300, 300 to 255, 255, 45, 45,
4194 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004195*/
4196
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004197static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004199{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200 int d_bytecode, d_lineno;
4201 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00004202 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004203
4204 d_bytecode = a->a_offset - a->a_lineno_off;
4205 d_lineno = i->i_lineno - a->a_lineno;
4206
4207 assert(d_bytecode >= 0);
4208 assert(d_lineno >= 0);
4209
Amaury Forgeot d'Arcbc212102008-02-04 23:51:55 +00004210 if(d_bytecode == 0 && d_lineno == 0)
4211 return 1;
4212
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004213 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004214 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 nbytes = a->a_lnotab_off + 2 * ncodes;
4216 len = PyString_GET_SIZE(a->a_lnotab);
4217 if (nbytes >= len) {
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004218 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004219 len = nbytes;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004220 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221 len *= 2;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004222 else {
4223 PyErr_NoMemory();
4224 return 0;
4225 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004226 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4227 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004228 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004229 lnotab = (unsigned char *)
4230 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004231 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004232 *lnotab++ = 255;
4233 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004235 d_bytecode -= ncodes * 255;
4236 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004237 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004238 assert(d_bytecode <= 255);
4239 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004240 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004241 nbytes = a->a_lnotab_off + 2 * ncodes;
4242 len = PyString_GET_SIZE(a->a_lnotab);
4243 if (nbytes >= len) {
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004244 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245 len = nbytes;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004246 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004247 len *= 2;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004248 else {
4249 PyErr_NoMemory();
4250 return 0;
4251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004252 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4253 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004254 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004255 lnotab = (unsigned char *)
4256 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004258 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004259 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004260 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004261 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004262 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004263 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004264 d_lineno -= ncodes * 255;
4265 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004266 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004267
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004268 len = PyString_GET_SIZE(a->a_lnotab);
4269 if (a->a_lnotab_off + 2 >= len) {
4270 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004271 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004272 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004273 lnotab = (unsigned char *)
4274 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004276 a->a_lnotab_off += 2;
4277 if (d_bytecode) {
4278 *lnotab++ = d_bytecode;
4279 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004280 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004281 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004282 *lnotab++ = 0;
4283 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285 a->a_lineno = i->i_lineno;
4286 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004287 return 1;
4288}
4289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004290/* assemble_emit()
4291 Extend the bytecode with a new instruction.
4292 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004293*/
4294
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004295static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004296assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004297{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004298 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00004299 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004300 char *code;
4301
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004302 size = instrsize(i);
4303 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004304 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004305 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004306 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004307 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004308 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004309 if (a->a_offset + size >= len) {
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004310 if (len > PY_SSIZE_T_MAX / 2)
4311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004312 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004313 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004314 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004315 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4316 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004317 if (size == 6) {
4318 assert(i->i_hasarg);
4319 *code++ = (char)EXTENDED_ARG;
4320 *code++ = ext & 0xff;
4321 *code++ = ext >> 8;
4322 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004323 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004324 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004325 if (i->i_hasarg) {
4326 assert(size == 3 || size == 6);
4327 *code++ = arg & 0xff;
4328 *code++ = arg >> 8;
4329 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004330 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004331}
4332
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004333static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004334assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004335{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004336 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004337 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004338 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004340 /* Compute the size of each block and fixup jump args.
4341 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004342start:
4343 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004345 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346 bsize = blocksize(b);
4347 b->b_offset = totsize;
4348 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004349 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004350 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004351 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4352 bsize = b->b_offset;
4353 for (i = 0; i < b->b_iused; i++) {
4354 struct instr *instr = &b->b_instr[i];
4355 /* Relative jumps are computed relative to
4356 the instruction pointer after fetching
4357 the jump instruction.
4358 */
4359 bsize += instrsize(instr);
4360 if (instr->i_jabs)
4361 instr->i_oparg = instr->i_target->b_offset;
4362 else if (instr->i_jrel) {
4363 int delta = instr->i_target->b_offset - bsize;
4364 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004365 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004366 else
4367 continue;
4368 if (instr->i_oparg > 0xffff)
4369 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004370 }
4371 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004372
4373 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004374 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004375 with a better solution.
4376
4377 In the meantime, should the goto be dropped in favor
4378 of a loop?
4379
4380 The issue is that in the first loop blocksize() is called
4381 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004382 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004383 i_oparg is calculated in the second loop above.
4384
4385 So we loop until we stop seeing new EXTENDED_ARGs.
4386 The only EXTENDED_ARGs that could be popping up are
4387 ones in jump instructions. So this should converge
4388 fairly quickly.
4389 */
4390 if (last_extended_arg_count != extended_arg_count) {
4391 last_extended_arg_count = extended_arg_count;
4392 goto start;
4393 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004394}
4395
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004396static PyObject *
4397dict_keys_inorder(PyObject *dict, int offset)
4398{
4399 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004400 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004401
4402 tuple = PyTuple_New(size);
4403 if (tuple == NULL)
4404 return NULL;
4405 while (PyDict_Next(dict, &pos, &k, &v)) {
4406 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004407 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004408 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004409 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004410 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004411 PyTuple_SET_ITEM(tuple, i - offset, k);
4412 }
4413 return tuple;
4414}
4415
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004416static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004417compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004418{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004419 PySTEntryObject *ste = c->u->u_ste;
4420 int flags = 0, n;
4421 if (ste->ste_type != ModuleBlock)
4422 flags |= CO_NEWLOCALS;
4423 if (ste->ste_type == FunctionBlock) {
4424 if (!ste->ste_unoptimized)
4425 flags |= CO_OPTIMIZED;
4426 if (ste->ste_nested)
4427 flags |= CO_NESTED;
4428 if (ste->ste_generator)
4429 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004430 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004431 if (ste->ste_varargs)
4432 flags |= CO_VARARGS;
4433 if (ste->ste_varkeywords)
4434 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004435 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004437
4438 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004439 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004440
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004441 n = PyDict_Size(c->u->u_freevars);
4442 if (n < 0)
4443 return -1;
4444 if (n == 0) {
4445 n = PyDict_Size(c->u->u_cellvars);
4446 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004447 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004448 if (n == 0) {
4449 flags |= CO_NOFREE;
4450 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004451 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004452
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004453 return flags;
4454}
4455
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004456static PyCodeObject *
4457makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004458{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004459 PyObject *tmp;
4460 PyCodeObject *co = NULL;
4461 PyObject *consts = NULL;
4462 PyObject *names = NULL;
4463 PyObject *varnames = NULL;
4464 PyObject *filename = NULL;
4465 PyObject *name = NULL;
4466 PyObject *freevars = NULL;
4467 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004468 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004469 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004470
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004471 tmp = dict_keys_inorder(c->u->u_consts, 0);
4472 if (!tmp)
4473 goto error;
4474 consts = PySequence_List(tmp); /* optimize_code requires a list */
4475 Py_DECREF(tmp);
4476
4477 names = dict_keys_inorder(c->u->u_names, 0);
4478 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4479 if (!consts || !names || !varnames)
4480 goto error;
4481
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004482 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4483 if (!cellvars)
4484 goto error;
4485 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4486 if (!freevars)
4487 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004488 filename = PyString_FromString(c->c_filename);
4489 if (!filename)
4490 goto error;
4491
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004492 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004493 flags = compute_code_flags(c);
4494 if (flags < 0)
4495 goto error;
4496
4497 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4498 if (!bytecode)
4499 goto error;
4500
4501 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4502 if (!tmp)
4503 goto error;
4504 Py_DECREF(consts);
4505 consts = tmp;
4506
4507 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4508 bytecode, consts, names, varnames,
4509 freevars, cellvars,
4510 filename, c->u->u_name,
4511 c->u->u_firstlineno,
4512 a->a_lnotab);
4513 error:
4514 Py_XDECREF(consts);
4515 Py_XDECREF(names);
4516 Py_XDECREF(varnames);
4517 Py_XDECREF(filename);
4518 Py_XDECREF(name);
4519 Py_XDECREF(freevars);
4520 Py_XDECREF(cellvars);
4521 Py_XDECREF(bytecode);
4522 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004523}
4524
Neal Norwitz4ffedad2006-08-04 04:58:47 +00004525
4526/* For debugging purposes only */
4527#if 0
4528static void
4529dump_instr(const struct instr *i)
4530{
4531 const char *jrel = i->i_jrel ? "jrel " : "";
4532 const char *jabs = i->i_jabs ? "jabs " : "";
4533 char arg[128];
4534
4535 *arg = '\0';
4536 if (i->i_hasarg)
4537 sprintf(arg, "arg: %d ", i->i_oparg);
4538
4539 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4540 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4541}
4542
4543static void
4544dump_basicblock(const basicblock *b)
4545{
4546 const char *seen = b->b_seen ? "seen " : "";
4547 const char *b_return = b->b_return ? "return " : "";
4548 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4549 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4550 if (b->b_instr) {
4551 int i;
4552 for (i = 0; i < b->b_iused; i++) {
4553 fprintf(stderr, " [%02d] ", i);
4554 dump_instr(b->b_instr + i);
4555 }
4556 }
4557}
4558#endif
4559
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004560static PyCodeObject *
4561assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004562{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004563 basicblock *b, *entryblock;
4564 struct assembler a;
4565 int i, j, nblocks;
4566 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004567
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004568 /* Make sure every block that falls off the end returns None.
4569 XXX NEXT_BLOCK() isn't quite right, because if the last
4570 block ends with a jump or return b_next shouldn't set.
4571 */
4572 if (!c->u->u_curblock->b_return) {
4573 NEXT_BLOCK(c);
4574 if (addNone)
4575 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4576 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004577 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004579 nblocks = 0;
4580 entryblock = NULL;
4581 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4582 nblocks++;
4583 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004584 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004585
Neal Norwitzed657552006-07-10 00:04:44 +00004586 /* Set firstlineno if it wasn't explicitly set. */
4587 if (!c->u->u_firstlineno) {
4588 if (entryblock && entryblock->b_instr)
4589 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4590 else
4591 c->u->u_firstlineno = 1;
4592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004593 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4594 goto error;
4595 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004596
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004597 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004598 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004599
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004600 /* Emit code in reverse postorder from dfs. */
4601 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004602 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004603 for (j = 0; j < b->b_iused; j++)
4604 if (!assemble_emit(&a, &b->b_instr[j]))
4605 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004606 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004607
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004608 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4609 goto error;
4610 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4611 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004612
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004613 co = makecode(c, &a);
4614 error:
4615 assemble_free(&a);
4616 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004617}