blob: 9547992957eef11697f639c650819ed27e9daaa6 [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
8 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
10 * 4. Assemble the basic blocks into final code. See assemble() in
11 * this file.
12 *
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 *
16 * CAUTION: The VISIT_* macros abort the current function when they encounter
17 * a problem. So don't invoke them when there is memory which needs to be
18 * released. Code blocks are OK, as the compiler structure takes care of
19 * 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/*
36 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000038 character encodings aren't handled
Jeremy Hyltone36f7782001-01-19 03:21:30 +000039
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000040 ref leaks in interpreter when press return on empty line
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000042 opcode_stack_effect() function should be reviewed since stack depth bugs
43 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045 Dead code is being generated (i.e. after unconditional jumps).
46*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000047
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000048#define DEFAULT_BLOCK_SIZE 16
49#define DEFAULT_BLOCKS 8
50#define DEFAULT_CODE_SIZE 128
51#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000054 unsigned i_jabs : 1;
55 unsigned i_jrel : 1;
56 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057 unsigned char i_opcode;
58 int i_oparg;
59 struct basicblock_ *i_target; /* target block (if jump instruction) */
60 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000061};
62
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000063typedef struct basicblock_ {
64 /* next block in the list of blocks for a unit (don't confuse with
65 * b_next) */
66 struct basicblock_ *b_list;
67 /* number of instructions used */
68 int b_iused;
69 /* length of instruction array (b_instr) */
70 int b_ialloc;
71 /* pointer to an array of instructions, initially NULL */
72 struct instr *b_instr;
73 /* If b_next is non-NULL, it is a pointer to the next
74 block reached by normal control flow. */
75 struct basicblock_ *b_next;
76 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000079 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000080 /* depth of stack upon entry of block, computed by stackdepth() */
81 int b_startdepth;
82 /* instruction offset for block, computed by assemble_jump_offsets() */
83 int b_offset;
84} basicblock;
85
86/* fblockinfo tracks the current frame block.
87
88 A frame block is used to handle loops, try/except, and try/finally.
89 It's called a frame block to distinguish it from a basic block in the
90 compiler IR.
91*/
92
93enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
94
95struct fblockinfo {
96 enum fblocktype fb_type;
97 basicblock *fb_block;
98};
99
100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
104 PySTEntryObject *u_ste;
105
106 PyObject *u_name;
107 /* The following fields are dicts that map objects to
108 the index of them in co_XXX. The index is used as
109 the argument for opcodes that refer to those collections.
110 */
111 PyObject *u_consts; /* all constants */
112 PyObject *u_names; /* all names */
113 PyObject *u_varnames; /* local variables */
114 PyObject *u_cellvars; /* cell variables */
115 PyObject *u_freevars; /* free variables */
116
117 PyObject *u_private; /* for private name mangling */
118
119 int u_argcount; /* number of arguments for block */
120 basicblock *u_blocks; /* pointer to list of blocks */
121 basicblock *u_curblock; /* pointer to current block */
122 int u_tmpname; /* temporary variables for list comps */
123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
128 int u_lineno; /* the lineno for the current stmt */
129 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
135 The u pointer points to the current compilation unit, while units
136 for enclosing blocks are stored in c_stack. The u and c_stack are
137 managed by compiler_enter_scope() and compiler_exit_scope().
138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
144 PyCompilerFlags *c_flags;
145
146 int c_interactive;
147 int c_nestlevel;
148
149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
151 char *c_encoding; /* source encoding (a borrowed reference) */
Neal Norwitzadb69fc2005-12-17 20:54:49 +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 */
157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
162 int a_lineno; /* last lineno of emitted instruction */
163 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 *);
190
191static int inplace_binop(struct compiler *, operator_ty);
192static int expr_constant(expr_ty e);
193
Guido van Rossumc2e20742006-02-27 22:32:47 +0000194static int compiler_with(struct compiler *, stmt_ty);
195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static PyCodeObject *assemble(struct compiler *, int addNone);
197static PyObject *__doc__;
198
199PyObject *
200_Py_Mangle(PyObject *private, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000201{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Name mangling: __private becomes _classname__private.
203 This is independent from how the name is used. */
204 const char *p, *name = PyString_AsString(ident);
205 char *buffer;
206 size_t nlen, plen;
207 if (private == NULL || name == NULL || name[0] != '_' || name[1] != '_') {
208 Py_INCREF(ident);
209 return ident;
210 }
211 p = PyString_AsString(private);
212 nlen = strlen(name);
213 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
214 Py_INCREF(ident);
215 return ident; /* Don't mangle __whatever__ */
216 }
217 /* Strip leading underscores from class name */
218 while (*p == '_')
219 p++;
220 if (*p == '\0') {
221 Py_INCREF(ident);
222 return ident; /* Don't mangle if class is just underscores */
223 }
224 plen = strlen(p);
225 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
226 if (!ident)
227 return 0;
228 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
229 buffer = PyString_AS_STRING(ident);
230 buffer[0] = '_';
231 strncpy(buffer+1, p, plen);
232 strcpy(buffer+1+plen, name);
233 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000234}
235
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000236static int
237compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000238{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241 c->c_stack = PyList_New(0);
242 if (!c->c_stack)
243 return 0;
244
245 return 1;
246}
247
248PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000249PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
250 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251{
252 struct compiler c;
253 PyCodeObject *co = NULL;
254 PyCompilerFlags local_flags;
255 int merged;
256
257 if (!__doc__) {
258 __doc__ = PyString_InternFromString("__doc__");
259 if (!__doc__)
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000260 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261 }
262
263 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000264 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265 c.c_filename = filename;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000266 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267 c.c_future = PyFuture_FromAST(mod, filename);
268 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000269 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 if (!flags) {
271 local_flags.cf_flags = 0;
272 flags = &local_flags;
273 }
274 merged = c.c_future->ff_features | flags->cf_flags;
275 c.c_future->ff_features = merged;
276 flags->cf_flags = merged;
277 c.c_flags = flags;
278 c.c_nestlevel = 0;
279
280 c.c_st = PySymtable_Build(mod, filename, c.c_future);
281 if (c.c_st == NULL) {
282 if (!PyErr_Occurred())
283 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000284 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285 }
286
287 /* XXX initialize to NULL for now, need to handle */
288 c.c_encoding = NULL;
289
290 co = compiler_mod(&c, mod);
291
Thomas Wouters1175c432006-02-27 22:49:54 +0000292 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000294 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295 return co;
296}
297
298PyCodeObject *
299PyNode_Compile(struct _node *n, const char *filename)
300{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000301 PyCodeObject *co = NULL;
Fredrik Lundh93d69a72005-12-18 15:44:21 +0000302 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000303 mod_ty mod = PyAST_FromNode(n, NULL, filename, arena);
304 if (mod)
305 co = PyAST_Compile(mod, filename, NULL, arena);
306 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000307 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000308}
309
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000310static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000312{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313 if (c->c_st)
314 PySymtable_Free(c->c_st);
315 if (c->c_future)
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000316 PyMem_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318}
319
Guido van Rossum79f25d91997-04-29 20:08:16 +0000320static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000322{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000323 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324 PyObject *v, *k, *dict = PyDict_New();
Guido van Rossumd076c731998-10-07 19:42:25 +0000325
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326 n = PyList_Size(list);
327 for (i = 0; i < n; i++) {
328 v = PyInt_FromLong(i);
329 if (!v) {
330 Py_DECREF(dict);
331 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000332 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333 k = PyList_GET_ITEM(list, i);
334 k = Py_BuildValue("(OO)", k, k->ob_type);
335 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
336 Py_XDECREF(k);
337 Py_DECREF(v);
338 Py_DECREF(dict);
339 return NULL;
340 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000341 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000343 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344 return dict;
345}
346
347/* Return new dict containing names from src that match scope(s).
348
349 src is a symbol table dictionary. If the scope of a name matches
350 either scope_type or flag is set, insert it into the new dict. The
351 values are integers, starting at offset and increasing by one for
352 each key.
353*/
354
355static PyObject *
356dictbytype(PyObject *src, int scope_type, int flag, int offset)
357{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000358 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359 PyObject *k, *v, *dest = PyDict_New();
360
361 assert(offset >= 0);
362 if (dest == NULL)
363 return NULL;
364
365 while (PyDict_Next(src, &pos, &k, &v)) {
366 /* XXX this should probably be a macro in symtable.h */
367 assert(PyInt_Check(v));
368 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
369
370 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
371 PyObject *tuple, *item = PyInt_FromLong(i);
372 if (item == NULL) {
373 Py_DECREF(dest);
374 return NULL;
375 }
376 i++;
377 tuple = Py_BuildValue("(OO)", k, k->ob_type);
378 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
379 Py_DECREF(item);
380 Py_DECREF(dest);
381 Py_XDECREF(tuple);
382 return NULL;
383 }
384 Py_DECREF(item);
385 Py_DECREF(tuple);
386 }
387 }
388 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000389}
390
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000391/* Begin: Peephole optimizations ----------------------------------------- */
392
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000393#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
394#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000395#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
396#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000397#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000398#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
399#define ISBASICBLOCK(blocks, start, bytes) (blocks[start]==blocks[start+bytes-1])
400
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000401/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
402 with LOAD_CONST (c1, c2, ... cn).
403 The consts table must still be in list form so that the
404 new constant (c1, c2, ... cn) can be appended.
405 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000406 Bails out with no change if one or more of the LOAD_CONSTs is missing.
407 Also works for BUILD_LIST when followed by an "in" or "not in" test.
408*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000409static int
410tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
411{
412 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000414
415 /* Pre-conditions */
416 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000417 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000419 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000420 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000421
422 /* Buildup new tuple of constants */
423 newconst = PyTuple_New(n);
424 if (newconst == NULL)
425 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000426 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000427 for (i=0 ; i<n ; i++) {
428 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000429 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000430 constant = PyList_GET_ITEM(consts, arg);
431 Py_INCREF(constant);
432 PyTuple_SET_ITEM(newconst, i, constant);
433 }
434
435 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000436 if (PyList_Append(consts, newconst)) {
437 Py_DECREF(newconst);
438 return 0;
439 }
440 Py_DECREF(newconst);
441
442 /* Write NOPs over old LOAD_CONSTS and
443 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
444 memset(codestr, NOP, n*3);
445 codestr[n*3] = LOAD_CONST;
446 SETARG(codestr, (n*3), len_consts);
447 return 1;
448}
449
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000450/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
451 with LOAD_CONST binop(c1,c2)
452 The consts table must still be in list form so that the
453 new constant can be appended.
454 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000455 Abandons the transformation if the folding fails (i.e. 1+'a').
456 If the new constant is a sequence, only folds when the size
457 is below a threshold value. That keeps pyc files from
458 becoming large in the presence of code like: (None,)*1000.
459*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000460static int
461fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
462{
463 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000464 Py_ssize_t len_consts, size;
465 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000466
467 /* Pre-conditions */
468 assert(PyList_CheckExact(consts));
469 assert(codestr[0] == LOAD_CONST);
470 assert(codestr[3] == LOAD_CONST);
471
472 /* Create new constant */
473 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
474 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
475 opcode = codestr[6];
476 switch (opcode) {
477 case BINARY_POWER:
478 newconst = PyNumber_Power(v, w, Py_None);
479 break;
480 case BINARY_MULTIPLY:
481 newconst = PyNumber_Multiply(v, w);
482 break;
483 case BINARY_DIVIDE:
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000484 /* Cannot fold this operation statically since
485 the result can depend on the run-time presence of the -Qnew flag */
Armin Rigo664b43b2005-01-07 18:10:51 +0000486 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000487 case BINARY_TRUE_DIVIDE:
488 newconst = PyNumber_TrueDivide(v, w);
489 break;
490 case BINARY_FLOOR_DIVIDE:
491 newconst = PyNumber_FloorDivide(v, w);
492 break;
493 case BINARY_MODULO:
494 newconst = PyNumber_Remainder(v, w);
495 break;
496 case BINARY_ADD:
497 newconst = PyNumber_Add(v, w);
498 break;
499 case BINARY_SUBTRACT:
500 newconst = PyNumber_Subtract(v, w);
501 break;
502 case BINARY_SUBSCR:
503 newconst = PyObject_GetItem(v, w);
504 break;
505 case BINARY_LSHIFT:
506 newconst = PyNumber_Lshift(v, w);
507 break;
508 case BINARY_RSHIFT:
509 newconst = PyNumber_Rshift(v, w);
510 break;
511 case BINARY_AND:
512 newconst = PyNumber_And(v, w);
513 break;
514 case BINARY_XOR:
515 newconst = PyNumber_Xor(v, w);
516 break;
517 case BINARY_OR:
518 newconst = PyNumber_Or(v, w);
519 break;
520 default:
521 /* Called with an unknown opcode */
Neal Norwitz4737b232005-11-19 23:58:29 +0000522 PyErr_Format(PyExc_SystemError,
523 "unexpected binary operation %d on a constant",
524 opcode);
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000525 return 0;
526 }
527 if (newconst == NULL) {
528 PyErr_Clear();
529 return 0;
530 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000531 size = PyObject_Size(newconst);
532 if (size == -1)
533 PyErr_Clear();
534 else if (size > 20) {
535 Py_DECREF(newconst);
536 return 0;
537 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000538
539 /* Append folded constant into consts table */
540 len_consts = PyList_GET_SIZE(consts);
541 if (PyList_Append(consts, newconst)) {
542 Py_DECREF(newconst);
543 return 0;
544 }
545 Py_DECREF(newconst);
546
547 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
548 memset(codestr, NOP, 4);
549 codestr[4] = LOAD_CONST;
550 SETARG(codestr, 4, len_consts);
551 return 1;
552}
553
Raymond Hettinger80121492005-02-20 12:41:32 +0000554static int
555fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
556{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000557 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000558 Py_ssize_t len_consts;
559 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000560
561 /* Pre-conditions */
562 assert(PyList_CheckExact(consts));
563 assert(codestr[0] == LOAD_CONST);
564
565 /* Create new constant */
566 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
567 opcode = codestr[3];
568 switch (opcode) {
569 case UNARY_NEGATIVE:
Raymond Hettingere63a0782005-02-23 13:37:55 +0000570 /* Preserve the sign of -0.0 */
571 if (PyObject_IsTrue(v) == 1)
572 newconst = PyNumber_Negative(v);
Raymond Hettinger80121492005-02-20 12:41:32 +0000573 break;
574 case UNARY_CONVERT:
575 newconst = PyObject_Repr(v);
576 break;
577 case UNARY_INVERT:
578 newconst = PyNumber_Invert(v);
579 break;
580 default:
581 /* Called with an unknown opcode */
Neal Norwitz4737b232005-11-19 23:58:29 +0000582 PyErr_Format(PyExc_SystemError,
583 "unexpected unary operation %d on a constant",
584 opcode);
Raymond Hettinger80121492005-02-20 12:41:32 +0000585 return 0;
586 }
587 if (newconst == NULL) {
588 PyErr_Clear();
589 return 0;
590 }
591
592 /* Append folded constant into consts table */
593 len_consts = PyList_GET_SIZE(consts);
594 if (PyList_Append(consts, newconst)) {
595 Py_DECREF(newconst);
596 return 0;
597 }
598 Py_DECREF(newconst);
599
600 /* Write NOP LOAD_CONST newconst */
601 codestr[0] = NOP;
602 codestr[1] = LOAD_CONST;
603 SETARG(codestr, 1, len_consts);
604 return 1;
605}
606
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000607static unsigned int *
608markblocks(unsigned char *code, int len)
609{
610 unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000611 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000612
613 if (blocks == NULL)
614 return NULL;
615 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000616
617 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000618 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
619 opcode = code[i];
620 switch (opcode) {
621 case FOR_ITER:
622 case JUMP_FORWARD:
623 case JUMP_IF_FALSE:
624 case JUMP_IF_TRUE:
625 case JUMP_ABSOLUTE:
626 case CONTINUE_LOOP:
627 case SETUP_LOOP:
628 case SETUP_EXCEPT:
629 case SETUP_FINALLY:
630 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000631 blocks[j] = 1;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000632 break;
633 }
634 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000635 /* Build block numbers in the second pass */
636 for (i=0 ; i<len ; i++) {
637 blockcnt += blocks[i]; /* increment blockcnt over labels */
638 blocks[i] = blockcnt;
639 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000640 return blocks;
641}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000642
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000643/* Perform basic peephole optimizations to components of a code object.
644 The consts object should still be in list form to allow new constants
645 to be appended.
646
647 To keep the optimizer simple, it bails out (does nothing) for code
648 containing extended arguments or that has a length over 32,700. That
649 allows us to avoid overflow and sign issues. Likewise, it bails when
650 the lineno table has complex encoding for gaps >= 255.
651
652 Optimizations are restricted to simple transformations occuring within a
653 single basic block. All transformations keep the code size the same or
654 smaller. For those that reduce size, the gaps are initially filled with
655 NOPs. Later those NOPs are removed and the jump addresses retargeted in
656 a single pass. Line numbering is adjusted accordingly. */
657
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000658static PyObject *
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000659optimize_code(PyObject *code, PyObject* consts, PyObject *names, PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000660{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000661 Py_ssize_t i, j, codelen;
662 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000663 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000664 unsigned char *codestr = NULL;
665 unsigned char *lineno;
666 int *addrmap = NULL;
667 int new_line, cum_orig_line, last_line, tabsiz;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000668 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONST codes */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000669 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000670 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000671
Raymond Hettingereffb3932004-10-30 08:55:08 +0000672 /* Bail out if an exception is set */
673 if (PyErr_Occurred())
674 goto exitUnchanged;
675
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000676 /* Bypass optimization when the lineno table is too complex */
677 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000678 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000679 tabsiz = PyString_GET_SIZE(lineno_obj);
680 if (memchr(lineno, 255, tabsiz) != NULL)
681 goto exitUnchanged;
682
Raymond Hettingera12fa142004-08-24 04:34:16 +0000683 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000684 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000685 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000686 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000687 goto exitUnchanged;
688
689 /* Make a modifiable copy of the code string */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000690 codestr = PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000691 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000692 goto exitUnchanged;
693 codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000694
Raymond Hettinger07359a72005-02-21 20:03:14 +0000695 /* Verify that RETURN_VALUE terminates the codestring. This allows
696 the various transformation patterns to look ahead several
697 instructions without additional checks to make sure they are not
698 looking beyond the end of the code string.
699 */
700 if (codestr[codelen-1] != RETURN_VALUE)
701 goto exitUnchanged;
702
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000703 /* Mapping to new jump targets after NOPs are removed */
704 addrmap = PyMem_Malloc(codelen * sizeof(int));
705 if (addrmap == NULL)
706 goto exitUnchanged;
707
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000708 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000709 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000710 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000711 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000712
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000713 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000714 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000715
716 lastlc = cumlc;
717 cumlc = 0;
718
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000719 switch (opcode) {
720
Raymond Hettinger43ea47f2004-06-24 09:25:39 +0000721 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000722 with JUMP_IF_TRUE POP_TOP */
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000723 case UNARY_NOT:
724 if (codestr[i+1] != JUMP_IF_FALSE ||
725 codestr[i+4] != POP_TOP ||
726 !ISBASICBLOCK(blocks,i,5))
727 continue;
728 tgt = GETJUMPTGT(codestr, (i+1));
729 if (codestr[tgt] != POP_TOP)
730 continue;
Raymond Hettinger43ea47f2004-06-24 09:25:39 +0000731 j = GETARG(codestr, i+1) + 1;
732 codestr[i] = JUMP_IF_TRUE;
733 SETARG(codestr, i, j);
734 codestr[i+3] = POP_TOP;
735 codestr[i+4] = NOP;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000736 break;
737
738 /* not a is b --> a is not b
739 not a in b --> a not in b
740 not a is not b --> a is b
Raymond Hettingerb615bf02005-02-10 01:42:32 +0000741 not a not in b --> a in b
Raymond Hettingera1645742005-02-06 22:05:42 +0000742 */
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000743 case COMPARE_OP:
744 j = GETARG(codestr, i);
745 if (j < 6 || j > 9 ||
746 codestr[i+3] != UNARY_NOT ||
747 !ISBASICBLOCK(blocks,i,4))
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000748 continue;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000749 SETARG(codestr, i, (j^1));
750 codestr[i+3] = NOP;
Tim Petersdb5860b2004-07-17 05:00:52 +0000751 break;
752
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000753 /* Replace LOAD_GLOBAL/LOAD_NAME None with LOAD_CONST None */
754 case LOAD_NAME:
755 case LOAD_GLOBAL:
756 j = GETARG(codestr, i);
757 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
758 if (name == NULL || strcmp(name, "None") != 0)
759 continue;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000760 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
761 if (PyList_GET_ITEM(consts, j) == Py_None) {
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000762 codestr[i] = LOAD_CONST;
763 SETARG(codestr, i, j);
Raymond Hettinger5dec0962004-11-02 04:20:10 +0000764 cumlc = lastlc + 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000765 break;
766 }
767 }
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000768 break;
769
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000770 /* Skip over LOAD_CONST trueconst JUMP_IF_FALSE xx POP_TOP */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000771 case LOAD_CONST:
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000772 cumlc = lastlc + 1;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000773 j = GETARG(codestr, i);
774 if (codestr[i+3] != JUMP_IF_FALSE ||
775 codestr[i+6] != POP_TOP ||
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000776 !ISBASICBLOCK(blocks,i,7) ||
777 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000778 continue;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000779 memset(codestr+i, NOP, 7);
Raymond Hettinger5dec0962004-11-02 04:20:10 +0000780 cumlc = 0;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000781 break;
782
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000783 /* Try to fold tuples of constants (includes a case for lists
784 which are only used for "in" and "not in" tests).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000785 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000786 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
787 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000788 case BUILD_TUPLE:
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000789 case BUILD_LIST:
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000790 j = GETARG(codestr, i);
791 h = i - 3 * j;
792 if (h >= 0 &&
Raymond Hettingereffb3932004-10-30 08:55:08 +0000793 j <= lastlc &&
Brett Cannon5dc8ced2005-03-03 07:01:48 +0000794 ((opcode == BUILD_TUPLE &&
795 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
796 (opcode == BUILD_LIST &&
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000797 codestr[i+3]==COMPARE_OP &&
798 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
Brett Cannon5dc8ced2005-03-03 07:01:48 +0000799 (GETARG(codestr,i+3)==6 ||
800 GETARG(codestr,i+3)==7))) &&
801 tuple_of_constants(&codestr[h], j, consts)) {
Raymond Hettinger5dec0962004-11-02 04:20:10 +0000802 assert(codestr[i] == LOAD_CONST);
803 cumlc = 1;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000804 break;
805 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000806 if (codestr[i+3] != UNPACK_SEQUENCE ||
807 !ISBASICBLOCK(blocks,i,6) ||
808 j != GETARG(codestr, i+3))
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000809 continue;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000810 if (j == 1) {
811 memset(codestr+i, NOP, 6);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000812 } else if (j == 2) {
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000813 codestr[i] = ROT_TWO;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000814 memset(codestr+i+1, NOP, 5);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000815 } else if (j == 3) {
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000816 codestr[i] = ROT_THREE;
817 codestr[i+1] = ROT_TWO;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000818 memset(codestr+i+2, NOP, 4);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000819 }
820 break;
821
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000822 /* Fold binary ops on constants.
823 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
824 case BINARY_POWER:
825 case BINARY_MULTIPLY:
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000826 case BINARY_TRUE_DIVIDE:
827 case BINARY_FLOOR_DIVIDE:
828 case BINARY_MODULO:
829 case BINARY_ADD:
830 case BINARY_SUBTRACT:
831 case BINARY_SUBSCR:
832 case BINARY_LSHIFT:
833 case BINARY_RSHIFT:
834 case BINARY_AND:
835 case BINARY_XOR:
836 case BINARY_OR:
837 if (lastlc >= 2 &&
838 ISBASICBLOCK(blocks, i-6, 7) &&
839 fold_binops_on_constants(&codestr[i-6], consts)) {
840 i -= 2;
841 assert(codestr[i] == LOAD_CONST);
842 cumlc = 1;
843 }
844 break;
845
Raymond Hettinger80121492005-02-20 12:41:32 +0000846 /* Fold unary ops on constants.
847 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
848 case UNARY_NEGATIVE:
849 case UNARY_CONVERT:
850 case UNARY_INVERT:
851 if (lastlc >= 1 &&
852 ISBASICBLOCK(blocks, i-3, 4) &&
853 fold_unaryops_on_constants(&codestr[i-3], consts)) {
854 i -= 2;
855 assert(codestr[i] == LOAD_CONST);
856 cumlc = 1;
857 }
858 break;
859
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000860 /* Simplify conditional jump to conditional jump where the
861 result of the first test implies the success of a similar
862 test or the failure of the opposite test.
863 Arises in code like:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000864 "if a and b:"
865 "if a or b:"
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000866 "a and b or c"
Armin Rigod7bcf4d2004-10-30 21:08:59 +0000867 "(a and b) and c"
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000868 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
Raymond Hettinger65d3c052004-08-25 15:15:56 +0000869 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
870 where y+3 is the instruction following the second test.
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000871 */
872 case JUMP_IF_FALSE:
873 case JUMP_IF_TRUE:
874 tgt = GETJUMPTGT(codestr, i);
875 j = codestr[tgt];
876 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
877 if (j == opcode) {
878 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
879 SETARG(codestr, i, tgttgt);
880 } else {
881 tgt -= i;
882 SETARG(codestr, i, tgt);
883 }
884 break;
885 }
886 /* Intentional fallthrough */
887
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000888 /* Replace jumps to unconditional jumps */
Raymond Hettinger255a3d02003-04-15 10:35:07 +0000889 case FOR_ITER:
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000890 case JUMP_FORWARD:
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000891 case JUMP_ABSOLUTE:
892 case CONTINUE_LOOP:
893 case SETUP_LOOP:
894 case SETUP_EXCEPT:
895 case SETUP_FINALLY:
896 tgt = GETJUMPTGT(codestr, i);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000897 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000898 continue;
899 tgttgt = GETJUMPTGT(codestr, tgt);
900 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
901 opcode = JUMP_ABSOLUTE;
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000902 if (!ABSOLUTE_JUMP(opcode))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000903 tgttgt -= i + 3; /* Calc relative jump addr */
904 if (tgttgt < 0) /* No backward relative jumps */
905 continue;
906 codestr[i] = opcode;
907 SETARG(codestr, i, tgttgt);
908 break;
909
910 case EXTENDED_ARG:
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000911 goto exitUnchanged;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000912
913 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
914 case RETURN_VALUE:
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000915 if (i+4 >= codelen ||
916 codestr[i+4] != RETURN_VALUE ||
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000917 !ISBASICBLOCK(blocks,i,5))
918 continue;
919 memset(codestr+i+1, NOP, 4);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000920 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000921 }
922 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000923
924 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000925 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
926 addrmap[i] = i - nops;
927 if (codestr[i] == NOP)
928 nops++;
929 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000930 cum_orig_line = 0;
931 last_line = 0;
932 for (i=0 ; i < tabsiz ; i+=2) {
933 cum_orig_line += lineno[i];
934 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000935 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000936 lineno[i] =((unsigned char)(new_line - last_line));
937 last_line = new_line;
938 }
939
940 /* Remove NOPs and fixup jump targets */
941 for (i=0, h=0 ; i<codelen ; ) {
942 opcode = codestr[i];
943 switch (opcode) {
944 case NOP:
945 i++;
946 continue;
947
948 case JUMP_ABSOLUTE:
949 case CONTINUE_LOOP:
950 j = addrmap[GETARG(codestr, i)];
951 SETARG(codestr, i, j);
952 break;
953
954 case FOR_ITER:
955 case JUMP_FORWARD:
956 case JUMP_IF_FALSE:
957 case JUMP_IF_TRUE:
958 case SETUP_LOOP:
959 case SETUP_EXCEPT:
960 case SETUP_FINALLY:
961 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
962 SETARG(codestr, i, j);
963 break;
964 }
965 adj = CODESIZE(opcode);
966 while (adj--)
967 codestr[h++] = codestr[i++];
968 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000969 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000970
971 code = PyString_FromStringAndSize((char *)codestr, h);
972 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000973 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000974 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000975 return code;
976
977exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000978 if (blocks != NULL)
979 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000980 if (addrmap != NULL)
981 PyMem_Free(addrmap);
982 if (codestr != NULL)
983 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000984 Py_INCREF(code);
985 return code;
986}
987
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000988/* End: Peephole optimizations ----------------------------------------- */
989
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990/*
991
992Leave this debugging code for just a little longer.
993
994static void
995compiler_display_symbols(PyObject *name, PyObject *symbols)
996{
997 PyObject *key, *value;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000998 int flags;
999 Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
1001 fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1002 while (PyDict_Next(symbols, &pos, &key, &value)) {
1003 flags = PyInt_AsLong(value);
1004 fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1005 if (flags & DEF_GLOBAL)
1006 fprintf(stderr, " declared_global");
1007 if (flags & DEF_LOCAL)
1008 fprintf(stderr, " local");
1009 if (flags & DEF_PARAM)
1010 fprintf(stderr, " param");
1011 if (flags & DEF_STAR)
1012 fprintf(stderr, " stararg");
1013 if (flags & DEF_DOUBLESTAR)
1014 fprintf(stderr, " starstar");
1015 if (flags & DEF_INTUPLE)
1016 fprintf(stderr, " tuple");
1017 if (flags & DEF_FREE)
1018 fprintf(stderr, " free");
1019 if (flags & DEF_FREE_GLOBAL)
1020 fprintf(stderr, " global");
1021 if (flags & DEF_FREE_CLASS)
1022 fprintf(stderr, " free/class");
1023 if (flags & DEF_IMPORT)
1024 fprintf(stderr, " import");
1025 fprintf(stderr, "\n");
1026 }
1027 fprintf(stderr, "\n");
1028}
1029*/
1030
1031static void
1032compiler_unit_check(struct compiler_unit *u)
1033{
1034 basicblock *block;
1035 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1036 assert(block != (void *)0xcbcbcbcb);
1037 assert(block != (void *)0xfbfbfbfb);
1038 assert(block != (void *)0xdbdbdbdb);
1039 if (block->b_instr != NULL) {
1040 assert(block->b_ialloc > 0);
1041 assert(block->b_iused > 0);
1042 assert(block->b_ialloc >= block->b_iused);
1043 }
1044 else {
1045 assert (block->b_iused == 0);
1046 assert (block->b_ialloc == 0);
1047 }
1048 }
1049}
1050
1051static void
1052compiler_unit_free(struct compiler_unit *u)
1053{
1054 basicblock *b, *next;
1055
1056 compiler_unit_check(u);
1057 b = u->u_blocks;
1058 while (b != NULL) {
1059 if (b->b_instr)
1060 PyObject_Free((void *)b->b_instr);
1061 next = b->b_list;
1062 PyObject_Free((void *)b);
1063 b = next;
1064 }
1065 Py_XDECREF(u->u_ste);
1066 Py_XDECREF(u->u_name);
1067 Py_XDECREF(u->u_consts);
1068 Py_XDECREF(u->u_names);
1069 Py_XDECREF(u->u_varnames);
1070 Py_XDECREF(u->u_freevars);
1071 Py_XDECREF(u->u_cellvars);
1072 Py_XDECREF(u->u_private);
1073 PyObject_Free(u);
1074}
1075
1076static int
1077compiler_enter_scope(struct compiler *c, identifier name, void *key,
1078 int lineno)
1079{
1080 struct compiler_unit *u;
1081
1082 u = PyObject_Malloc(sizeof(struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001083 if (!u) {
1084 PyErr_NoMemory();
1085 return 0;
1086 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087 memset(u, 0, sizeof(struct compiler_unit));
1088 u->u_argcount = 0;
1089 u->u_ste = PySymtable_Lookup(c->c_st, key);
1090 if (!u->u_ste) {
1091 compiler_unit_free(u);
Neal Norwitz87b801c2005-12-18 04:42:47 +00001092 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093 }
1094 Py_INCREF(name);
1095 u->u_name = name;
1096 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1097 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1098 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
1099 PyDict_Size(u->u_cellvars));
1100
1101 u->u_blocks = NULL;
1102 u->u_tmpname = 0;
1103 u->u_nfblocks = 0;
1104 u->u_firstlineno = lineno;
1105 u->u_lineno = 0;
1106 u->u_lineno_set = false;
1107 u->u_consts = PyDict_New();
1108 if (!u->u_consts) {
1109 compiler_unit_free(u);
1110 return 0;
1111 }
1112 u->u_names = PyDict_New();
1113 if (!u->u_names) {
1114 compiler_unit_free(u);
1115 return 0;
1116 }
1117
1118 u->u_private = NULL;
1119
1120 /* Push the old compiler_unit on the stack. */
1121 if (c->u) {
1122 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1123 if (PyList_Append(c->c_stack, wrapper) < 0) {
1124 compiler_unit_free(u);
1125 return 0;
1126 }
1127 Py_DECREF(wrapper);
1128 u->u_private = c->u->u_private;
1129 Py_XINCREF(u->u_private);
1130 }
1131 c->u = u;
1132
1133 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001134 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 return 0;
1136
1137 return 1;
1138}
1139
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001140static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141compiler_exit_scope(struct compiler *c)
1142{
1143 int n;
1144 PyObject *wrapper;
1145
1146 c->c_nestlevel--;
1147 compiler_unit_free(c->u);
1148 /* Restore c->u to the parent unit. */
1149 n = PyList_GET_SIZE(c->c_stack) - 1;
1150 if (n >= 0) {
1151 wrapper = PyList_GET_ITEM(c->c_stack, n);
1152 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001153 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001155 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 compiler_unit_check(c->u);
1157 }
1158 else
1159 c->u = NULL;
1160
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161}
1162
Guido van Rossumc2e20742006-02-27 22:32:47 +00001163/* Allocate a new "anonymous" local variable.
1164 Used by list comprehensions and with statements.
1165*/
1166
1167static PyObject *
1168compiler_new_tmpname(struct compiler *c)
1169{
1170 char tmpname[256];
1171 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1172 return PyString_FromString(tmpname);
1173}
1174
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175/* Allocate a new block and return a pointer to it.
1176 Returns NULL on error.
1177*/
1178
1179static basicblock *
1180compiler_new_block(struct compiler *c)
1181{
1182 basicblock *b;
1183 struct compiler_unit *u;
1184
1185 u = c->u;
1186 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001187 if (b == NULL) {
1188 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001190 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191 memset((void *)b, 0, sizeof(basicblock));
1192 assert (b->b_next == NULL);
1193 b->b_list = u->u_blocks;
1194 u->u_blocks = b;
1195 return b;
1196}
1197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198static basicblock *
1199compiler_use_new_block(struct compiler *c)
1200{
1201 basicblock *block = compiler_new_block(c);
1202 if (block == NULL)
1203 return NULL;
1204 c->u->u_curblock = block;
1205 return block;
1206}
1207
1208static basicblock *
1209compiler_next_block(struct compiler *c)
1210{
1211 basicblock *block = compiler_new_block(c);
1212 if (block == NULL)
1213 return NULL;
1214 c->u->u_curblock->b_next = block;
1215 c->u->u_curblock = block;
1216 return block;
1217}
1218
1219static basicblock *
1220compiler_use_next_block(struct compiler *c, basicblock *block)
1221{
1222 assert(block != NULL);
1223 c->u->u_curblock->b_next = block;
1224 c->u->u_curblock = block;
1225 return block;
1226}
1227
1228/* Returns the offset of the next instruction in the current block's
1229 b_instr array. Resizes the b_instr as necessary.
1230 Returns -1 on failure.
1231 */
1232
1233static int
1234compiler_next_instr(struct compiler *c, basicblock *b)
1235{
1236 assert(b != NULL);
1237 if (b->b_instr == NULL) {
1238 b->b_instr = PyObject_Malloc(sizeof(struct instr) *
1239 DEFAULT_BLOCK_SIZE);
1240 if (b->b_instr == NULL) {
1241 PyErr_NoMemory();
1242 return -1;
1243 }
1244 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1245 memset((char *)b->b_instr, 0,
1246 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
1247 }
1248 else if (b->b_iused == b->b_ialloc) {
1249 size_t oldsize, newsize;
1250 oldsize = b->b_ialloc * sizeof(struct instr);
1251 newsize = oldsize << 1;
1252 if (newsize == 0) {
1253 PyErr_NoMemory();
1254 return -1;
1255 }
1256 b->b_ialloc <<= 1;
1257 b->b_instr = PyObject_Realloc((void *)b->b_instr, newsize);
1258 if (b->b_instr == NULL)
1259 return -1;
1260 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1261 }
1262 return b->b_iused++;
1263}
1264
1265static void
1266compiler_set_lineno(struct compiler *c, int off)
1267{
1268 basicblock *b;
1269 if (c->u->u_lineno_set)
1270 return;
1271 c->u->u_lineno_set = true;
1272 b = c->u->u_curblock;
1273 b->b_instr[off].i_lineno = c->u->u_lineno;
1274}
1275
1276static int
1277opcode_stack_effect(int opcode, int oparg)
1278{
1279 switch (opcode) {
1280 case POP_TOP:
1281 return -1;
1282 case ROT_TWO:
1283 case ROT_THREE:
1284 return 0;
1285 case DUP_TOP:
1286 return 1;
1287 case ROT_FOUR:
1288 return 0;
1289
1290 case UNARY_POSITIVE:
1291 case UNARY_NEGATIVE:
1292 case UNARY_NOT:
1293 case UNARY_CONVERT:
1294 case UNARY_INVERT:
1295 return 0;
1296
1297 case BINARY_POWER:
1298 case BINARY_MULTIPLY:
1299 case BINARY_DIVIDE:
1300 case BINARY_MODULO:
1301 case BINARY_ADD:
1302 case BINARY_SUBTRACT:
1303 case BINARY_SUBSCR:
1304 case BINARY_FLOOR_DIVIDE:
1305 case BINARY_TRUE_DIVIDE:
1306 return -1;
1307 case INPLACE_FLOOR_DIVIDE:
1308 case INPLACE_TRUE_DIVIDE:
1309 return -1;
1310
1311 case SLICE+0:
1312 return 1;
1313 case SLICE+1:
1314 return 0;
1315 case SLICE+2:
1316 return 0;
1317 case SLICE+3:
1318 return -1;
1319
1320 case STORE_SLICE+0:
1321 return -2;
1322 case STORE_SLICE+1:
1323 return -3;
1324 case STORE_SLICE+2:
1325 return -3;
1326 case STORE_SLICE+3:
1327 return -4;
1328
1329 case DELETE_SLICE+0:
1330 return -1;
1331 case DELETE_SLICE+1:
1332 return -2;
1333 case DELETE_SLICE+2:
1334 return -2;
1335 case DELETE_SLICE+3:
1336 return -3;
1337
1338 case INPLACE_ADD:
1339 case INPLACE_SUBTRACT:
1340 case INPLACE_MULTIPLY:
1341 case INPLACE_DIVIDE:
1342 case INPLACE_MODULO:
1343 return -1;
1344 case STORE_SUBSCR:
1345 return -3;
1346 case DELETE_SUBSCR:
1347 return -2;
1348
1349 case BINARY_LSHIFT:
1350 case BINARY_RSHIFT:
1351 case BINARY_AND:
1352 case BINARY_XOR:
1353 case BINARY_OR:
1354 return -1;
1355 case INPLACE_POWER:
1356 return -1;
1357 case GET_ITER:
1358 return 0;
1359
1360 case PRINT_EXPR:
1361 return -1;
1362 case PRINT_ITEM:
1363 return -1;
1364 case PRINT_NEWLINE:
1365 return 0;
1366 case PRINT_ITEM_TO:
1367 return -2;
1368 case PRINT_NEWLINE_TO:
1369 return -1;
1370 case INPLACE_LSHIFT:
1371 case INPLACE_RSHIFT:
1372 case INPLACE_AND:
1373 case INPLACE_XOR:
1374 case INPLACE_OR:
1375 return -1;
1376 case BREAK_LOOP:
1377 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001378 case WITH_CLEANUP:
1379 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 case LOAD_LOCALS:
1381 return 1;
1382 case RETURN_VALUE:
1383 return -1;
1384 case IMPORT_STAR:
1385 return -1;
1386 case EXEC_STMT:
1387 return -3;
1388 case YIELD_VALUE:
1389 return 0;
1390
1391 case POP_BLOCK:
1392 return 0;
1393 case END_FINALLY:
1394 return -1; /* or -2 or -3 if exception occurred */
1395 case BUILD_CLASS:
1396 return -2;
1397
1398 case STORE_NAME:
1399 return -1;
1400 case DELETE_NAME:
1401 return 0;
1402 case UNPACK_SEQUENCE:
1403 return oparg-1;
1404 case FOR_ITER:
1405 return 1;
1406
1407 case STORE_ATTR:
1408 return -2;
1409 case DELETE_ATTR:
1410 return -1;
1411 case STORE_GLOBAL:
1412 return -1;
1413 case DELETE_GLOBAL:
1414 return 0;
1415 case DUP_TOPX:
1416 return oparg;
1417 case LOAD_CONST:
1418 return 1;
1419 case LOAD_NAME:
1420 return 1;
1421 case BUILD_TUPLE:
1422 case BUILD_LIST:
1423 return 1-oparg;
1424 case BUILD_MAP:
1425 return 1;
1426 case LOAD_ATTR:
1427 return 0;
1428 case COMPARE_OP:
1429 return -1;
1430 case IMPORT_NAME:
1431 return 0;
1432 case IMPORT_FROM:
1433 return 1;
1434
1435 case JUMP_FORWARD:
1436 case JUMP_IF_FALSE:
1437 case JUMP_IF_TRUE:
1438 case JUMP_ABSOLUTE:
1439 return 0;
1440
1441 case LOAD_GLOBAL:
1442 return 1;
1443
1444 case CONTINUE_LOOP:
1445 return 0;
1446 case SETUP_LOOP:
1447 return 0;
1448 case SETUP_EXCEPT:
1449 case SETUP_FINALLY:
1450 return 3; /* actually pushed by an exception */
1451
1452 case LOAD_FAST:
1453 return 1;
1454 case STORE_FAST:
1455 return -1;
1456 case DELETE_FAST:
1457 return 0;
1458
1459 case RAISE_VARARGS:
1460 return -oparg;
1461#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1462 case CALL_FUNCTION:
1463 return -NARGS(oparg);
1464 case CALL_FUNCTION_VAR:
1465 case CALL_FUNCTION_KW:
1466 return -NARGS(oparg)-1;
1467 case CALL_FUNCTION_VAR_KW:
1468 return -NARGS(oparg)-2;
1469#undef NARGS
1470 case MAKE_FUNCTION:
1471 return -oparg;
1472 case BUILD_SLICE:
1473 if (oparg == 3)
1474 return -2;
1475 else
1476 return -1;
1477
1478 case MAKE_CLOSURE:
1479 return -oparg;
1480 case LOAD_CLOSURE:
1481 return 1;
1482 case LOAD_DEREF:
1483 return 1;
1484 case STORE_DEREF:
1485 return -1;
1486 default:
1487 fprintf(stderr, "opcode = %d\n", opcode);
1488 Py_FatalError("opcode_stack_effect()");
1489
1490 }
1491 return 0; /* not reachable */
1492}
1493
1494/* Add an opcode with no argument.
1495 Returns 0 on failure, 1 on success.
1496*/
1497
1498static int
1499compiler_addop(struct compiler *c, int opcode)
1500{
1501 basicblock *b;
1502 struct instr *i;
1503 int off;
1504 off = compiler_next_instr(c, c->u->u_curblock);
1505 if (off < 0)
1506 return 0;
1507 b = c->u->u_curblock;
1508 i = &b->b_instr[off];
1509 i->i_opcode = opcode;
1510 i->i_hasarg = 0;
1511 if (opcode == RETURN_VALUE)
1512 b->b_return = 1;
1513 compiler_set_lineno(c, off);
1514 return 1;
1515}
1516
1517static int
1518compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1519{
1520 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001521 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522
1523 /* necessary to make sure types aren't coerced (e.g., int and long) */
Neil Schemenauer3a44aaa2005-10-23 17:21:54 +00001524 t = PyTuple_Pack(2, o, o->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525 if (t == NULL)
1526 return -1;
1527
1528 v = PyDict_GetItem(dict, t);
1529 if (!v) {
1530 arg = PyDict_Size(dict);
1531 v = PyInt_FromLong(arg);
1532 if (!v) {
1533 Py_DECREF(t);
1534 return -1;
1535 }
1536 if (PyDict_SetItem(dict, t, v) < 0) {
1537 Py_DECREF(t);
1538 Py_DECREF(v);
1539 return -1;
1540 }
1541 Py_DECREF(v);
1542 }
1543 else
1544 arg = PyInt_AsLong(v);
1545 Py_DECREF(t);
1546 return arg;
1547}
1548
1549static int
1550compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1551 PyObject *o)
1552{
1553 int arg = compiler_add_o(c, dict, o);
1554 if (arg < 0)
1555 return 0;
1556 return compiler_addop_i(c, opcode, arg);
1557}
1558
1559static int
1560compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
1561 PyObject *o)
1562{
1563 int arg;
1564 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1565 if (!mangled)
1566 return 0;
1567 arg = compiler_add_o(c, dict, mangled);
1568 Py_DECREF(mangled);
1569 if (arg < 0)
1570 return 0;
1571 return compiler_addop_i(c, opcode, arg);
1572}
1573
1574/* Add an opcode with an integer argument.
1575 Returns 0 on failure, 1 on success.
1576*/
1577
1578static int
1579compiler_addop_i(struct compiler *c, int opcode, int oparg)
1580{
1581 struct instr *i;
1582 int off;
1583 off = compiler_next_instr(c, c->u->u_curblock);
1584 if (off < 0)
1585 return 0;
1586 i = &c->u->u_curblock->b_instr[off];
1587 i->i_opcode = opcode;
1588 i->i_oparg = oparg;
1589 i->i_hasarg = 1;
1590 compiler_set_lineno(c, off);
1591 return 1;
1592}
1593
1594static int
1595compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1596{
1597 struct instr *i;
1598 int off;
1599
1600 assert(b != NULL);
1601 off = compiler_next_instr(c, c->u->u_curblock);
1602 if (off < 0)
1603 return 0;
1604 compiler_set_lineno(c, off);
1605 i = &c->u->u_curblock->b_instr[off];
1606 i->i_opcode = opcode;
1607 i->i_target = b;
1608 i->i_hasarg = 1;
1609 if (absolute)
1610 i->i_jabs = 1;
1611 else
1612 i->i_jrel = 1;
1613 return 1;
1614}
1615
1616/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1617 like to find better names.) NEW_BLOCK() creates a new block and sets
1618 it as the current block. NEXT_BLOCK() also creates an implicit jump
1619 from the current block to the new block.
1620*/
1621
1622/* XXX The returns inside these macros make it impossible to decref
1623 objects created in the local function.
1624*/
1625
1626
1627#define NEW_BLOCK(C) { \
1628 if (compiler_use_new_block((C)) == NULL) \
1629 return 0; \
1630}
1631
1632#define NEXT_BLOCK(C) { \
1633 if (compiler_next_block((C)) == NULL) \
1634 return 0; \
1635}
1636
1637#define ADDOP(C, OP) { \
1638 if (!compiler_addop((C), (OP))) \
1639 return 0; \
1640}
1641
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001642#define ADDOP_IN_SCOPE(C, OP) { \
1643 if (!compiler_addop((C), (OP))) { \
1644 compiler_exit_scope(c); \
1645 return 0; \
1646 } \
1647}
1648
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649#define ADDOP_O(C, OP, O, TYPE) { \
1650 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1651 return 0; \
1652}
1653
1654#define ADDOP_NAME(C, OP, O, TYPE) { \
1655 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1656 return 0; \
1657}
1658
1659#define ADDOP_I(C, OP, O) { \
1660 if (!compiler_addop_i((C), (OP), (O))) \
1661 return 0; \
1662}
1663
1664#define ADDOP_JABS(C, OP, O) { \
1665 if (!compiler_addop_j((C), (OP), (O), 1)) \
1666 return 0; \
1667}
1668
1669#define ADDOP_JREL(C, OP, O) { \
1670 if (!compiler_addop_j((C), (OP), (O), 0)) \
1671 return 0; \
1672}
1673
1674/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1675 the ASDL name to synthesize the name of the C type and the visit function.
1676*/
1677
1678#define VISIT(C, TYPE, V) {\
1679 if (!compiler_visit_ ## TYPE((C), (V))) \
1680 return 0; \
1681}
1682
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001683#define VISIT_IN_SCOPE(C, TYPE, V) {\
1684 if (!compiler_visit_ ## TYPE((C), (V))) { \
1685 compiler_exit_scope(c); \
1686 return 0; \
1687 } \
1688}
1689
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690#define VISIT_SLICE(C, V, CTX) {\
1691 if (!compiler_visit_slice((C), (V), (CTX))) \
1692 return 0; \
1693}
1694
1695#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001696 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001698 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1699 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700 if (!compiler_visit_ ## TYPE((C), elt)) \
1701 return 0; \
1702 } \
1703}
1704
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001705#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001706 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001707 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001708 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1709 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001710 if (!compiler_visit_ ## TYPE((C), elt)) { \
1711 compiler_exit_scope(c); \
1712 return 0; \
1713 } \
1714 } \
1715}
1716
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717static int
1718compiler_isdocstring(stmt_ty s)
1719{
1720 if (s->kind != Expr_kind)
1721 return 0;
1722 return s->v.Expr.value->kind == Str_kind;
1723}
1724
1725/* Compile a sequence of statements, checking for a docstring. */
1726
1727static int
1728compiler_body(struct compiler *c, asdl_seq *stmts)
1729{
1730 int i = 0;
1731 stmt_ty st;
1732
1733 if (!asdl_seq_LEN(stmts))
1734 return 1;
1735 st = asdl_seq_GET(stmts, 0);
1736 if (compiler_isdocstring(st)) {
1737 i = 1;
1738 VISIT(c, expr, st->v.Expr.value);
1739 if (!compiler_nameop(c, __doc__, Store))
1740 return 0;
1741 }
1742 for (; i < asdl_seq_LEN(stmts); i++)
1743 VISIT(c, stmt, asdl_seq_GET(stmts, i));
1744 return 1;
1745}
1746
1747static PyCodeObject *
1748compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001749{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001750 PyCodeObject *co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751 int addNone = 1;
1752 static PyObject *module;
1753 if (!module) {
1754 module = PyString_FromString("<module>");
1755 if (!module)
1756 return NULL;
1757 }
1758 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001759 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760 switch (mod->kind) {
1761 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001762 if (!compiler_body(c, mod->v.Module.body)) {
1763 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001765 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 break;
1767 case Interactive_kind:
1768 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001769 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 break;
1771 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001772 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773 addNone = 0;
1774 break;
1775 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001776 PyErr_SetString(PyExc_SystemError,
1777 "suite should not be possible");
1778 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001780 PyErr_Format(PyExc_SystemError,
1781 "module kind %d should not be possible",
1782 mod->kind);
1783 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001784 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785 co = assemble(c, addNone);
1786 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001787 return co;
1788}
1789
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790/* The test for LOCAL must come before the test for FREE in order to
1791 handle classes where name is both local and free. The local var is
1792 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001793*/
1794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795static int
1796get_ref_type(struct compiler *c, PyObject *name)
1797{
1798 int scope = PyST_GetScope(c->u->u_ste, name);
1799 if (scope == 0) {
1800 char buf[350];
1801 PyOS_snprintf(buf, sizeof(buf),
1802 "unknown scope for %.100s in %.100s(%s) in %s\n"
1803 "symbols: %s\nlocals: %s\nglobals: %s\n",
1804 PyString_AS_STRING(name),
1805 PyString_AS_STRING(c->u->u_name),
1806 PyObject_REPR(c->u->u_ste->ste_id),
1807 c->c_filename,
1808 PyObject_REPR(c->u->u_ste->ste_symbols),
1809 PyObject_REPR(c->u->u_varnames),
1810 PyObject_REPR(c->u->u_names)
1811 );
1812 Py_FatalError(buf);
1813 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001814
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815 return scope;
1816}
1817
1818static int
1819compiler_lookup_arg(PyObject *dict, PyObject *name)
1820{
1821 PyObject *k, *v;
1822 k = Py_BuildValue("(OO)", name, name->ob_type);
1823 if (k == NULL)
1824 return -1;
1825 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001826 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 if (v == NULL)
1828 return -1;
1829 return PyInt_AS_LONG(v);
1830}
1831
1832static int
1833compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1834{
1835 int i, free = PyCode_GetNumFree(co);
1836 if (free == 0) {
1837 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1838 ADDOP_I(c, MAKE_FUNCTION, args);
1839 return 1;
1840 }
1841 for (i = 0; i < free; ++i) {
1842 /* Bypass com_addop_varname because it will generate
1843 LOAD_DEREF but LOAD_CLOSURE is needed.
1844 */
1845 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1846 int arg, reftype;
1847
1848 /* Special case: If a class contains a method with a
1849 free variable that has the same name as a method,
1850 the name will be considered free *and* local in the
1851 class. It should be handled by the closure, as
1852 well as by the normal name loookup logic.
1853 */
1854 reftype = get_ref_type(c, name);
1855 if (reftype == CELL)
1856 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1857 else /* (reftype == FREE) */
1858 arg = compiler_lookup_arg(c->u->u_freevars, name);
1859 if (arg == -1) {
1860 printf("lookup %s in %s %d %d\n"
1861 "freevars of %s: %s\n",
1862 PyObject_REPR(name),
1863 PyString_AS_STRING(c->u->u_name),
1864 reftype, arg,
1865 PyString_AS_STRING(co->co_name),
1866 PyObject_REPR(co->co_freevars));
1867 Py_FatalError("compiler_make_closure()");
1868 }
1869 ADDOP_I(c, LOAD_CLOSURE, arg);
1870 }
1871 ADDOP_I(c, BUILD_TUPLE, free);
1872 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1873 ADDOP_I(c, MAKE_CLOSURE, args);
1874 return 1;
1875}
1876
1877static int
1878compiler_decorators(struct compiler *c, asdl_seq* decos)
1879{
1880 int i;
1881
1882 if (!decos)
1883 return 1;
1884
1885 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1886 VISIT(c, expr, asdl_seq_GET(decos, i));
1887 }
1888 return 1;
1889}
1890
1891static int
1892compiler_arguments(struct compiler *c, arguments_ty args)
1893{
1894 int i;
1895 int n = asdl_seq_LEN(args->args);
1896 /* Correctly handle nested argument lists */
1897 for (i = 0; i < n; i++) {
1898 expr_ty arg = asdl_seq_GET(args->args, i);
1899 if (arg->kind == Tuple_kind) {
1900 PyObject *id = PyString_FromFormat(".%d", i);
1901 if (id == NULL) {
1902 return 0;
1903 }
1904 if (!compiler_nameop(c, id, Load)) {
1905 Py_DECREF(id);
1906 return 0;
1907 }
1908 Py_DECREF(id);
1909 VISIT(c, expr, arg);
1910 }
1911 }
1912 return 1;
1913}
1914
1915static int
1916compiler_function(struct compiler *c, stmt_ty s)
1917{
1918 PyCodeObject *co;
1919 PyObject *first_const = Py_None;
1920 arguments_ty args = s->v.FunctionDef.args;
1921 asdl_seq* decos = s->v.FunctionDef.decorators;
1922 stmt_ty st;
1923 int i, n, docstring;
1924
1925 assert(s->kind == FunctionDef_kind);
1926
1927 if (!compiler_decorators(c, decos))
1928 return 0;
1929 if (args->defaults)
1930 VISIT_SEQ(c, expr, args->defaults);
1931 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1932 s->lineno))
1933 return 0;
1934
1935 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1936 docstring = compiler_isdocstring(st);
1937 if (docstring)
1938 first_const = st->v.Expr.value->v.Str.s;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001939 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1940 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001942 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943
1944 /* unpack nested arguments */
1945 compiler_arguments(c, args);
1946
1947 c->u->u_argcount = asdl_seq_LEN(args->args);
1948 n = asdl_seq_LEN(s->v.FunctionDef.body);
1949 /* if there was a docstring, we need to skip the first statement */
1950 for (i = docstring; i < n; i++) {
1951 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1952 if (i == 0 && s2->kind == Expr_kind &&
1953 s2->v.Expr.value->kind == Str_kind)
1954 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001955 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 }
1957 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001958 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 if (co == NULL)
1960 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
1962 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001963 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964
1965 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1966 ADDOP_I(c, CALL_FUNCTION, 1);
1967 }
1968
1969 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1970}
1971
1972static int
1973compiler_class(struct compiler *c, stmt_ty s)
1974{
1975 int n;
1976 PyCodeObject *co;
1977 PyObject *str;
1978 /* push class name on stack, needed by BUILD_CLASS */
1979 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1980 /* push the tuple of base classes on the stack */
1981 n = asdl_seq_LEN(s->v.ClassDef.bases);
1982 if (n > 0)
1983 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1984 ADDOP_I(c, BUILD_TUPLE, n);
1985 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1986 s->lineno))
1987 return 0;
1988 c->u->u_private = s->v.ClassDef.name;
1989 Py_INCREF(c->u->u_private);
1990 str = PyString_InternFromString("__name__");
1991 if (!str || !compiler_nameop(c, str, Load)) {
1992 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001993 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994 return 0;
1995 }
1996
1997 Py_DECREF(str);
1998 str = PyString_InternFromString("__module__");
1999 if (!str || !compiler_nameop(c, str, Store)) {
2000 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002001 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 return 0;
2003 }
2004 Py_DECREF(str);
2005
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002006 if (!compiler_body(c, s->v.ClassDef.body)) {
2007 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002009 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002011 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2012 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002014 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 if (co == NULL)
2016 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017
2018 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002019 Py_DECREF(co);
2020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 ADDOP_I(c, CALL_FUNCTION, 0);
2022 ADDOP(c, BUILD_CLASS);
2023 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2024 return 0;
2025 return 1;
2026}
2027
2028static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002029compiler_ifexp(struct compiler *c, expr_ty e)
2030{
2031 basicblock *end, *next;
2032
2033 assert(e->kind == IfExp_kind);
2034 end = compiler_new_block(c);
2035 if (end == NULL)
2036 return 0;
2037 next = compiler_new_block(c);
2038 if (next == NULL)
2039 return 0;
2040 VISIT(c, expr, e->v.IfExp.test);
2041 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2042 ADDOP(c, POP_TOP);
2043 VISIT(c, expr, e->v.IfExp.body);
2044 ADDOP_JREL(c, JUMP_FORWARD, end);
2045 compiler_use_next_block(c, next);
2046 ADDOP(c, POP_TOP);
2047 VISIT(c, expr, e->v.IfExp.orelse);
2048 compiler_use_next_block(c, end);
2049 return 1;
2050}
2051
2052static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053compiler_lambda(struct compiler *c, expr_ty e)
2054{
2055 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002056 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 arguments_ty args = e->v.Lambda.args;
2058 assert(e->kind == Lambda_kind);
2059
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002060 if (!name) {
2061 name = PyString_InternFromString("<lambda>");
2062 if (!name)
2063 return 0;
2064 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065
2066 if (args->defaults)
2067 VISIT_SEQ(c, expr, args->defaults);
2068 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2069 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002070
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 /* unpack nested arguments */
2072 compiler_arguments(c, args);
2073
2074 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002075 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2076 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002078 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 if (co == NULL)
2080 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081
2082 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002083 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084
2085 return 1;
2086}
2087
2088static int
2089compiler_print(struct compiler *c, stmt_ty s)
2090{
2091 int i, n;
2092 bool dest;
2093
2094 assert(s->kind == Print_kind);
2095 n = asdl_seq_LEN(s->v.Print.values);
2096 dest = false;
2097 if (s->v.Print.dest) {
2098 VISIT(c, expr, s->v.Print.dest);
2099 dest = true;
2100 }
2101 for (i = 0; i < n; i++) {
2102 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2103 if (dest) {
2104 ADDOP(c, DUP_TOP);
2105 VISIT(c, expr, e);
2106 ADDOP(c, ROT_TWO);
2107 ADDOP(c, PRINT_ITEM_TO);
2108 }
2109 else {
2110 VISIT(c, expr, e);
2111 ADDOP(c, PRINT_ITEM);
2112 }
2113 }
2114 if (s->v.Print.nl) {
2115 if (dest)
2116 ADDOP(c, PRINT_NEWLINE_TO)
2117 else
2118 ADDOP(c, PRINT_NEWLINE)
2119 }
2120 else if (dest)
2121 ADDOP(c, POP_TOP);
2122 return 1;
2123}
2124
2125static int
2126compiler_if(struct compiler *c, stmt_ty s)
2127{
2128 basicblock *end, *next;
2129
2130 assert(s->kind == If_kind);
2131 end = compiler_new_block(c);
2132 if (end == NULL)
2133 return 0;
2134 next = compiler_new_block(c);
2135 if (next == NULL)
2136 return 0;
2137 VISIT(c, expr, s->v.If.test);
2138 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2139 ADDOP(c, POP_TOP);
2140 VISIT_SEQ(c, stmt, s->v.If.body);
2141 ADDOP_JREL(c, JUMP_FORWARD, end);
2142 compiler_use_next_block(c, next);
2143 ADDOP(c, POP_TOP);
2144 if (s->v.If.orelse)
2145 VISIT_SEQ(c, stmt, s->v.If.orelse);
2146 compiler_use_next_block(c, end);
2147 return 1;
2148}
2149
2150static int
2151compiler_for(struct compiler *c, stmt_ty s)
2152{
2153 basicblock *start, *cleanup, *end;
2154
2155 start = compiler_new_block(c);
2156 cleanup = compiler_new_block(c);
2157 end = compiler_new_block(c);
2158 if (start == NULL || end == NULL || cleanup == NULL)
2159 return 0;
2160 ADDOP_JREL(c, SETUP_LOOP, end);
2161 if (!compiler_push_fblock(c, LOOP, start))
2162 return 0;
2163 VISIT(c, expr, s->v.For.iter);
2164 ADDOP(c, GET_ITER);
2165 compiler_use_next_block(c, start);
2166 ADDOP_JREL(c, FOR_ITER, cleanup);
2167 VISIT(c, expr, s->v.For.target);
2168 VISIT_SEQ(c, stmt, s->v.For.body);
2169 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2170 compiler_use_next_block(c, cleanup);
2171 ADDOP(c, POP_BLOCK);
2172 compiler_pop_fblock(c, LOOP, start);
2173 VISIT_SEQ(c, stmt, s->v.For.orelse);
2174 compiler_use_next_block(c, end);
2175 return 1;
2176}
2177
2178static int
2179compiler_while(struct compiler *c, stmt_ty s)
2180{
2181 basicblock *loop, *orelse, *end, *anchor = NULL;
2182 int constant = expr_constant(s->v.While.test);
2183
2184 if (constant == 0)
2185 return 1;
2186 loop = compiler_new_block(c);
2187 end = compiler_new_block(c);
2188 if (constant == -1) {
2189 anchor = compiler_new_block(c);
2190 if (anchor == NULL)
2191 return 0;
2192 }
2193 if (loop == NULL || end == NULL)
2194 return 0;
2195 if (s->v.While.orelse) {
2196 orelse = compiler_new_block(c);
2197 if (orelse == NULL)
2198 return 0;
2199 }
2200 else
2201 orelse = NULL;
2202
2203 ADDOP_JREL(c, SETUP_LOOP, end);
2204 compiler_use_next_block(c, loop);
2205 if (!compiler_push_fblock(c, LOOP, loop))
2206 return 0;
2207 if (constant == -1) {
2208 VISIT(c, expr, s->v.While.test);
2209 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2210 ADDOP(c, POP_TOP);
2211 }
2212 VISIT_SEQ(c, stmt, s->v.While.body);
2213 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2214
2215 /* XXX should the two POP instructions be in a separate block
2216 if there is no else clause ?
2217 */
2218
2219 if (constant == -1) {
2220 compiler_use_next_block(c, anchor);
2221 ADDOP(c, POP_TOP);
2222 ADDOP(c, POP_BLOCK);
2223 }
2224 compiler_pop_fblock(c, LOOP, loop);
2225 if (orelse != NULL)
2226 VISIT_SEQ(c, stmt, s->v.While.orelse);
2227 compiler_use_next_block(c, end);
2228
2229 return 1;
2230}
2231
2232static int
2233compiler_continue(struct compiler *c)
2234{
2235 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2236 int i;
2237
2238 if (!c->u->u_nfblocks)
2239 return compiler_error(c, LOOP_ERROR_MSG);
2240 i = c->u->u_nfblocks - 1;
2241 switch (c->u->u_fblock[i].fb_type) {
2242 case LOOP:
2243 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2244 break;
2245 case EXCEPT:
2246 case FINALLY_TRY:
2247 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2248 ;
2249 if (i == -1)
2250 return compiler_error(c, LOOP_ERROR_MSG);
2251 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2252 break;
2253 case FINALLY_END:
2254 return compiler_error(c,
2255 "'continue' not supported inside 'finally' clause");
2256 }
2257
2258 return 1;
2259}
2260
2261/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2262
2263 SETUP_FINALLY L
2264 <code for body>
2265 POP_BLOCK
2266 LOAD_CONST <None>
2267 L: <code for finalbody>
2268 END_FINALLY
2269
2270 The special instructions use the block stack. Each block
2271 stack entry contains the instruction that created it (here
2272 SETUP_FINALLY), the level of the value stack at the time the
2273 block stack entry was created, and a label (here L).
2274
2275 SETUP_FINALLY:
2276 Pushes the current value stack level and the label
2277 onto the block stack.
2278 POP_BLOCK:
2279 Pops en entry from the block stack, and pops the value
2280 stack until its level is the same as indicated on the
2281 block stack. (The label is ignored.)
2282 END_FINALLY:
2283 Pops a variable number of entries from the *value* stack
2284 and re-raises the exception they specify. The number of
2285 entries popped depends on the (pseudo) exception type.
2286
2287 The block stack is unwound when an exception is raised:
2288 when a SETUP_FINALLY entry is found, the exception is pushed
2289 onto the value stack (and the exception condition is cleared),
2290 and the interpreter jumps to the label gotten from the block
2291 stack.
2292*/
2293
2294static int
2295compiler_try_finally(struct compiler *c, stmt_ty s)
2296{
2297 basicblock *body, *end;
2298 body = compiler_new_block(c);
2299 end = compiler_new_block(c);
2300 if (body == NULL || end == NULL)
2301 return 0;
2302
2303 ADDOP_JREL(c, SETUP_FINALLY, end);
2304 compiler_use_next_block(c, body);
2305 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2306 return 0;
2307 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2308 ADDOP(c, POP_BLOCK);
2309 compiler_pop_fblock(c, FINALLY_TRY, body);
2310
2311 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2312 compiler_use_next_block(c, end);
2313 if (!compiler_push_fblock(c, FINALLY_END, end))
2314 return 0;
2315 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2316 ADDOP(c, END_FINALLY);
2317 compiler_pop_fblock(c, FINALLY_END, end);
2318
2319 return 1;
2320}
2321
2322/*
2323 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2324 (The contents of the value stack is shown in [], with the top
2325 at the right; 'tb' is trace-back info, 'val' the exception's
2326 associated value, and 'exc' the exception.)
2327
2328 Value stack Label Instruction Argument
2329 [] SETUP_EXCEPT L1
2330 [] <code for S>
2331 [] POP_BLOCK
2332 [] JUMP_FORWARD L0
2333
2334 [tb, val, exc] L1: DUP )
2335 [tb, val, exc, exc] <evaluate E1> )
2336 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2337 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2338 [tb, val, exc, 1] POP )
2339 [tb, val, exc] POP
2340 [tb, val] <assign to V1> (or POP if no V1)
2341 [tb] POP
2342 [] <code for S1>
2343 JUMP_FORWARD L0
2344
2345 [tb, val, exc, 0] L2: POP
2346 [tb, val, exc] DUP
2347 .............................etc.......................
2348
2349 [tb, val, exc, 0] Ln+1: POP
2350 [tb, val, exc] END_FINALLY # re-raise exception
2351
2352 [] L0: <next statement>
2353
2354 Of course, parts are not generated if Vi or Ei is not present.
2355*/
2356static int
2357compiler_try_except(struct compiler *c, stmt_ty s)
2358{
2359 basicblock *body, *orelse, *except, *end;
2360 int i, n;
2361
2362 body = compiler_new_block(c);
2363 except = compiler_new_block(c);
2364 orelse = compiler_new_block(c);
2365 end = compiler_new_block(c);
2366 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2367 return 0;
2368 ADDOP_JREL(c, SETUP_EXCEPT, except);
2369 compiler_use_next_block(c, body);
2370 if (!compiler_push_fblock(c, EXCEPT, body))
2371 return 0;
2372 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2373 ADDOP(c, POP_BLOCK);
2374 compiler_pop_fblock(c, EXCEPT, body);
2375 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2376 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2377 compiler_use_next_block(c, except);
2378 for (i = 0; i < n; i++) {
2379 excepthandler_ty handler = asdl_seq_GET(
2380 s->v.TryExcept.handlers, i);
2381 if (!handler->type && i < n-1)
2382 return compiler_error(c, "default 'except:' must be last");
2383 except = compiler_new_block(c);
2384 if (except == NULL)
2385 return 0;
2386 if (handler->type) {
2387 ADDOP(c, DUP_TOP);
2388 VISIT(c, expr, handler->type);
2389 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2390 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2391 ADDOP(c, POP_TOP);
2392 }
2393 ADDOP(c, POP_TOP);
2394 if (handler->name) {
2395 VISIT(c, expr, handler->name);
2396 }
2397 else {
2398 ADDOP(c, POP_TOP);
2399 }
2400 ADDOP(c, POP_TOP);
2401 VISIT_SEQ(c, stmt, handler->body);
2402 ADDOP_JREL(c, JUMP_FORWARD, end);
2403 compiler_use_next_block(c, except);
2404 if (handler->type)
2405 ADDOP(c, POP_TOP);
2406 }
2407 ADDOP(c, END_FINALLY);
2408 compiler_use_next_block(c, orelse);
2409 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2410 compiler_use_next_block(c, end);
2411 return 1;
2412}
2413
2414static int
2415compiler_import_as(struct compiler *c, identifier name, identifier asname)
2416{
2417 /* The IMPORT_NAME opcode was already generated. This function
2418 merely needs to bind the result to a name.
2419
2420 If there is a dot in name, we need to split it and emit a
2421 LOAD_ATTR for each name.
2422 */
2423 const char *src = PyString_AS_STRING(name);
2424 const char *dot = strchr(src, '.');
2425 if (dot) {
2426 /* Consume the base module name to get the first attribute */
2427 src = dot + 1;
2428 while (dot) {
2429 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002430 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002432 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002434 if (!attr)
2435 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002437 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438 src = dot + 1;
2439 }
2440 }
2441 return compiler_nameop(c, asname, Store);
2442}
2443
2444static int
2445compiler_import(struct compiler *c, stmt_ty s)
2446{
2447 /* The Import node stores a module name like a.b.c as a single
2448 string. This is convenient for all cases except
2449 import a.b.c as d
2450 where we need to parse that string to extract the individual
2451 module names.
2452 XXX Perhaps change the representation to make this case simpler?
2453 */
2454 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002455
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 for (i = 0; i < n; i++) {
2457 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2458 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002459 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002461 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2462 level = PyInt_FromLong(0);
2463 else
2464 level = PyInt_FromLong(-1);
2465
2466 if (level == NULL)
2467 return 0;
2468
2469 ADDOP_O(c, LOAD_CONST, level, consts);
2470 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2472 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2473
2474 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002475 r = compiler_import_as(c, alias->name, alias->asname);
2476 if (!r)
2477 return r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 }
2479 else {
2480 identifier tmp = alias->name;
2481 const char *base = PyString_AS_STRING(alias->name);
2482 char *dot = strchr(base, '.');
2483 if (dot)
2484 tmp = PyString_FromStringAndSize(base,
2485 dot - base);
2486 r = compiler_nameop(c, tmp, Store);
2487 if (dot) {
2488 Py_DECREF(tmp);
2489 }
2490 if (!r)
2491 return r;
2492 }
2493 }
2494 return 1;
2495}
2496
2497static int
2498compiler_from_import(struct compiler *c, stmt_ty s)
2499{
2500 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501
2502 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002503 PyObject *level;
2504
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505 if (!names)
2506 return 0;
2507
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002508 if (s->v.ImportFrom.level == 0 && c->c_flags &&
2509 !(c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2510 level = PyInt_FromLong(-1);
2511 else
2512 level = PyInt_FromLong(s->v.ImportFrom.level);
2513
2514 if (!level) {
2515 Py_DECREF(names);
2516 return 0;
2517 }
2518
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519 /* build up the names */
2520 for (i = 0; i < n; i++) {
2521 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2522 Py_INCREF(alias->name);
2523 PyTuple_SET_ITEM(names, i, alias->name);
2524 }
2525
2526 if (s->lineno > c->c_future->ff_lineno) {
2527 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2528 "__future__")) {
2529 Py_DECREF(names);
2530 return compiler_error(c,
2531 "from __future__ imports must occur "
2532 "at the beginning of the file");
2533
2534 }
2535 }
2536
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002537 ADDOP_O(c, LOAD_CONST, level, consts);
2538 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002540 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2542 for (i = 0; i < n; i++) {
2543 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2544 identifier store_name;
2545
2546 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2547 assert(n == 1);
2548 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002549 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 }
2551
2552 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2553 store_name = alias->name;
2554 if (alias->asname)
2555 store_name = alias->asname;
2556
2557 if (!compiler_nameop(c, store_name, Store)) {
2558 Py_DECREF(names);
2559 return 0;
2560 }
2561 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002562 /* remove imported module */
2563 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 return 1;
2565}
2566
2567static int
2568compiler_assert(struct compiler *c, stmt_ty s)
2569{
2570 static PyObject *assertion_error = NULL;
2571 basicblock *end;
2572
2573 if (Py_OptimizeFlag)
2574 return 1;
2575 if (assertion_error == NULL) {
2576 assertion_error = PyString_FromString("AssertionError");
2577 if (assertion_error == NULL)
2578 return 0;
2579 }
2580 VISIT(c, expr, s->v.Assert.test);
2581 end = compiler_new_block(c);
2582 if (end == NULL)
2583 return 0;
2584 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2585 ADDOP(c, POP_TOP);
2586 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2587 if (s->v.Assert.msg) {
2588 VISIT(c, expr, s->v.Assert.msg);
2589 ADDOP_I(c, RAISE_VARARGS, 2);
2590 }
2591 else {
2592 ADDOP_I(c, RAISE_VARARGS, 1);
2593 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002594 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595 ADDOP(c, POP_TOP);
2596 return 1;
2597}
2598
2599static int
2600compiler_visit_stmt(struct compiler *c, stmt_ty s)
2601{
2602 int i, n;
2603
2604 c->u->u_lineno = s->lineno;
2605 c->u->u_lineno_set = false;
2606 switch (s->kind) {
2607 case FunctionDef_kind:
2608 return compiler_function(c, s);
2609 case ClassDef_kind:
2610 return compiler_class(c, s);
2611 case Return_kind:
2612 if (c->u->u_ste->ste_type != FunctionBlock)
2613 return compiler_error(c, "'return' outside function");
2614 if (s->v.Return.value) {
2615 if (c->u->u_ste->ste_generator) {
2616 return compiler_error(c,
2617 "'return' with argument inside generator");
2618 }
2619 VISIT(c, expr, s->v.Return.value);
2620 }
2621 else
2622 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2623 ADDOP(c, RETURN_VALUE);
2624 break;
2625 case Delete_kind:
2626 VISIT_SEQ(c, expr, s->v.Delete.targets)
2627 break;
2628 case Assign_kind:
2629 n = asdl_seq_LEN(s->v.Assign.targets);
2630 VISIT(c, expr, s->v.Assign.value);
2631 for (i = 0; i < n; i++) {
2632 if (i < n - 1)
2633 ADDOP(c, DUP_TOP);
2634 VISIT(c, expr,
2635 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2636 }
2637 break;
2638 case AugAssign_kind:
2639 return compiler_augassign(c, s);
2640 case Print_kind:
2641 return compiler_print(c, s);
2642 case For_kind:
2643 return compiler_for(c, s);
2644 case While_kind:
2645 return compiler_while(c, s);
2646 case If_kind:
2647 return compiler_if(c, s);
2648 case Raise_kind:
2649 n = 0;
2650 if (s->v.Raise.type) {
2651 VISIT(c, expr, s->v.Raise.type);
2652 n++;
2653 if (s->v.Raise.inst) {
2654 VISIT(c, expr, s->v.Raise.inst);
2655 n++;
2656 if (s->v.Raise.tback) {
2657 VISIT(c, expr, s->v.Raise.tback);
2658 n++;
2659 }
2660 }
2661 }
2662 ADDOP_I(c, RAISE_VARARGS, n);
2663 break;
2664 case TryExcept_kind:
2665 return compiler_try_except(c, s);
2666 case TryFinally_kind:
2667 return compiler_try_finally(c, s);
2668 case Assert_kind:
2669 return compiler_assert(c, s);
2670 case Import_kind:
2671 return compiler_import(c, s);
2672 case ImportFrom_kind:
2673 return compiler_from_import(c, s);
2674 case Exec_kind:
2675 VISIT(c, expr, s->v.Exec.body);
2676 if (s->v.Exec.globals) {
2677 VISIT(c, expr, s->v.Exec.globals);
2678 if (s->v.Exec.locals) {
2679 VISIT(c, expr, s->v.Exec.locals);
2680 } else {
2681 ADDOP(c, DUP_TOP);
2682 }
2683 } else {
2684 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2685 ADDOP(c, DUP_TOP);
2686 }
2687 ADDOP(c, EXEC_STMT);
2688 break;
2689 case Global_kind:
2690 break;
2691 case Expr_kind:
2692 VISIT(c, expr, s->v.Expr.value);
2693 if (c->c_interactive && c->c_nestlevel <= 1) {
2694 ADDOP(c, PRINT_EXPR);
2695 }
2696 else {
2697 ADDOP(c, POP_TOP);
2698 }
2699 break;
2700 case Pass_kind:
2701 break;
2702 case Break_kind:
2703 if (!c->u->u_nfblocks)
2704 return compiler_error(c, "'break' outside loop");
2705 ADDOP(c, BREAK_LOOP);
2706 break;
2707 case Continue_kind:
2708 return compiler_continue(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002709 case With_kind:
2710 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 }
2712 return 1;
2713}
2714
2715static int
2716unaryop(unaryop_ty op)
2717{
2718 switch (op) {
2719 case Invert:
2720 return UNARY_INVERT;
2721 case Not:
2722 return UNARY_NOT;
2723 case UAdd:
2724 return UNARY_POSITIVE;
2725 case USub:
2726 return UNARY_NEGATIVE;
2727 }
2728 return 0;
2729}
2730
2731static int
2732binop(struct compiler *c, operator_ty op)
2733{
2734 switch (op) {
2735 case Add:
2736 return BINARY_ADD;
2737 case Sub:
2738 return BINARY_SUBTRACT;
2739 case Mult:
2740 return BINARY_MULTIPLY;
2741 case Div:
2742 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2743 return BINARY_TRUE_DIVIDE;
2744 else
2745 return BINARY_DIVIDE;
2746 case Mod:
2747 return BINARY_MODULO;
2748 case Pow:
2749 return BINARY_POWER;
2750 case LShift:
2751 return BINARY_LSHIFT;
2752 case RShift:
2753 return BINARY_RSHIFT;
2754 case BitOr:
2755 return BINARY_OR;
2756 case BitXor:
2757 return BINARY_XOR;
2758 case BitAnd:
2759 return BINARY_AND;
2760 case FloorDiv:
2761 return BINARY_FLOOR_DIVIDE;
2762 }
2763 return 0;
2764}
2765
2766static int
2767cmpop(cmpop_ty op)
2768{
2769 switch (op) {
2770 case Eq:
2771 return PyCmp_EQ;
2772 case NotEq:
2773 return PyCmp_NE;
2774 case Lt:
2775 return PyCmp_LT;
2776 case LtE:
2777 return PyCmp_LE;
2778 case Gt:
2779 return PyCmp_GT;
2780 case GtE:
2781 return PyCmp_GE;
2782 case Is:
2783 return PyCmp_IS;
2784 case IsNot:
2785 return PyCmp_IS_NOT;
2786 case In:
2787 return PyCmp_IN;
2788 case NotIn:
2789 return PyCmp_NOT_IN;
2790 }
2791 return PyCmp_BAD;
2792}
2793
2794static int
2795inplace_binop(struct compiler *c, operator_ty op)
2796{
2797 switch (op) {
2798 case Add:
2799 return INPLACE_ADD;
2800 case Sub:
2801 return INPLACE_SUBTRACT;
2802 case Mult:
2803 return INPLACE_MULTIPLY;
2804 case Div:
2805 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2806 return INPLACE_TRUE_DIVIDE;
2807 else
2808 return INPLACE_DIVIDE;
2809 case Mod:
2810 return INPLACE_MODULO;
2811 case Pow:
2812 return INPLACE_POWER;
2813 case LShift:
2814 return INPLACE_LSHIFT;
2815 case RShift:
2816 return INPLACE_RSHIFT;
2817 case BitOr:
2818 return INPLACE_OR;
2819 case BitXor:
2820 return INPLACE_XOR;
2821 case BitAnd:
2822 return INPLACE_AND;
2823 case FloorDiv:
2824 return INPLACE_FLOOR_DIVIDE;
2825 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002826 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002827 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828 return 0;
2829}
2830
2831static int
2832compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2833{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002834 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2836
2837 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002838 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839 /* XXX AugStore isn't used anywhere! */
2840
2841 /* First check for assignment to __debug__. Param? */
2842 if ((ctx == Store || ctx == AugStore || ctx == Del)
2843 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2844 return compiler_error(c, "can not assign to __debug__");
2845 }
2846
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002847 mangled = _Py_Mangle(c->u->u_private, name);
2848 if (!mangled)
2849 return 0;
2850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851 op = 0;
2852 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002853 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854 switch (scope) {
2855 case FREE:
2856 dict = c->u->u_freevars;
2857 optype = OP_DEREF;
2858 break;
2859 case CELL:
2860 dict = c->u->u_cellvars;
2861 optype = OP_DEREF;
2862 break;
2863 case LOCAL:
2864 if (c->u->u_ste->ste_type == FunctionBlock)
2865 optype = OP_FAST;
2866 break;
2867 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002868 if (c->u->u_ste->ste_type == FunctionBlock &&
2869 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870 optype = OP_GLOBAL;
2871 break;
2872 case GLOBAL_EXPLICIT:
2873 optype = OP_GLOBAL;
2874 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002875 default:
2876 /* scope can be 0 */
2877 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878 }
2879
2880 /* XXX Leave assert here, but handle __doc__ and the like better */
2881 assert(scope || PyString_AS_STRING(name)[0] == '_');
2882
2883 switch (optype) {
2884 case OP_DEREF:
2885 switch (ctx) {
2886 case Load: op = LOAD_DEREF; break;
2887 case Store: op = STORE_DEREF; break;
2888 case AugLoad:
2889 case AugStore:
2890 break;
2891 case Del:
2892 PyErr_Format(PyExc_SyntaxError,
2893 "can not delete variable '%s' referenced "
2894 "in nested scope",
2895 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002896 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002899 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002900 PyErr_SetString(PyExc_SystemError,
2901 "param invalid for deref variable");
2902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903 }
2904 break;
2905 case OP_FAST:
2906 switch (ctx) {
2907 case Load: op = LOAD_FAST; break;
2908 case Store: op = STORE_FAST; break;
2909 case Del: op = DELETE_FAST; break;
2910 case AugLoad:
2911 case AugStore:
2912 break;
2913 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002914 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002915 PyErr_SetString(PyExc_SystemError,
2916 "param invalid for local variable");
2917 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002919 ADDOP_O(c, op, mangled, varnames);
2920 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 return 1;
2922 case OP_GLOBAL:
2923 switch (ctx) {
2924 case Load: op = LOAD_GLOBAL; break;
2925 case Store: op = STORE_GLOBAL; break;
2926 case Del: op = DELETE_GLOBAL; break;
2927 case AugLoad:
2928 case AugStore:
2929 break;
2930 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002931 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002932 PyErr_SetString(PyExc_SystemError,
2933 "param invalid for global variable");
2934 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 }
2936 break;
2937 case OP_NAME:
2938 switch (ctx) {
2939 case Load: op = LOAD_NAME; break;
2940 case Store: op = STORE_NAME; break;
2941 case Del: op = DELETE_NAME; break;
2942 case AugLoad:
2943 case AugStore:
2944 break;
2945 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002946 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002947 PyErr_SetString(PyExc_SystemError,
2948 "param invalid for name variable");
2949 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950 }
2951 break;
2952 }
2953
2954 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002955 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002956 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002957 if (arg < 0)
2958 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002959 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960}
2961
2962static int
2963compiler_boolop(struct compiler *c, expr_ty e)
2964{
2965 basicblock *end;
2966 int jumpi, i, n;
2967 asdl_seq *s;
2968
2969 assert(e->kind == BoolOp_kind);
2970 if (e->v.BoolOp.op == And)
2971 jumpi = JUMP_IF_FALSE;
2972 else
2973 jumpi = JUMP_IF_TRUE;
2974 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002975 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 return 0;
2977 s = e->v.BoolOp.values;
2978 n = asdl_seq_LEN(s) - 1;
2979 for (i = 0; i < n; ++i) {
2980 VISIT(c, expr, asdl_seq_GET(s, i));
2981 ADDOP_JREL(c, jumpi, end);
2982 ADDOP(c, POP_TOP)
2983 }
2984 VISIT(c, expr, asdl_seq_GET(s, n));
2985 compiler_use_next_block(c, end);
2986 return 1;
2987}
2988
2989static int
2990compiler_list(struct compiler *c, expr_ty e)
2991{
2992 int n = asdl_seq_LEN(e->v.List.elts);
2993 if (e->v.List.ctx == Store) {
2994 ADDOP_I(c, UNPACK_SEQUENCE, n);
2995 }
2996 VISIT_SEQ(c, expr, e->v.List.elts);
2997 if (e->v.List.ctx == Load) {
2998 ADDOP_I(c, BUILD_LIST, n);
2999 }
3000 return 1;
3001}
3002
3003static int
3004compiler_tuple(struct compiler *c, expr_ty e)
3005{
3006 int n = asdl_seq_LEN(e->v.Tuple.elts);
3007 if (e->v.Tuple.ctx == Store) {
3008 ADDOP_I(c, UNPACK_SEQUENCE, n);
3009 }
3010 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3011 if (e->v.Tuple.ctx == Load) {
3012 ADDOP_I(c, BUILD_TUPLE, n);
3013 }
3014 return 1;
3015}
3016
3017static int
3018compiler_compare(struct compiler *c, expr_ty e)
3019{
3020 int i, n;
3021 basicblock *cleanup = NULL;
3022
3023 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3024 VISIT(c, expr, e->v.Compare.left);
3025 n = asdl_seq_LEN(e->v.Compare.ops);
3026 assert(n > 0);
3027 if (n > 1) {
3028 cleanup = compiler_new_block(c);
3029 if (cleanup == NULL)
3030 return 0;
3031 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3032 }
3033 for (i = 1; i < n; i++) {
3034 ADDOP(c, DUP_TOP);
3035 ADDOP(c, ROT_THREE);
3036 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3037 ADDOP_I(c, COMPARE_OP,
3038 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3039 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3040 NEXT_BLOCK(c);
3041 ADDOP(c, POP_TOP);
3042 if (i < (n - 1))
3043 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3044 }
3045 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3046 ADDOP_I(c, COMPARE_OP,
3047 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3048 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3049 if (n > 1) {
3050 basicblock *end = compiler_new_block(c);
3051 if (end == NULL)
3052 return 0;
3053 ADDOP_JREL(c, JUMP_FORWARD, end);
3054 compiler_use_next_block(c, cleanup);
3055 ADDOP(c, ROT_TWO);
3056 ADDOP(c, POP_TOP);
3057 compiler_use_next_block(c, end);
3058 }
3059 return 1;
3060}
3061
3062static int
3063compiler_call(struct compiler *c, expr_ty e)
3064{
3065 int n, code = 0;
3066
3067 VISIT(c, expr, e->v.Call.func);
3068 n = asdl_seq_LEN(e->v.Call.args);
3069 VISIT_SEQ(c, expr, e->v.Call.args);
3070 if (e->v.Call.keywords) {
3071 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3072 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3073 }
3074 if (e->v.Call.starargs) {
3075 VISIT(c, expr, e->v.Call.starargs);
3076 code |= 1;
3077 }
3078 if (e->v.Call.kwargs) {
3079 VISIT(c, expr, e->v.Call.kwargs);
3080 code |= 2;
3081 }
3082 switch (code) {
3083 case 0:
3084 ADDOP_I(c, CALL_FUNCTION, n);
3085 break;
3086 case 1:
3087 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3088 break;
3089 case 2:
3090 ADDOP_I(c, CALL_FUNCTION_KW, n);
3091 break;
3092 case 3:
3093 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3094 break;
3095 }
3096 return 1;
3097}
3098
3099static int
3100compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
3101 asdl_seq *generators, int gen_index,
3102 expr_ty elt)
3103{
3104 /* generate code for the iterator, then each of the ifs,
3105 and then write to the element */
3106
3107 comprehension_ty l;
3108 basicblock *start, *anchor, *skip, *if_cleanup;
3109 int i, n;
3110
3111 start = compiler_new_block(c);
3112 skip = compiler_new_block(c);
3113 if_cleanup = compiler_new_block(c);
3114 anchor = compiler_new_block(c);
3115
3116 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3117 anchor == NULL)
3118 return 0;
3119
3120 l = asdl_seq_GET(generators, gen_index);
3121 VISIT(c, expr, l->iter);
3122 ADDOP(c, GET_ITER);
3123 compiler_use_next_block(c, start);
3124 ADDOP_JREL(c, FOR_ITER, anchor);
3125 NEXT_BLOCK(c);
3126 VISIT(c, expr, l->target);
3127
3128 /* XXX this needs to be cleaned up...a lot! */
3129 n = asdl_seq_LEN(l->ifs);
3130 for (i = 0; i < n; i++) {
3131 expr_ty e = asdl_seq_GET(l->ifs, i);
3132 VISIT(c, expr, e);
3133 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3134 NEXT_BLOCK(c);
3135 ADDOP(c, POP_TOP);
3136 }
3137
3138 if (++gen_index < asdl_seq_LEN(generators))
3139 if (!compiler_listcomp_generator(c, tmpname,
3140 generators, gen_index, elt))
3141 return 0;
3142
3143 /* only append after the last for generator */
3144 if (gen_index >= asdl_seq_LEN(generators)) {
3145 if (!compiler_nameop(c, tmpname, Load))
3146 return 0;
3147 VISIT(c, expr, elt);
3148 ADDOP_I(c, CALL_FUNCTION, 1);
3149 ADDOP(c, POP_TOP);
3150
3151 compiler_use_next_block(c, skip);
3152 }
3153 for (i = 0; i < n; i++) {
3154 ADDOP_I(c, JUMP_FORWARD, 1);
3155 if (i == 0)
3156 compiler_use_next_block(c, if_cleanup);
3157 ADDOP(c, POP_TOP);
3158 }
3159 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3160 compiler_use_next_block(c, anchor);
3161 /* delete the append method added to locals */
3162 if (gen_index == 1)
3163 if (!compiler_nameop(c, tmpname, Del))
3164 return 0;
3165
3166 return 1;
3167}
3168
3169static int
3170compiler_listcomp(struct compiler *c, expr_ty e)
3171{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003172 identifier tmp;
3173 int rc = 0;
3174 static identifier append;
3175 asdl_seq *generators = e->v.ListComp.generators;
3176
3177 assert(e->kind == ListComp_kind);
3178 if (!append) {
3179 append = PyString_InternFromString("append");
3180 if (!append)
3181 return 0;
3182 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003183 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184 if (!tmp)
3185 return 0;
3186 ADDOP_I(c, BUILD_LIST, 0);
3187 ADDOP(c, DUP_TOP);
3188 ADDOP_O(c, LOAD_ATTR, append, names);
3189 if (compiler_nameop(c, tmp, Store))
3190 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3191 e->v.ListComp.elt);
3192 Py_DECREF(tmp);
3193 return rc;
3194}
3195
3196static int
3197compiler_genexp_generator(struct compiler *c,
3198 asdl_seq *generators, int gen_index,
3199 expr_ty elt)
3200{
3201 /* generate code for the iterator, then each of the ifs,
3202 and then write to the element */
3203
3204 comprehension_ty ge;
3205 basicblock *start, *anchor, *skip, *if_cleanup, *end;
3206 int i, n;
3207
3208 start = compiler_new_block(c);
3209 skip = compiler_new_block(c);
3210 if_cleanup = compiler_new_block(c);
3211 anchor = compiler_new_block(c);
3212 end = compiler_new_block(c);
3213
3214 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3215 anchor == NULL || end == NULL)
3216 return 0;
3217
3218 ge = asdl_seq_GET(generators, gen_index);
3219 ADDOP_JREL(c, SETUP_LOOP, end);
3220 if (!compiler_push_fblock(c, LOOP, start))
3221 return 0;
3222
3223 if (gen_index == 0) {
3224 /* Receive outermost iter as an implicit argument */
3225 c->u->u_argcount = 1;
3226 ADDOP_I(c, LOAD_FAST, 0);
3227 }
3228 else {
3229 /* Sub-iter - calculate on the fly */
3230 VISIT(c, expr, ge->iter);
3231 ADDOP(c, GET_ITER);
3232 }
3233 compiler_use_next_block(c, start);
3234 ADDOP_JREL(c, FOR_ITER, anchor);
3235 NEXT_BLOCK(c);
3236 VISIT(c, expr, ge->target);
3237
3238 /* XXX this needs to be cleaned up...a lot! */
3239 n = asdl_seq_LEN(ge->ifs);
3240 for (i = 0; i < n; i++) {
3241 expr_ty e = asdl_seq_GET(ge->ifs, i);
3242 VISIT(c, expr, e);
3243 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3244 NEXT_BLOCK(c);
3245 ADDOP(c, POP_TOP);
3246 }
3247
3248 if (++gen_index < asdl_seq_LEN(generators))
3249 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3250 return 0;
3251
3252 /* only append after the last 'for' generator */
3253 if (gen_index >= asdl_seq_LEN(generators)) {
3254 VISIT(c, expr, elt);
3255 ADDOP(c, YIELD_VALUE);
3256 ADDOP(c, POP_TOP);
3257
3258 compiler_use_next_block(c, skip);
3259 }
3260 for (i = 0; i < n; i++) {
3261 ADDOP_I(c, JUMP_FORWARD, 1);
3262 if (i == 0)
3263 compiler_use_next_block(c, if_cleanup);
3264
3265 ADDOP(c, POP_TOP);
3266 }
3267 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3268 compiler_use_next_block(c, anchor);
3269 ADDOP(c, POP_BLOCK);
3270 compiler_pop_fblock(c, LOOP, start);
3271 compiler_use_next_block(c, end);
3272
3273 return 1;
3274}
3275
3276static int
3277compiler_genexp(struct compiler *c, expr_ty e)
3278{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003279 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 PyCodeObject *co;
3281 expr_ty outermost_iter = ((comprehension_ty)
3282 (asdl_seq_GET(e->v.GeneratorExp.generators,
3283 0)))->iter;
3284
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003285 if (!name) {
3286 name = PyString_FromString("<genexpr>");
3287 if (!name)
3288 return 0;
3289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290
3291 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3292 return 0;
3293 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3294 e->v.GeneratorExp.elt);
3295 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003296 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297 if (co == NULL)
3298 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299
3300 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003301 Py_DECREF(co);
3302
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 VISIT(c, expr, outermost_iter);
3304 ADDOP(c, GET_ITER);
3305 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306
3307 return 1;
3308}
3309
3310static int
3311compiler_visit_keyword(struct compiler *c, keyword_ty k)
3312{
3313 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3314 VISIT(c, expr, k->value);
3315 return 1;
3316}
3317
3318/* Test whether expression is constant. For constants, report
3319 whether they are true or false.
3320
3321 Return values: 1 for true, 0 for false, -1 for non-constant.
3322 */
3323
3324static int
3325expr_constant(expr_ty e)
3326{
3327 switch (e->kind) {
3328 case Num_kind:
3329 return PyObject_IsTrue(e->v.Num.n);
3330 case Str_kind:
3331 return PyObject_IsTrue(e->v.Str.s);
3332 default:
3333 return -1;
3334 }
3335}
3336
Guido van Rossumc2e20742006-02-27 22:32:47 +00003337/*
3338 Implements the with statement from PEP 343.
3339
3340 The semantics outlined in that PEP are as follows:
3341
3342 with EXPR as VAR:
3343 BLOCK
3344
3345 It is implemented roughly as:
3346
3347 context = (EXPR).__context__()
3348 exit = context.__exit__ # not calling it
3349 value = context.__enter__()
3350 try:
3351 VAR = value # if VAR present in the syntax
3352 BLOCK
3353 finally:
3354 if an exception was raised:
3355 exc = copy of (exception, instance, traceback)
3356 else:
3357 exc = (None, None, None)
3358 exit(*exc)
3359 */
3360static int
3361compiler_with(struct compiler *c, stmt_ty s)
3362{
3363 static identifier context_attr, enter_attr, exit_attr;
3364 basicblock *block, *finally;
3365 identifier tmpexit, tmpvalue = NULL;
3366
3367 assert(s->kind == With_kind);
3368
3369 if (!context_attr) {
3370 context_attr = PyString_InternFromString("__context__");
3371 if (!context_attr)
3372 return 0;
3373 }
3374 if (!enter_attr) {
3375 enter_attr = PyString_InternFromString("__enter__");
3376 if (!enter_attr)
3377 return 0;
3378 }
3379 if (!exit_attr) {
3380 exit_attr = PyString_InternFromString("__exit__");
3381 if (!exit_attr)
3382 return 0;
3383 }
3384
3385 block = compiler_new_block(c);
3386 finally = compiler_new_block(c);
3387 if (!block || !finally)
3388 return 0;
3389
3390 /* Create a temporary variable to hold context.__exit__ */
3391 tmpexit = compiler_new_tmpname(c);
3392 if (tmpexit == NULL)
3393 return 0;
3394 PyArena_AddPyObject(c->c_arena, tmpexit);
3395
3396 if (s->v.With.optional_vars) {
3397 /* Create a temporary variable to hold context.__enter__().
3398 We need to do this rather than preserving it on the stack
3399 because SETUP_FINALLY remembers the stack level.
3400 We need to do the assignment *inside* the try/finally
3401 so that context.__exit__() is called when the assignment
3402 fails. But we need to call context.__enter__() *before*
3403 the try/finally so that if it fails we won't call
3404 context.__exit__().
3405 */
3406 tmpvalue = compiler_new_tmpname(c);
3407 if (tmpvalue == NULL)
3408 return 0;
3409 PyArena_AddPyObject(c->c_arena, tmpvalue);
3410 }
3411
3412 /* Evaluate (EXPR).__context__() */
3413 VISIT(c, expr, s->v.With.context_expr);
3414 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3415 ADDOP_I(c, CALL_FUNCTION, 0);
3416
3417 /* Squirrel away context.__exit__ */
3418 ADDOP(c, DUP_TOP);
3419 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3420 if (!compiler_nameop(c, tmpexit, Store))
3421 return 0;
3422
3423 /* Call context.__enter__() */
3424 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3425 ADDOP_I(c, CALL_FUNCTION, 0);
3426
3427 if (s->v.With.optional_vars) {
3428 /* Store it in tmpvalue */
3429 if (!compiler_nameop(c, tmpvalue, Store))
3430 return 0;
3431 }
3432 else {
3433 /* Discard result from context.__enter__() */
3434 ADDOP(c, POP_TOP);
3435 }
3436
3437 /* Start the try block */
3438 ADDOP_JREL(c, SETUP_FINALLY, finally);
3439
3440 compiler_use_next_block(c, block);
3441 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3442 return 0;
3443 }
3444
3445 if (s->v.With.optional_vars) {
3446 /* Bind saved result of context.__enter__() to VAR */
3447 if (!compiler_nameop(c, tmpvalue, Load) ||
3448 !compiler_nameop(c, tmpvalue, Del))
3449 return 0;
3450 VISIT(c, expr, s->v.With.optional_vars);
3451 }
3452
3453 /* BLOCK code */
3454 VISIT_SEQ(c, stmt, s->v.With.body);
3455
3456 /* End of try block; start the finally block */
3457 ADDOP(c, POP_BLOCK);
3458 compiler_pop_fblock(c, FINALLY_TRY, block);
3459
3460 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3461 compiler_use_next_block(c, finally);
3462 if (!compiler_push_fblock(c, FINALLY_END, finally))
3463 return 0;
3464
3465 /* Finally block starts; push tmpexit and issue our magic opcode. */
3466 if (!compiler_nameop(c, tmpexit, Load) ||
3467 !compiler_nameop(c, tmpexit, Del))
3468 return 0;
3469 ADDOP(c, WITH_CLEANUP);
3470 ADDOP_I(c, CALL_FUNCTION, 3);
3471 ADDOP(c, POP_TOP);
3472
3473 /* Finally block ends. */
3474 ADDOP(c, END_FINALLY);
3475 compiler_pop_fblock(c, FINALLY_END, finally);
3476 return 1;
3477}
3478
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479static int
3480compiler_visit_expr(struct compiler *c, expr_ty e)
3481{
3482 int i, n;
3483
3484 if (e->lineno > c->u->u_lineno) {
3485 c->u->u_lineno = e->lineno;
3486 c->u->u_lineno_set = false;
3487 }
3488 switch (e->kind) {
3489 case BoolOp_kind:
3490 return compiler_boolop(c, e);
3491 case BinOp_kind:
3492 VISIT(c, expr, e->v.BinOp.left);
3493 VISIT(c, expr, e->v.BinOp.right);
3494 ADDOP(c, binop(c, e->v.BinOp.op));
3495 break;
3496 case UnaryOp_kind:
3497 VISIT(c, expr, e->v.UnaryOp.operand);
3498 ADDOP(c, unaryop(e->v.UnaryOp.op));
3499 break;
3500 case Lambda_kind:
3501 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003502 case IfExp_kind:
3503 return compiler_ifexp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504 case Dict_kind:
3505 /* XXX get rid of arg? */
3506 ADDOP_I(c, BUILD_MAP, 0);
3507 n = asdl_seq_LEN(e->v.Dict.values);
3508 /* We must arrange things just right for STORE_SUBSCR.
3509 It wants the stack to look like (value) (dict) (key) */
3510 for (i = 0; i < n; i++) {
3511 ADDOP(c, DUP_TOP);
3512 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3513 ADDOP(c, ROT_TWO);
3514 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3515 ADDOP(c, STORE_SUBSCR);
3516 }
3517 break;
3518 case ListComp_kind:
3519 return compiler_listcomp(c, e);
3520 case GeneratorExp_kind:
3521 return compiler_genexp(c, e);
3522 case Yield_kind:
3523 if (c->u->u_ste->ste_type != FunctionBlock)
3524 return compiler_error(c, "'yield' outside function");
3525 /*
3526 for (i = 0; i < c->u->u_nfblocks; i++) {
3527 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3528 return compiler_error(
3529 c, "'yield' not allowed in a 'try' "
3530 "block with a 'finally' clause");
3531 }
3532 */
3533 if (e->v.Yield.value) {
3534 VISIT(c, expr, e->v.Yield.value);
3535 }
3536 else {
3537 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3538 }
3539 ADDOP(c, YIELD_VALUE);
3540 break;
3541 case Compare_kind:
3542 return compiler_compare(c, e);
3543 case Call_kind:
3544 return compiler_call(c, e);
3545 case Repr_kind:
3546 VISIT(c, expr, e->v.Repr.value);
3547 ADDOP(c, UNARY_CONVERT);
3548 break;
3549 case Num_kind:
3550 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3551 break;
3552 case Str_kind:
3553 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3554 break;
3555 /* The following exprs can be assignment targets. */
3556 case Attribute_kind:
3557 if (e->v.Attribute.ctx != AugStore)
3558 VISIT(c, expr, e->v.Attribute.value);
3559 switch (e->v.Attribute.ctx) {
3560 case AugLoad:
3561 ADDOP(c, DUP_TOP);
3562 /* Fall through to load */
3563 case Load:
3564 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3565 break;
3566 case AugStore:
3567 ADDOP(c, ROT_TWO);
3568 /* Fall through to save */
3569 case Store:
3570 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3571 break;
3572 case Del:
3573 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3574 break;
3575 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003576 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003577 PyErr_SetString(PyExc_SystemError,
3578 "param invalid in attribute expression");
3579 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 }
3581 break;
3582 case Subscript_kind:
3583 switch (e->v.Subscript.ctx) {
3584 case AugLoad:
3585 VISIT(c, expr, e->v.Subscript.value);
3586 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3587 break;
3588 case Load:
3589 VISIT(c, expr, e->v.Subscript.value);
3590 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3591 break;
3592 case AugStore:
3593 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3594 break;
3595 case Store:
3596 VISIT(c, expr, e->v.Subscript.value);
3597 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3598 break;
3599 case Del:
3600 VISIT(c, expr, e->v.Subscript.value);
3601 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3602 break;
3603 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003604 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003605 PyErr_SetString(PyExc_SystemError,
3606 "param invalid in subscript expression");
3607 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608 }
3609 break;
3610 case Name_kind:
3611 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3612 /* child nodes of List and Tuple will have expr_context set */
3613 case List_kind:
3614 return compiler_list(c, e);
3615 case Tuple_kind:
3616 return compiler_tuple(c, e);
3617 }
3618 return 1;
3619}
3620
3621static int
3622compiler_augassign(struct compiler *c, stmt_ty s)
3623{
3624 expr_ty e = s->v.AugAssign.target;
3625 expr_ty auge;
3626
3627 assert(s->kind == AugAssign_kind);
3628
3629 switch (e->kind) {
3630 case Attribute_kind:
3631 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003632 AugLoad, e->lineno, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 if (auge == NULL)
3634 return 0;
3635 VISIT(c, expr, auge);
3636 VISIT(c, expr, s->v.AugAssign.value);
3637 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3638 auge->v.Attribute.ctx = AugStore;
3639 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640 break;
3641 case Subscript_kind:
3642 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003643 AugLoad, e->lineno, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644 if (auge == NULL)
3645 return 0;
3646 VISIT(c, expr, auge);
3647 VISIT(c, expr, s->v.AugAssign.value);
3648 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3649 auge->v.Subscript.ctx = AugStore;
3650 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 break;
3652 case Name_kind:
3653 VISIT(c, expr, s->v.AugAssign.target);
3654 VISIT(c, expr, s->v.AugAssign.value);
3655 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3656 return compiler_nameop(c, e->v.Name.id, Store);
3657 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003658 PyErr_Format(PyExc_SystemError,
3659 "invalid node type (%d) for augmented assignment",
3660 e->kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661 return 0;
3662 }
3663 return 1;
3664}
3665
3666static int
3667compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3668{
3669 struct fblockinfo *f;
3670 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3671 return 0;
3672 f = &c->u->u_fblock[c->u->u_nfblocks++];
3673 f->fb_type = t;
3674 f->fb_block = b;
3675 return 1;
3676}
3677
3678static void
3679compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3680{
3681 struct compiler_unit *u = c->u;
3682 assert(u->u_nfblocks > 0);
3683 u->u_nfblocks--;
3684 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3685 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3686}
3687
3688/* Raises a SyntaxError and returns 0.
3689 If something goes wrong, a different exception may be raised.
3690*/
3691
3692static int
3693compiler_error(struct compiler *c, const char *errstr)
3694{
3695 PyObject *loc;
3696 PyObject *u = NULL, *v = NULL;
3697
3698 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3699 if (!loc) {
3700 Py_INCREF(Py_None);
3701 loc = Py_None;
3702 }
3703 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3704 Py_None, loc);
3705 if (!u)
3706 goto exit;
3707 v = Py_BuildValue("(zO)", errstr, u);
3708 if (!v)
3709 goto exit;
3710 PyErr_SetObject(PyExc_SyntaxError, v);
3711 exit:
3712 Py_DECREF(loc);
3713 Py_XDECREF(u);
3714 Py_XDECREF(v);
3715 return 0;
3716}
3717
3718static int
3719compiler_handle_subscr(struct compiler *c, const char *kind,
3720 expr_context_ty ctx)
3721{
3722 int op = 0;
3723
3724 /* XXX this code is duplicated */
3725 switch (ctx) {
3726 case AugLoad: /* fall through to Load */
3727 case Load: op = BINARY_SUBSCR; break;
3728 case AugStore:/* fall through to Store */
3729 case Store: op = STORE_SUBSCR; break;
3730 case Del: op = DELETE_SUBSCR; break;
3731 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003732 PyErr_Format(PyExc_SystemError,
3733 "invalid %s kind %d in subscript\n",
3734 kind, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735 return 0;
3736 }
3737 if (ctx == AugLoad) {
3738 ADDOP_I(c, DUP_TOPX, 2);
3739 }
3740 else if (ctx == AugStore) {
3741 ADDOP(c, ROT_THREE);
3742 }
3743 ADDOP(c, op);
3744 return 1;
3745}
3746
3747static int
3748compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3749{
3750 int n = 2;
3751 assert(s->kind == Slice_kind);
3752
3753 /* only handles the cases where BUILD_SLICE is emitted */
3754 if (s->v.Slice.lower) {
3755 VISIT(c, expr, s->v.Slice.lower);
3756 }
3757 else {
3758 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3759 }
3760
3761 if (s->v.Slice.upper) {
3762 VISIT(c, expr, s->v.Slice.upper);
3763 }
3764 else {
3765 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3766 }
3767
3768 if (s->v.Slice.step) {
3769 n++;
3770 VISIT(c, expr, s->v.Slice.step);
3771 }
3772 ADDOP_I(c, BUILD_SLICE, n);
3773 return 1;
3774}
3775
3776static int
3777compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3778{
3779 int op = 0, slice_offset = 0, stack_count = 0;
3780
3781 assert(s->v.Slice.step == NULL);
3782 if (s->v.Slice.lower) {
3783 slice_offset++;
3784 stack_count++;
3785 if (ctx != AugStore)
3786 VISIT(c, expr, s->v.Slice.lower);
3787 }
3788 if (s->v.Slice.upper) {
3789 slice_offset += 2;
3790 stack_count++;
3791 if (ctx != AugStore)
3792 VISIT(c, expr, s->v.Slice.upper);
3793 }
3794
3795 if (ctx == AugLoad) {
3796 switch (stack_count) {
3797 case 0: ADDOP(c, DUP_TOP); break;
3798 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3799 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3800 }
3801 }
3802 else if (ctx == AugStore) {
3803 switch (stack_count) {
3804 case 0: ADDOP(c, ROT_TWO); break;
3805 case 1: ADDOP(c, ROT_THREE); break;
3806 case 2: ADDOP(c, ROT_FOUR); break;
3807 }
3808 }
3809
3810 switch (ctx) {
3811 case AugLoad: /* fall through to Load */
3812 case Load: op = SLICE; break;
3813 case AugStore:/* fall through to Store */
3814 case Store: op = STORE_SLICE; break;
3815 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003816 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003817 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003818 PyErr_SetString(PyExc_SystemError,
3819 "param invalid in simple slice");
3820 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003821 }
3822
3823 ADDOP(c, op + slice_offset);
3824 return 1;
3825}
3826
3827static int
3828compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3829 expr_context_ty ctx)
3830{
3831 switch (s->kind) {
3832 case Ellipsis_kind:
3833 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3834 break;
3835 case Slice_kind:
3836 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003837 case Index_kind:
3838 VISIT(c, expr, s->v.Index.value);
3839 break;
3840 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003841 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003842 PyErr_SetString(PyExc_SystemError,
3843 "extended slice invalid in nested slice");
3844 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003845 }
3846 return 1;
3847}
3848
3849
3850static int
3851compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3852{
3853 switch (s->kind) {
3854 case Ellipsis_kind:
3855 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3856 break;
3857 case Slice_kind:
3858 if (!s->v.Slice.step)
3859 return compiler_simple_slice(c, s, ctx);
3860 if (!compiler_slice(c, s, ctx))
3861 return 0;
3862 if (ctx == AugLoad) {
3863 ADDOP_I(c, DUP_TOPX, 2);
3864 }
3865 else if (ctx == AugStore) {
3866 ADDOP(c, ROT_THREE);
3867 }
3868 return compiler_handle_subscr(c, "slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003869 case ExtSlice_kind: {
3870 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3871 for (i = 0; i < n; i++) {
3872 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3873 if (!compiler_visit_nested_slice(c, sub, ctx))
3874 return 0;
3875 }
3876 ADDOP_I(c, BUILD_TUPLE, n);
3877 return compiler_handle_subscr(c, "extended slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 }
3879 case Index_kind:
3880 if (ctx != AugStore)
3881 VISIT(c, expr, s->v.Index.value);
3882 return compiler_handle_subscr(c, "index", ctx);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003883 default:
3884 PyErr_Format(PyExc_SystemError,
3885 "invalid slice %d", s->kind);
3886 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887 }
3888 return 1;
3889}
3890
3891/* do depth-first search of basic block graph, starting with block.
3892 post records the block indices in post-order.
3893
3894 XXX must handle implicit jumps from one block to next
3895*/
3896
3897static void
3898dfs(struct compiler *c, basicblock *b, struct assembler *a)
3899{
3900 int i;
3901 struct instr *instr = NULL;
3902
3903 if (b->b_seen)
3904 return;
3905 b->b_seen = 1;
3906 if (b->b_next != NULL)
3907 dfs(c, b->b_next, a);
3908 for (i = 0; i < b->b_iused; i++) {
3909 instr = &b->b_instr[i];
3910 if (instr->i_jrel || instr->i_jabs)
3911 dfs(c, instr->i_target, a);
3912 }
3913 a->a_postorder[a->a_nblocks++] = b;
3914}
3915
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003916static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003917stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3918{
3919 int i;
3920 struct instr *instr;
3921 if (b->b_seen || b->b_startdepth >= depth)
3922 return maxdepth;
3923 b->b_seen = 1;
3924 b->b_startdepth = depth;
3925 for (i = 0; i < b->b_iused; i++) {
3926 instr = &b->b_instr[i];
3927 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3928 if (depth > maxdepth)
3929 maxdepth = depth;
3930 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3931 if (instr->i_jrel || instr->i_jabs) {
3932 maxdepth = stackdepth_walk(c, instr->i_target,
3933 depth, maxdepth);
3934 if (instr->i_opcode == JUMP_ABSOLUTE ||
3935 instr->i_opcode == JUMP_FORWARD) {
3936 goto out; /* remaining code is dead */
3937 }
3938 }
3939 }
3940 if (b->b_next)
3941 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3942out:
3943 b->b_seen = 0;
3944 return maxdepth;
3945}
3946
3947/* Find the flow path that needs the largest stack. We assume that
3948 * cycles in the flow graph have no net effect on the stack depth.
3949 */
3950static int
3951stackdepth(struct compiler *c)
3952{
3953 basicblock *b, *entryblock;
3954 entryblock = NULL;
3955 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3956 b->b_seen = 0;
3957 b->b_startdepth = INT_MIN;
3958 entryblock = b;
3959 }
3960 return stackdepth_walk(c, entryblock, 0, 0);
3961}
3962
3963static int
3964assemble_init(struct assembler *a, int nblocks, int firstlineno)
3965{
3966 memset(a, 0, sizeof(struct assembler));
3967 a->a_lineno = firstlineno;
3968 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3969 if (!a->a_bytecode)
3970 return 0;
3971 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3972 if (!a->a_lnotab)
3973 return 0;
3974 a->a_postorder = (basicblock **)PyObject_Malloc(
3975 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003976 if (!a->a_postorder) {
3977 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003978 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003979 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980 return 1;
3981}
3982
3983static void
3984assemble_free(struct assembler *a)
3985{
3986 Py_XDECREF(a->a_bytecode);
3987 Py_XDECREF(a->a_lnotab);
3988 if (a->a_postorder)
3989 PyObject_Free(a->a_postorder);
3990}
3991
3992/* Return the size of a basic block in bytes. */
3993
3994static int
3995instrsize(struct instr *instr)
3996{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003997 if (!instr->i_hasarg)
3998 return 1;
3999 if (instr->i_oparg > 0xffff)
4000 return 6;
4001 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004002}
4003
4004static int
4005blocksize(basicblock *b)
4006{
4007 int i;
4008 int size = 0;
4009
4010 for (i = 0; i < b->b_iused; i++)
4011 size += instrsize(&b->b_instr[i]);
4012 return size;
4013}
4014
4015/* All about a_lnotab.
4016
4017c_lnotab is an array of unsigned bytes disguised as a Python string.
4018It is used to map bytecode offsets to source code line #s (when needed
4019for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004020
Tim Peters2a7f3842001-06-09 09:26:21 +00004021The array is conceptually a list of
4022 (bytecode offset increment, line number increment)
4023pairs. The details are important and delicate, best illustrated by example:
4024
4025 byte code offset source code line number
4026 0 1
4027 6 2
4028 50 7
4029 350 307
4030 361 308
4031
4032The first trick is that these numbers aren't stored, only the increments
4033from one row to the next (this doesn't really work, but it's a start):
4034
4035 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4036
4037The second trick is that an unsigned byte can't hold negative values, or
4038values larger than 255, so (a) there's a deep assumption that byte code
4039offsets and their corresponding line #s both increase monotonically, and (b)
4040if at least one column jumps by more than 255 from one row to the next, more
4041than one pair is written to the table. In case #b, there's no way to know
4042from looking at the table later how many were written. That's the delicate
4043part. A user of c_lnotab desiring to find the source line number
4044corresponding to a bytecode address A should do something like this
4045
4046 lineno = addr = 0
4047 for addr_incr, line_incr in c_lnotab:
4048 addr += addr_incr
4049 if addr > A:
4050 return lineno
4051 lineno += line_incr
4052
4053In order for this to work, when the addr field increments by more than 255,
4054the line # increment in each pair generated must be 0 until the remaining addr
4055increment is < 256. So, in the example above, com_set_lineno should not (as
4056was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
4057255, 0, 45, 255, 0, 45.
4058*/
4059
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004060static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004062{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063 int d_bytecode, d_lineno;
4064 int len;
4065 char *lnotab;
4066
4067 d_bytecode = a->a_offset - a->a_lineno_off;
4068 d_lineno = i->i_lineno - a->a_lineno;
4069
4070 assert(d_bytecode >= 0);
4071 assert(d_lineno >= 0);
4072
4073 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004074 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004075
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004076 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004077 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004078 nbytes = a->a_lnotab_off + 2 * ncodes;
4079 len = PyString_GET_SIZE(a->a_lnotab);
4080 if (nbytes >= len) {
4081 if (len * 2 < nbytes)
4082 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004083 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004084 len *= 2;
4085 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4086 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004087 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004088 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004089 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090 *lnotab++ = 255;
4091 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004092 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093 d_bytecode -= ncodes * 255;
4094 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004095 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096 assert(d_bytecode <= 255);
4097 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004098 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004099 nbytes = a->a_lnotab_off + 2 * ncodes;
4100 len = PyString_GET_SIZE(a->a_lnotab);
4101 if (nbytes >= len) {
4102 if (len * 2 < nbytes)
4103 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004104 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105 len *= 2;
4106 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4107 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004108 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4110 *lnotab++ = 255;
4111 *lnotab++ = d_bytecode;
4112 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004113 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 *lnotab++ = 255;
4115 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004116 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117 d_lineno -= ncodes * 255;
4118 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004119 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121 len = PyString_GET_SIZE(a->a_lnotab);
4122 if (a->a_lnotab_off + 2 >= len) {
4123 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004124 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004125 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004127
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128 a->a_lnotab_off += 2;
4129 if (d_bytecode) {
4130 *lnotab++ = d_bytecode;
4131 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004132 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133 else { /* First line of a block; def stmt, etc. */
4134 *lnotab++ = 0;
4135 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004136 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004137 a->a_lineno = i->i_lineno;
4138 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004139 return 1;
4140}
4141
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004142/* assemble_emit()
4143 Extend the bytecode with a new instruction.
4144 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004145*/
4146
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004147static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004149{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004150 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151 int len = PyString_GET_SIZE(a->a_bytecode);
4152 char *code;
4153
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004154 size = instrsize(i);
4155 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004156 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004157 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004158 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161 if (a->a_offset + size >= len) {
4162 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004163 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004164 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4166 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004167 if (size == 6) {
4168 assert(i->i_hasarg);
4169 *code++ = (char)EXTENDED_ARG;
4170 *code++ = ext & 0xff;
4171 *code++ = ext >> 8;
4172 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004173 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004174 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004175 if (i->i_hasarg) {
4176 assert(size == 3 || size == 6);
4177 *code++ = arg & 0xff;
4178 *code++ = arg >> 8;
4179 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004180 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004181}
4182
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004183static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004185{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004187 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004188 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190 /* Compute the size of each block and fixup jump args.
4191 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004192start:
4193 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004195 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004196 bsize = blocksize(b);
4197 b->b_offset = totsize;
4198 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004199 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004200 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4202 bsize = b->b_offset;
4203 for (i = 0; i < b->b_iused; i++) {
4204 struct instr *instr = &b->b_instr[i];
4205 /* Relative jumps are computed relative to
4206 the instruction pointer after fetching
4207 the jump instruction.
4208 */
4209 bsize += instrsize(instr);
4210 if (instr->i_jabs)
4211 instr->i_oparg = instr->i_target->b_offset;
4212 else if (instr->i_jrel) {
4213 int delta = instr->i_target->b_offset - bsize;
4214 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004215 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004216 else
4217 continue;
4218 if (instr->i_oparg > 0xffff)
4219 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004220 }
4221 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004222
4223 /* XXX: This is an awful hack that could hurt performance, but
4224 on the bright side it should work until we come up
4225 with a better solution.
4226
4227 In the meantime, should the goto be dropped in favor
4228 of a loop?
4229
4230 The issue is that in the first loop blocksize() is called
4231 which calls instrsize() which requires i_oparg be set
4232 appropriately. There is a bootstrap problem because
4233 i_oparg is calculated in the second loop above.
4234
4235 So we loop until we stop seeing new EXTENDED_ARGs.
4236 The only EXTENDED_ARGs that could be popping up are
4237 ones in jump instructions. So this should converge
4238 fairly quickly.
4239 */
4240 if (last_extended_arg_count != extended_arg_count) {
4241 last_extended_arg_count = extended_arg_count;
4242 goto start;
4243 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004244}
4245
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004246static PyObject *
4247dict_keys_inorder(PyObject *dict, int offset)
4248{
4249 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004250 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004251
4252 tuple = PyTuple_New(size);
4253 if (tuple == NULL)
4254 return NULL;
4255 while (PyDict_Next(dict, &pos, &k, &v)) {
4256 i = PyInt_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004258 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004259 assert((i - offset) < size);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004260 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004261 PyTuple_SET_ITEM(tuple, i - offset, k);
4262 }
4263 return tuple;
4264}
4265
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004266static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004267compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004268{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004269 PySTEntryObject *ste = c->u->u_ste;
4270 int flags = 0, n;
4271 if (ste->ste_type != ModuleBlock)
4272 flags |= CO_NEWLOCALS;
4273 if (ste->ste_type == FunctionBlock) {
4274 if (!ste->ste_unoptimized)
4275 flags |= CO_OPTIMIZED;
4276 if (ste->ste_nested)
4277 flags |= CO_NESTED;
4278 if (ste->ste_generator)
4279 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004280 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004281 if (ste->ste_varargs)
4282 flags |= CO_VARARGS;
4283 if (ste->ste_varkeywords)
4284 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004285 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004286 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004287
4288 /* (Only) inherit compilerflags in PyCF_MASK */
4289 flags |= (c->c_flags->cf_flags & PyCF_MASK);
4290
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291 n = PyDict_Size(c->u->u_freevars);
4292 if (n < 0)
4293 return -1;
4294 if (n == 0) {
4295 n = PyDict_Size(c->u->u_cellvars);
4296 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004297 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004298 if (n == 0) {
4299 flags |= CO_NOFREE;
4300 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004301 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004302
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004303 return flags;
4304}
4305
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004306static PyCodeObject *
4307makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004308{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004309 PyObject *tmp;
4310 PyCodeObject *co = NULL;
4311 PyObject *consts = NULL;
4312 PyObject *names = NULL;
4313 PyObject *varnames = NULL;
4314 PyObject *filename = NULL;
4315 PyObject *name = NULL;
4316 PyObject *freevars = NULL;
4317 PyObject *cellvars = NULL;
4318 PyObject *bytecode = NULL;
4319 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004320
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321 tmp = dict_keys_inorder(c->u->u_consts, 0);
4322 if (!tmp)
4323 goto error;
4324 consts = PySequence_List(tmp); /* optimize_code requires a list */
4325 Py_DECREF(tmp);
4326
4327 names = dict_keys_inorder(c->u->u_names, 0);
4328 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4329 if (!consts || !names || !varnames)
4330 goto error;
4331
4332 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4333 if (!cellvars)
4334 goto error;
4335 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4336 if (!freevars)
4337 goto error;
4338 filename = PyString_FromString(c->c_filename);
4339 if (!filename)
4340 goto error;
4341
4342 nlocals = PyDict_Size(c->u->u_varnames);
4343 flags = compute_code_flags(c);
4344 if (flags < 0)
4345 goto error;
4346
4347 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4348 if (!bytecode)
4349 goto error;
4350
4351 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4352 if (!tmp)
4353 goto error;
4354 Py_DECREF(consts);
4355 consts = tmp;
4356
4357 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4358 bytecode, consts, names, varnames,
4359 freevars, cellvars,
4360 filename, c->u->u_name,
4361 c->u->u_firstlineno,
4362 a->a_lnotab);
4363 error:
4364 Py_XDECREF(consts);
4365 Py_XDECREF(names);
4366 Py_XDECREF(varnames);
4367 Py_XDECREF(filename);
4368 Py_XDECREF(name);
4369 Py_XDECREF(freevars);
4370 Py_XDECREF(cellvars);
4371 Py_XDECREF(bytecode);
4372 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004373}
4374
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004375static PyCodeObject *
4376assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004377{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378 basicblock *b, *entryblock;
4379 struct assembler a;
4380 int i, j, nblocks;
4381 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004382
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004383 /* Make sure every block that falls off the end returns None.
4384 XXX NEXT_BLOCK() isn't quite right, because if the last
4385 block ends with a jump or return b_next shouldn't set.
4386 */
4387 if (!c->u->u_curblock->b_return) {
4388 NEXT_BLOCK(c);
4389 if (addNone)
4390 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4391 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004392 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004394 nblocks = 0;
4395 entryblock = NULL;
4396 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4397 nblocks++;
4398 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004399 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004400
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004401 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4402 goto error;
4403 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004404
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004406 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408 /* Emit code in reverse postorder from dfs. */
4409 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004410 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411 for (j = 0; j < b->b_iused; j++)
4412 if (!assemble_emit(&a, &b->b_instr[j]))
4413 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004414 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004415
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004416 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4417 goto error;
4418 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4419 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004420
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421 co = makecode(c, &a);
4422 error:
4423 assemble_free(&a);
4424 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004425}