blob: 9705ce4e398a2656223a881070ed9169a3cf0b1c [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);
2455 for (i = 0; i < n; i++) {
2456 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2457 int r;
2458
2459 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2460 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2461
2462 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002463 r = compiler_import_as(c, alias->name, alias->asname);
2464 if (!r)
2465 return r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 }
2467 else {
2468 identifier tmp = alias->name;
2469 const char *base = PyString_AS_STRING(alias->name);
2470 char *dot = strchr(base, '.');
2471 if (dot)
2472 tmp = PyString_FromStringAndSize(base,
2473 dot - base);
2474 r = compiler_nameop(c, tmp, Store);
2475 if (dot) {
2476 Py_DECREF(tmp);
2477 }
2478 if (!r)
2479 return r;
2480 }
2481 }
2482 return 1;
2483}
2484
2485static int
2486compiler_from_import(struct compiler *c, stmt_ty s)
2487{
2488 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489
2490 PyObject *names = PyTuple_New(n);
2491 if (!names)
2492 return 0;
2493
2494 /* build up the names */
2495 for (i = 0; i < n; i++) {
2496 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2497 Py_INCREF(alias->name);
2498 PyTuple_SET_ITEM(names, i, alias->name);
2499 }
2500
2501 if (s->lineno > c->c_future->ff_lineno) {
2502 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2503 "__future__")) {
2504 Py_DECREF(names);
2505 return compiler_error(c,
2506 "from __future__ imports must occur "
2507 "at the beginning of the file");
2508
2509 }
2510 }
2511
2512 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002513 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2515 for (i = 0; i < n; i++) {
2516 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2517 identifier store_name;
2518
2519 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2520 assert(n == 1);
2521 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002522 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523 }
2524
2525 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2526 store_name = alias->name;
2527 if (alias->asname)
2528 store_name = alias->asname;
2529
2530 if (!compiler_nameop(c, store_name, Store)) {
2531 Py_DECREF(names);
2532 return 0;
2533 }
2534 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002535 /* remove imported module */
2536 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 return 1;
2538}
2539
2540static int
2541compiler_assert(struct compiler *c, stmt_ty s)
2542{
2543 static PyObject *assertion_error = NULL;
2544 basicblock *end;
2545
2546 if (Py_OptimizeFlag)
2547 return 1;
2548 if (assertion_error == NULL) {
2549 assertion_error = PyString_FromString("AssertionError");
2550 if (assertion_error == NULL)
2551 return 0;
2552 }
2553 VISIT(c, expr, s->v.Assert.test);
2554 end = compiler_new_block(c);
2555 if (end == NULL)
2556 return 0;
2557 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2558 ADDOP(c, POP_TOP);
2559 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2560 if (s->v.Assert.msg) {
2561 VISIT(c, expr, s->v.Assert.msg);
2562 ADDOP_I(c, RAISE_VARARGS, 2);
2563 }
2564 else {
2565 ADDOP_I(c, RAISE_VARARGS, 1);
2566 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002567 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 ADDOP(c, POP_TOP);
2569 return 1;
2570}
2571
2572static int
2573compiler_visit_stmt(struct compiler *c, stmt_ty s)
2574{
2575 int i, n;
2576
2577 c->u->u_lineno = s->lineno;
2578 c->u->u_lineno_set = false;
2579 switch (s->kind) {
2580 case FunctionDef_kind:
2581 return compiler_function(c, s);
2582 case ClassDef_kind:
2583 return compiler_class(c, s);
2584 case Return_kind:
2585 if (c->u->u_ste->ste_type != FunctionBlock)
2586 return compiler_error(c, "'return' outside function");
2587 if (s->v.Return.value) {
2588 if (c->u->u_ste->ste_generator) {
2589 return compiler_error(c,
2590 "'return' with argument inside generator");
2591 }
2592 VISIT(c, expr, s->v.Return.value);
2593 }
2594 else
2595 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2596 ADDOP(c, RETURN_VALUE);
2597 break;
2598 case Delete_kind:
2599 VISIT_SEQ(c, expr, s->v.Delete.targets)
2600 break;
2601 case Assign_kind:
2602 n = asdl_seq_LEN(s->v.Assign.targets);
2603 VISIT(c, expr, s->v.Assign.value);
2604 for (i = 0; i < n; i++) {
2605 if (i < n - 1)
2606 ADDOP(c, DUP_TOP);
2607 VISIT(c, expr,
2608 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2609 }
2610 break;
2611 case AugAssign_kind:
2612 return compiler_augassign(c, s);
2613 case Print_kind:
2614 return compiler_print(c, s);
2615 case For_kind:
2616 return compiler_for(c, s);
2617 case While_kind:
2618 return compiler_while(c, s);
2619 case If_kind:
2620 return compiler_if(c, s);
2621 case Raise_kind:
2622 n = 0;
2623 if (s->v.Raise.type) {
2624 VISIT(c, expr, s->v.Raise.type);
2625 n++;
2626 if (s->v.Raise.inst) {
2627 VISIT(c, expr, s->v.Raise.inst);
2628 n++;
2629 if (s->v.Raise.tback) {
2630 VISIT(c, expr, s->v.Raise.tback);
2631 n++;
2632 }
2633 }
2634 }
2635 ADDOP_I(c, RAISE_VARARGS, n);
2636 break;
2637 case TryExcept_kind:
2638 return compiler_try_except(c, s);
2639 case TryFinally_kind:
2640 return compiler_try_finally(c, s);
2641 case Assert_kind:
2642 return compiler_assert(c, s);
2643 case Import_kind:
2644 return compiler_import(c, s);
2645 case ImportFrom_kind:
2646 return compiler_from_import(c, s);
2647 case Exec_kind:
2648 VISIT(c, expr, s->v.Exec.body);
2649 if (s->v.Exec.globals) {
2650 VISIT(c, expr, s->v.Exec.globals);
2651 if (s->v.Exec.locals) {
2652 VISIT(c, expr, s->v.Exec.locals);
2653 } else {
2654 ADDOP(c, DUP_TOP);
2655 }
2656 } else {
2657 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2658 ADDOP(c, DUP_TOP);
2659 }
2660 ADDOP(c, EXEC_STMT);
2661 break;
2662 case Global_kind:
2663 break;
2664 case Expr_kind:
2665 VISIT(c, expr, s->v.Expr.value);
2666 if (c->c_interactive && c->c_nestlevel <= 1) {
2667 ADDOP(c, PRINT_EXPR);
2668 }
2669 else {
2670 ADDOP(c, POP_TOP);
2671 }
2672 break;
2673 case Pass_kind:
2674 break;
2675 case Break_kind:
2676 if (!c->u->u_nfblocks)
2677 return compiler_error(c, "'break' outside loop");
2678 ADDOP(c, BREAK_LOOP);
2679 break;
2680 case Continue_kind:
2681 return compiler_continue(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002682 case With_kind:
2683 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 }
2685 return 1;
2686}
2687
2688static int
2689unaryop(unaryop_ty op)
2690{
2691 switch (op) {
2692 case Invert:
2693 return UNARY_INVERT;
2694 case Not:
2695 return UNARY_NOT;
2696 case UAdd:
2697 return UNARY_POSITIVE;
2698 case USub:
2699 return UNARY_NEGATIVE;
2700 }
2701 return 0;
2702}
2703
2704static int
2705binop(struct compiler *c, operator_ty op)
2706{
2707 switch (op) {
2708 case Add:
2709 return BINARY_ADD;
2710 case Sub:
2711 return BINARY_SUBTRACT;
2712 case Mult:
2713 return BINARY_MULTIPLY;
2714 case Div:
2715 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2716 return BINARY_TRUE_DIVIDE;
2717 else
2718 return BINARY_DIVIDE;
2719 case Mod:
2720 return BINARY_MODULO;
2721 case Pow:
2722 return BINARY_POWER;
2723 case LShift:
2724 return BINARY_LSHIFT;
2725 case RShift:
2726 return BINARY_RSHIFT;
2727 case BitOr:
2728 return BINARY_OR;
2729 case BitXor:
2730 return BINARY_XOR;
2731 case BitAnd:
2732 return BINARY_AND;
2733 case FloorDiv:
2734 return BINARY_FLOOR_DIVIDE;
2735 }
2736 return 0;
2737}
2738
2739static int
2740cmpop(cmpop_ty op)
2741{
2742 switch (op) {
2743 case Eq:
2744 return PyCmp_EQ;
2745 case NotEq:
2746 return PyCmp_NE;
2747 case Lt:
2748 return PyCmp_LT;
2749 case LtE:
2750 return PyCmp_LE;
2751 case Gt:
2752 return PyCmp_GT;
2753 case GtE:
2754 return PyCmp_GE;
2755 case Is:
2756 return PyCmp_IS;
2757 case IsNot:
2758 return PyCmp_IS_NOT;
2759 case In:
2760 return PyCmp_IN;
2761 case NotIn:
2762 return PyCmp_NOT_IN;
2763 }
2764 return PyCmp_BAD;
2765}
2766
2767static int
2768inplace_binop(struct compiler *c, operator_ty op)
2769{
2770 switch (op) {
2771 case Add:
2772 return INPLACE_ADD;
2773 case Sub:
2774 return INPLACE_SUBTRACT;
2775 case Mult:
2776 return INPLACE_MULTIPLY;
2777 case Div:
2778 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2779 return INPLACE_TRUE_DIVIDE;
2780 else
2781 return INPLACE_DIVIDE;
2782 case Mod:
2783 return INPLACE_MODULO;
2784 case Pow:
2785 return INPLACE_POWER;
2786 case LShift:
2787 return INPLACE_LSHIFT;
2788 case RShift:
2789 return INPLACE_RSHIFT;
2790 case BitOr:
2791 return INPLACE_OR;
2792 case BitXor:
2793 return INPLACE_XOR;
2794 case BitAnd:
2795 return INPLACE_AND;
2796 case FloorDiv:
2797 return INPLACE_FLOOR_DIVIDE;
2798 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002799 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002800 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801 return 0;
2802}
2803
2804static int
2805compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2806{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002807 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002808 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2809
2810 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002811 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002812 /* XXX AugStore isn't used anywhere! */
2813
2814 /* First check for assignment to __debug__. Param? */
2815 if ((ctx == Store || ctx == AugStore || ctx == Del)
2816 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2817 return compiler_error(c, "can not assign to __debug__");
2818 }
2819
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002820 mangled = _Py_Mangle(c->u->u_private, name);
2821 if (!mangled)
2822 return 0;
2823
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824 op = 0;
2825 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002826 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827 switch (scope) {
2828 case FREE:
2829 dict = c->u->u_freevars;
2830 optype = OP_DEREF;
2831 break;
2832 case CELL:
2833 dict = c->u->u_cellvars;
2834 optype = OP_DEREF;
2835 break;
2836 case LOCAL:
2837 if (c->u->u_ste->ste_type == FunctionBlock)
2838 optype = OP_FAST;
2839 break;
2840 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002841 if (c->u->u_ste->ste_type == FunctionBlock &&
2842 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843 optype = OP_GLOBAL;
2844 break;
2845 case GLOBAL_EXPLICIT:
2846 optype = OP_GLOBAL;
2847 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002848 default:
2849 /* scope can be 0 */
2850 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851 }
2852
2853 /* XXX Leave assert here, but handle __doc__ and the like better */
2854 assert(scope || PyString_AS_STRING(name)[0] == '_');
2855
2856 switch (optype) {
2857 case OP_DEREF:
2858 switch (ctx) {
2859 case Load: op = LOAD_DEREF; break;
2860 case Store: op = STORE_DEREF; break;
2861 case AugLoad:
2862 case AugStore:
2863 break;
2864 case Del:
2865 PyErr_Format(PyExc_SyntaxError,
2866 "can not delete variable '%s' referenced "
2867 "in nested scope",
2868 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002869 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002872 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002873 PyErr_SetString(PyExc_SystemError,
2874 "param invalid for deref variable");
2875 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876 }
2877 break;
2878 case OP_FAST:
2879 switch (ctx) {
2880 case Load: op = LOAD_FAST; break;
2881 case Store: op = STORE_FAST; break;
2882 case Del: op = DELETE_FAST; break;
2883 case AugLoad:
2884 case AugStore:
2885 break;
2886 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002887 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002888 PyErr_SetString(PyExc_SystemError,
2889 "param invalid for local variable");
2890 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002892 ADDOP_O(c, op, mangled, varnames);
2893 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894 return 1;
2895 case OP_GLOBAL:
2896 switch (ctx) {
2897 case Load: op = LOAD_GLOBAL; break;
2898 case Store: op = STORE_GLOBAL; break;
2899 case Del: op = DELETE_GLOBAL; break;
2900 case AugLoad:
2901 case AugStore:
2902 break;
2903 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002904 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002905 PyErr_SetString(PyExc_SystemError,
2906 "param invalid for global variable");
2907 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908 }
2909 break;
2910 case OP_NAME:
2911 switch (ctx) {
2912 case Load: op = LOAD_NAME; break;
2913 case Store: op = STORE_NAME; break;
2914 case Del: op = DELETE_NAME; break;
2915 case AugLoad:
2916 case AugStore:
2917 break;
2918 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002919 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002920 PyErr_SetString(PyExc_SystemError,
2921 "param invalid for name variable");
2922 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 }
2924 break;
2925 }
2926
2927 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002928 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002929 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002930 if (arg < 0)
2931 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002932 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933}
2934
2935static int
2936compiler_boolop(struct compiler *c, expr_ty e)
2937{
2938 basicblock *end;
2939 int jumpi, i, n;
2940 asdl_seq *s;
2941
2942 assert(e->kind == BoolOp_kind);
2943 if (e->v.BoolOp.op == And)
2944 jumpi = JUMP_IF_FALSE;
2945 else
2946 jumpi = JUMP_IF_TRUE;
2947 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002948 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949 return 0;
2950 s = e->v.BoolOp.values;
2951 n = asdl_seq_LEN(s) - 1;
2952 for (i = 0; i < n; ++i) {
2953 VISIT(c, expr, asdl_seq_GET(s, i));
2954 ADDOP_JREL(c, jumpi, end);
2955 ADDOP(c, POP_TOP)
2956 }
2957 VISIT(c, expr, asdl_seq_GET(s, n));
2958 compiler_use_next_block(c, end);
2959 return 1;
2960}
2961
2962static int
2963compiler_list(struct compiler *c, expr_ty e)
2964{
2965 int n = asdl_seq_LEN(e->v.List.elts);
2966 if (e->v.List.ctx == Store) {
2967 ADDOP_I(c, UNPACK_SEQUENCE, n);
2968 }
2969 VISIT_SEQ(c, expr, e->v.List.elts);
2970 if (e->v.List.ctx == Load) {
2971 ADDOP_I(c, BUILD_LIST, n);
2972 }
2973 return 1;
2974}
2975
2976static int
2977compiler_tuple(struct compiler *c, expr_ty e)
2978{
2979 int n = asdl_seq_LEN(e->v.Tuple.elts);
2980 if (e->v.Tuple.ctx == Store) {
2981 ADDOP_I(c, UNPACK_SEQUENCE, n);
2982 }
2983 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2984 if (e->v.Tuple.ctx == Load) {
2985 ADDOP_I(c, BUILD_TUPLE, n);
2986 }
2987 return 1;
2988}
2989
2990static int
2991compiler_compare(struct compiler *c, expr_ty e)
2992{
2993 int i, n;
2994 basicblock *cleanup = NULL;
2995
2996 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2997 VISIT(c, expr, e->v.Compare.left);
2998 n = asdl_seq_LEN(e->v.Compare.ops);
2999 assert(n > 0);
3000 if (n > 1) {
3001 cleanup = compiler_new_block(c);
3002 if (cleanup == NULL)
3003 return 0;
3004 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3005 }
3006 for (i = 1; i < n; i++) {
3007 ADDOP(c, DUP_TOP);
3008 ADDOP(c, ROT_THREE);
3009 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3010 ADDOP_I(c, COMPARE_OP,
3011 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3012 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3013 NEXT_BLOCK(c);
3014 ADDOP(c, POP_TOP);
3015 if (i < (n - 1))
3016 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3017 }
3018 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3019 ADDOP_I(c, COMPARE_OP,
3020 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3021 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3022 if (n > 1) {
3023 basicblock *end = compiler_new_block(c);
3024 if (end == NULL)
3025 return 0;
3026 ADDOP_JREL(c, JUMP_FORWARD, end);
3027 compiler_use_next_block(c, cleanup);
3028 ADDOP(c, ROT_TWO);
3029 ADDOP(c, POP_TOP);
3030 compiler_use_next_block(c, end);
3031 }
3032 return 1;
3033}
3034
3035static int
3036compiler_call(struct compiler *c, expr_ty e)
3037{
3038 int n, code = 0;
3039
3040 VISIT(c, expr, e->v.Call.func);
3041 n = asdl_seq_LEN(e->v.Call.args);
3042 VISIT_SEQ(c, expr, e->v.Call.args);
3043 if (e->v.Call.keywords) {
3044 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3045 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3046 }
3047 if (e->v.Call.starargs) {
3048 VISIT(c, expr, e->v.Call.starargs);
3049 code |= 1;
3050 }
3051 if (e->v.Call.kwargs) {
3052 VISIT(c, expr, e->v.Call.kwargs);
3053 code |= 2;
3054 }
3055 switch (code) {
3056 case 0:
3057 ADDOP_I(c, CALL_FUNCTION, n);
3058 break;
3059 case 1:
3060 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3061 break;
3062 case 2:
3063 ADDOP_I(c, CALL_FUNCTION_KW, n);
3064 break;
3065 case 3:
3066 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3067 break;
3068 }
3069 return 1;
3070}
3071
3072static int
3073compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
3074 asdl_seq *generators, int gen_index,
3075 expr_ty elt)
3076{
3077 /* generate code for the iterator, then each of the ifs,
3078 and then write to the element */
3079
3080 comprehension_ty l;
3081 basicblock *start, *anchor, *skip, *if_cleanup;
3082 int i, n;
3083
3084 start = compiler_new_block(c);
3085 skip = compiler_new_block(c);
3086 if_cleanup = compiler_new_block(c);
3087 anchor = compiler_new_block(c);
3088
3089 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3090 anchor == NULL)
3091 return 0;
3092
3093 l = asdl_seq_GET(generators, gen_index);
3094 VISIT(c, expr, l->iter);
3095 ADDOP(c, GET_ITER);
3096 compiler_use_next_block(c, start);
3097 ADDOP_JREL(c, FOR_ITER, anchor);
3098 NEXT_BLOCK(c);
3099 VISIT(c, expr, l->target);
3100
3101 /* XXX this needs to be cleaned up...a lot! */
3102 n = asdl_seq_LEN(l->ifs);
3103 for (i = 0; i < n; i++) {
3104 expr_ty e = asdl_seq_GET(l->ifs, i);
3105 VISIT(c, expr, e);
3106 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3107 NEXT_BLOCK(c);
3108 ADDOP(c, POP_TOP);
3109 }
3110
3111 if (++gen_index < asdl_seq_LEN(generators))
3112 if (!compiler_listcomp_generator(c, tmpname,
3113 generators, gen_index, elt))
3114 return 0;
3115
3116 /* only append after the last for generator */
3117 if (gen_index >= asdl_seq_LEN(generators)) {
3118 if (!compiler_nameop(c, tmpname, Load))
3119 return 0;
3120 VISIT(c, expr, elt);
3121 ADDOP_I(c, CALL_FUNCTION, 1);
3122 ADDOP(c, POP_TOP);
3123
3124 compiler_use_next_block(c, skip);
3125 }
3126 for (i = 0; i < n; i++) {
3127 ADDOP_I(c, JUMP_FORWARD, 1);
3128 if (i == 0)
3129 compiler_use_next_block(c, if_cleanup);
3130 ADDOP(c, POP_TOP);
3131 }
3132 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3133 compiler_use_next_block(c, anchor);
3134 /* delete the append method added to locals */
3135 if (gen_index == 1)
3136 if (!compiler_nameop(c, tmpname, Del))
3137 return 0;
3138
3139 return 1;
3140}
3141
3142static int
3143compiler_listcomp(struct compiler *c, expr_ty e)
3144{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 identifier tmp;
3146 int rc = 0;
3147 static identifier append;
3148 asdl_seq *generators = e->v.ListComp.generators;
3149
3150 assert(e->kind == ListComp_kind);
3151 if (!append) {
3152 append = PyString_InternFromString("append");
3153 if (!append)
3154 return 0;
3155 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003156 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157 if (!tmp)
3158 return 0;
3159 ADDOP_I(c, BUILD_LIST, 0);
3160 ADDOP(c, DUP_TOP);
3161 ADDOP_O(c, LOAD_ATTR, append, names);
3162 if (compiler_nameop(c, tmp, Store))
3163 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3164 e->v.ListComp.elt);
3165 Py_DECREF(tmp);
3166 return rc;
3167}
3168
3169static int
3170compiler_genexp_generator(struct compiler *c,
3171 asdl_seq *generators, int gen_index,
3172 expr_ty elt)
3173{
3174 /* generate code for the iterator, then each of the ifs,
3175 and then write to the element */
3176
3177 comprehension_ty ge;
3178 basicblock *start, *anchor, *skip, *if_cleanup, *end;
3179 int i, n;
3180
3181 start = compiler_new_block(c);
3182 skip = compiler_new_block(c);
3183 if_cleanup = compiler_new_block(c);
3184 anchor = compiler_new_block(c);
3185 end = compiler_new_block(c);
3186
3187 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3188 anchor == NULL || end == NULL)
3189 return 0;
3190
3191 ge = asdl_seq_GET(generators, gen_index);
3192 ADDOP_JREL(c, SETUP_LOOP, end);
3193 if (!compiler_push_fblock(c, LOOP, start))
3194 return 0;
3195
3196 if (gen_index == 0) {
3197 /* Receive outermost iter as an implicit argument */
3198 c->u->u_argcount = 1;
3199 ADDOP_I(c, LOAD_FAST, 0);
3200 }
3201 else {
3202 /* Sub-iter - calculate on the fly */
3203 VISIT(c, expr, ge->iter);
3204 ADDOP(c, GET_ITER);
3205 }
3206 compiler_use_next_block(c, start);
3207 ADDOP_JREL(c, FOR_ITER, anchor);
3208 NEXT_BLOCK(c);
3209 VISIT(c, expr, ge->target);
3210
3211 /* XXX this needs to be cleaned up...a lot! */
3212 n = asdl_seq_LEN(ge->ifs);
3213 for (i = 0; i < n; i++) {
3214 expr_ty e = asdl_seq_GET(ge->ifs, i);
3215 VISIT(c, expr, e);
3216 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3217 NEXT_BLOCK(c);
3218 ADDOP(c, POP_TOP);
3219 }
3220
3221 if (++gen_index < asdl_seq_LEN(generators))
3222 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3223 return 0;
3224
3225 /* only append after the last 'for' generator */
3226 if (gen_index >= asdl_seq_LEN(generators)) {
3227 VISIT(c, expr, elt);
3228 ADDOP(c, YIELD_VALUE);
3229 ADDOP(c, POP_TOP);
3230
3231 compiler_use_next_block(c, skip);
3232 }
3233 for (i = 0; i < n; i++) {
3234 ADDOP_I(c, JUMP_FORWARD, 1);
3235 if (i == 0)
3236 compiler_use_next_block(c, if_cleanup);
3237
3238 ADDOP(c, POP_TOP);
3239 }
3240 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3241 compiler_use_next_block(c, anchor);
3242 ADDOP(c, POP_BLOCK);
3243 compiler_pop_fblock(c, LOOP, start);
3244 compiler_use_next_block(c, end);
3245
3246 return 1;
3247}
3248
3249static int
3250compiler_genexp(struct compiler *c, expr_ty e)
3251{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003252 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253 PyCodeObject *co;
3254 expr_ty outermost_iter = ((comprehension_ty)
3255 (asdl_seq_GET(e->v.GeneratorExp.generators,
3256 0)))->iter;
3257
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003258 if (!name) {
3259 name = PyString_FromString("<genexpr>");
3260 if (!name)
3261 return 0;
3262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263
3264 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3265 return 0;
3266 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3267 e->v.GeneratorExp.elt);
3268 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003269 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270 if (co == NULL)
3271 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272
3273 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003274 Py_DECREF(co);
3275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276 VISIT(c, expr, outermost_iter);
3277 ADDOP(c, GET_ITER);
3278 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279
3280 return 1;
3281}
3282
3283static int
3284compiler_visit_keyword(struct compiler *c, keyword_ty k)
3285{
3286 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3287 VISIT(c, expr, k->value);
3288 return 1;
3289}
3290
3291/* Test whether expression is constant. For constants, report
3292 whether they are true or false.
3293
3294 Return values: 1 for true, 0 for false, -1 for non-constant.
3295 */
3296
3297static int
3298expr_constant(expr_ty e)
3299{
3300 switch (e->kind) {
3301 case Num_kind:
3302 return PyObject_IsTrue(e->v.Num.n);
3303 case Str_kind:
3304 return PyObject_IsTrue(e->v.Str.s);
3305 default:
3306 return -1;
3307 }
3308}
3309
Guido van Rossumc2e20742006-02-27 22:32:47 +00003310/*
3311 Implements the with statement from PEP 343.
3312
3313 The semantics outlined in that PEP are as follows:
3314
3315 with EXPR as VAR:
3316 BLOCK
3317
3318 It is implemented roughly as:
3319
3320 context = (EXPR).__context__()
3321 exit = context.__exit__ # not calling it
3322 value = context.__enter__()
3323 try:
3324 VAR = value # if VAR present in the syntax
3325 BLOCK
3326 finally:
3327 if an exception was raised:
3328 exc = copy of (exception, instance, traceback)
3329 else:
3330 exc = (None, None, None)
3331 exit(*exc)
3332 */
3333static int
3334compiler_with(struct compiler *c, stmt_ty s)
3335{
3336 static identifier context_attr, enter_attr, exit_attr;
3337 basicblock *block, *finally;
3338 identifier tmpexit, tmpvalue = NULL;
3339
3340 assert(s->kind == With_kind);
3341
3342 if (!context_attr) {
3343 context_attr = PyString_InternFromString("__context__");
3344 if (!context_attr)
3345 return 0;
3346 }
3347 if (!enter_attr) {
3348 enter_attr = PyString_InternFromString("__enter__");
3349 if (!enter_attr)
3350 return 0;
3351 }
3352 if (!exit_attr) {
3353 exit_attr = PyString_InternFromString("__exit__");
3354 if (!exit_attr)
3355 return 0;
3356 }
3357
3358 block = compiler_new_block(c);
3359 finally = compiler_new_block(c);
3360 if (!block || !finally)
3361 return 0;
3362
3363 /* Create a temporary variable to hold context.__exit__ */
3364 tmpexit = compiler_new_tmpname(c);
3365 if (tmpexit == NULL)
3366 return 0;
3367 PyArena_AddPyObject(c->c_arena, tmpexit);
3368
3369 if (s->v.With.optional_vars) {
3370 /* Create a temporary variable to hold context.__enter__().
3371 We need to do this rather than preserving it on the stack
3372 because SETUP_FINALLY remembers the stack level.
3373 We need to do the assignment *inside* the try/finally
3374 so that context.__exit__() is called when the assignment
3375 fails. But we need to call context.__enter__() *before*
3376 the try/finally so that if it fails we won't call
3377 context.__exit__().
3378 */
3379 tmpvalue = compiler_new_tmpname(c);
3380 if (tmpvalue == NULL)
3381 return 0;
3382 PyArena_AddPyObject(c->c_arena, tmpvalue);
3383 }
3384
3385 /* Evaluate (EXPR).__context__() */
3386 VISIT(c, expr, s->v.With.context_expr);
3387 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3388 ADDOP_I(c, CALL_FUNCTION, 0);
3389
3390 /* Squirrel away context.__exit__ */
3391 ADDOP(c, DUP_TOP);
3392 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3393 if (!compiler_nameop(c, tmpexit, Store))
3394 return 0;
3395
3396 /* Call context.__enter__() */
3397 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3398 ADDOP_I(c, CALL_FUNCTION, 0);
3399
3400 if (s->v.With.optional_vars) {
3401 /* Store it in tmpvalue */
3402 if (!compiler_nameop(c, tmpvalue, Store))
3403 return 0;
3404 }
3405 else {
3406 /* Discard result from context.__enter__() */
3407 ADDOP(c, POP_TOP);
3408 }
3409
3410 /* Start the try block */
3411 ADDOP_JREL(c, SETUP_FINALLY, finally);
3412
3413 compiler_use_next_block(c, block);
3414 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
3415 return 0;
3416 }
3417
3418 if (s->v.With.optional_vars) {
3419 /* Bind saved result of context.__enter__() to VAR */
3420 if (!compiler_nameop(c, tmpvalue, Load) ||
3421 !compiler_nameop(c, tmpvalue, Del))
3422 return 0;
3423 VISIT(c, expr, s->v.With.optional_vars);
3424 }
3425
3426 /* BLOCK code */
3427 VISIT_SEQ(c, stmt, s->v.With.body);
3428
3429 /* End of try block; start the finally block */
3430 ADDOP(c, POP_BLOCK);
3431 compiler_pop_fblock(c, FINALLY_TRY, block);
3432
3433 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3434 compiler_use_next_block(c, finally);
3435 if (!compiler_push_fblock(c, FINALLY_END, finally))
3436 return 0;
3437
3438 /* Finally block starts; push tmpexit and issue our magic opcode. */
3439 if (!compiler_nameop(c, tmpexit, Load) ||
3440 !compiler_nameop(c, tmpexit, Del))
3441 return 0;
3442 ADDOP(c, WITH_CLEANUP);
3443 ADDOP_I(c, CALL_FUNCTION, 3);
3444 ADDOP(c, POP_TOP);
3445
3446 /* Finally block ends. */
3447 ADDOP(c, END_FINALLY);
3448 compiler_pop_fblock(c, FINALLY_END, finally);
3449 return 1;
3450}
3451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452static int
3453compiler_visit_expr(struct compiler *c, expr_ty e)
3454{
3455 int i, n;
3456
3457 if (e->lineno > c->u->u_lineno) {
3458 c->u->u_lineno = e->lineno;
3459 c->u->u_lineno_set = false;
3460 }
3461 switch (e->kind) {
3462 case BoolOp_kind:
3463 return compiler_boolop(c, e);
3464 case BinOp_kind:
3465 VISIT(c, expr, e->v.BinOp.left);
3466 VISIT(c, expr, e->v.BinOp.right);
3467 ADDOP(c, binop(c, e->v.BinOp.op));
3468 break;
3469 case UnaryOp_kind:
3470 VISIT(c, expr, e->v.UnaryOp.operand);
3471 ADDOP(c, unaryop(e->v.UnaryOp.op));
3472 break;
3473 case Lambda_kind:
3474 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003475 case IfExp_kind:
3476 return compiler_ifexp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477 case Dict_kind:
3478 /* XXX get rid of arg? */
3479 ADDOP_I(c, BUILD_MAP, 0);
3480 n = asdl_seq_LEN(e->v.Dict.values);
3481 /* We must arrange things just right for STORE_SUBSCR.
3482 It wants the stack to look like (value) (dict) (key) */
3483 for (i = 0; i < n; i++) {
3484 ADDOP(c, DUP_TOP);
3485 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3486 ADDOP(c, ROT_TWO);
3487 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3488 ADDOP(c, STORE_SUBSCR);
3489 }
3490 break;
3491 case ListComp_kind:
3492 return compiler_listcomp(c, e);
3493 case GeneratorExp_kind:
3494 return compiler_genexp(c, e);
3495 case Yield_kind:
3496 if (c->u->u_ste->ste_type != FunctionBlock)
3497 return compiler_error(c, "'yield' outside function");
3498 /*
3499 for (i = 0; i < c->u->u_nfblocks; i++) {
3500 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3501 return compiler_error(
3502 c, "'yield' not allowed in a 'try' "
3503 "block with a 'finally' clause");
3504 }
3505 */
3506 if (e->v.Yield.value) {
3507 VISIT(c, expr, e->v.Yield.value);
3508 }
3509 else {
3510 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3511 }
3512 ADDOP(c, YIELD_VALUE);
3513 break;
3514 case Compare_kind:
3515 return compiler_compare(c, e);
3516 case Call_kind:
3517 return compiler_call(c, e);
3518 case Repr_kind:
3519 VISIT(c, expr, e->v.Repr.value);
3520 ADDOP(c, UNARY_CONVERT);
3521 break;
3522 case Num_kind:
3523 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3524 break;
3525 case Str_kind:
3526 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3527 break;
3528 /* The following exprs can be assignment targets. */
3529 case Attribute_kind:
3530 if (e->v.Attribute.ctx != AugStore)
3531 VISIT(c, expr, e->v.Attribute.value);
3532 switch (e->v.Attribute.ctx) {
3533 case AugLoad:
3534 ADDOP(c, DUP_TOP);
3535 /* Fall through to load */
3536 case Load:
3537 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3538 break;
3539 case AugStore:
3540 ADDOP(c, ROT_TWO);
3541 /* Fall through to save */
3542 case Store:
3543 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3544 break;
3545 case Del:
3546 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3547 break;
3548 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003549 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003550 PyErr_SetString(PyExc_SystemError,
3551 "param invalid in attribute expression");
3552 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 }
3554 break;
3555 case Subscript_kind:
3556 switch (e->v.Subscript.ctx) {
3557 case AugLoad:
3558 VISIT(c, expr, e->v.Subscript.value);
3559 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3560 break;
3561 case Load:
3562 VISIT(c, expr, e->v.Subscript.value);
3563 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3564 break;
3565 case AugStore:
3566 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3567 break;
3568 case Store:
3569 VISIT(c, expr, e->v.Subscript.value);
3570 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3571 break;
3572 case Del:
3573 VISIT(c, expr, e->v.Subscript.value);
3574 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3575 break;
3576 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003577 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003578 PyErr_SetString(PyExc_SystemError,
3579 "param invalid in subscript expression");
3580 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581 }
3582 break;
3583 case Name_kind:
3584 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3585 /* child nodes of List and Tuple will have expr_context set */
3586 case List_kind:
3587 return compiler_list(c, e);
3588 case Tuple_kind:
3589 return compiler_tuple(c, e);
3590 }
3591 return 1;
3592}
3593
3594static int
3595compiler_augassign(struct compiler *c, stmt_ty s)
3596{
3597 expr_ty e = s->v.AugAssign.target;
3598 expr_ty auge;
3599
3600 assert(s->kind == AugAssign_kind);
3601
3602 switch (e->kind) {
3603 case Attribute_kind:
3604 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003605 AugLoad, e->lineno, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 if (auge == NULL)
3607 return 0;
3608 VISIT(c, expr, auge);
3609 VISIT(c, expr, s->v.AugAssign.value);
3610 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3611 auge->v.Attribute.ctx = AugStore;
3612 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 break;
3614 case Subscript_kind:
3615 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003616 AugLoad, e->lineno, c->c_arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 if (auge == NULL)
3618 return 0;
3619 VISIT(c, expr, auge);
3620 VISIT(c, expr, s->v.AugAssign.value);
3621 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3622 auge->v.Subscript.ctx = AugStore;
3623 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 break;
3625 case Name_kind:
3626 VISIT(c, expr, s->v.AugAssign.target);
3627 VISIT(c, expr, s->v.AugAssign.value);
3628 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3629 return compiler_nameop(c, e->v.Name.id, Store);
3630 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003631 PyErr_Format(PyExc_SystemError,
3632 "invalid node type (%d) for augmented assignment",
3633 e->kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 return 0;
3635 }
3636 return 1;
3637}
3638
3639static int
3640compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3641{
3642 struct fblockinfo *f;
3643 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3644 return 0;
3645 f = &c->u->u_fblock[c->u->u_nfblocks++];
3646 f->fb_type = t;
3647 f->fb_block = b;
3648 return 1;
3649}
3650
3651static void
3652compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3653{
3654 struct compiler_unit *u = c->u;
3655 assert(u->u_nfblocks > 0);
3656 u->u_nfblocks--;
3657 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3658 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3659}
3660
3661/* Raises a SyntaxError and returns 0.
3662 If something goes wrong, a different exception may be raised.
3663*/
3664
3665static int
3666compiler_error(struct compiler *c, const char *errstr)
3667{
3668 PyObject *loc;
3669 PyObject *u = NULL, *v = NULL;
3670
3671 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3672 if (!loc) {
3673 Py_INCREF(Py_None);
3674 loc = Py_None;
3675 }
3676 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3677 Py_None, loc);
3678 if (!u)
3679 goto exit;
3680 v = Py_BuildValue("(zO)", errstr, u);
3681 if (!v)
3682 goto exit;
3683 PyErr_SetObject(PyExc_SyntaxError, v);
3684 exit:
3685 Py_DECREF(loc);
3686 Py_XDECREF(u);
3687 Py_XDECREF(v);
3688 return 0;
3689}
3690
3691static int
3692compiler_handle_subscr(struct compiler *c, const char *kind,
3693 expr_context_ty ctx)
3694{
3695 int op = 0;
3696
3697 /* XXX this code is duplicated */
3698 switch (ctx) {
3699 case AugLoad: /* fall through to Load */
3700 case Load: op = BINARY_SUBSCR; break;
3701 case AugStore:/* fall through to Store */
3702 case Store: op = STORE_SUBSCR; break;
3703 case Del: op = DELETE_SUBSCR; break;
3704 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003705 PyErr_Format(PyExc_SystemError,
3706 "invalid %s kind %d in subscript\n",
3707 kind, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708 return 0;
3709 }
3710 if (ctx == AugLoad) {
3711 ADDOP_I(c, DUP_TOPX, 2);
3712 }
3713 else if (ctx == AugStore) {
3714 ADDOP(c, ROT_THREE);
3715 }
3716 ADDOP(c, op);
3717 return 1;
3718}
3719
3720static int
3721compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3722{
3723 int n = 2;
3724 assert(s->kind == Slice_kind);
3725
3726 /* only handles the cases where BUILD_SLICE is emitted */
3727 if (s->v.Slice.lower) {
3728 VISIT(c, expr, s->v.Slice.lower);
3729 }
3730 else {
3731 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3732 }
3733
3734 if (s->v.Slice.upper) {
3735 VISIT(c, expr, s->v.Slice.upper);
3736 }
3737 else {
3738 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3739 }
3740
3741 if (s->v.Slice.step) {
3742 n++;
3743 VISIT(c, expr, s->v.Slice.step);
3744 }
3745 ADDOP_I(c, BUILD_SLICE, n);
3746 return 1;
3747}
3748
3749static int
3750compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3751{
3752 int op = 0, slice_offset = 0, stack_count = 0;
3753
3754 assert(s->v.Slice.step == NULL);
3755 if (s->v.Slice.lower) {
3756 slice_offset++;
3757 stack_count++;
3758 if (ctx != AugStore)
3759 VISIT(c, expr, s->v.Slice.lower);
3760 }
3761 if (s->v.Slice.upper) {
3762 slice_offset += 2;
3763 stack_count++;
3764 if (ctx != AugStore)
3765 VISIT(c, expr, s->v.Slice.upper);
3766 }
3767
3768 if (ctx == AugLoad) {
3769 switch (stack_count) {
3770 case 0: ADDOP(c, DUP_TOP); break;
3771 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3772 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3773 }
3774 }
3775 else if (ctx == AugStore) {
3776 switch (stack_count) {
3777 case 0: ADDOP(c, ROT_TWO); break;
3778 case 1: ADDOP(c, ROT_THREE); break;
3779 case 2: ADDOP(c, ROT_FOUR); break;
3780 }
3781 }
3782
3783 switch (ctx) {
3784 case AugLoad: /* fall through to Load */
3785 case Load: op = SLICE; break;
3786 case AugStore:/* fall through to Store */
3787 case Store: op = STORE_SLICE; break;
3788 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003789 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003790 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003791 PyErr_SetString(PyExc_SystemError,
3792 "param invalid in simple slice");
3793 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794 }
3795
3796 ADDOP(c, op + slice_offset);
3797 return 1;
3798}
3799
3800static int
3801compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3802 expr_context_ty ctx)
3803{
3804 switch (s->kind) {
3805 case Ellipsis_kind:
3806 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3807 break;
3808 case Slice_kind:
3809 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 case Index_kind:
3811 VISIT(c, expr, s->v.Index.value);
3812 break;
3813 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003814 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003815 PyErr_SetString(PyExc_SystemError,
3816 "extended slice invalid in nested slice");
3817 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 }
3819 return 1;
3820}
3821
3822
3823static int
3824compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3825{
3826 switch (s->kind) {
3827 case Ellipsis_kind:
3828 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3829 break;
3830 case Slice_kind:
3831 if (!s->v.Slice.step)
3832 return compiler_simple_slice(c, s, ctx);
3833 if (!compiler_slice(c, s, ctx))
3834 return 0;
3835 if (ctx == AugLoad) {
3836 ADDOP_I(c, DUP_TOPX, 2);
3837 }
3838 else if (ctx == AugStore) {
3839 ADDOP(c, ROT_THREE);
3840 }
3841 return compiler_handle_subscr(c, "slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842 case ExtSlice_kind: {
3843 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3844 for (i = 0; i < n; i++) {
3845 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3846 if (!compiler_visit_nested_slice(c, sub, ctx))
3847 return 0;
3848 }
3849 ADDOP_I(c, BUILD_TUPLE, n);
3850 return compiler_handle_subscr(c, "extended slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851 }
3852 case Index_kind:
3853 if (ctx != AugStore)
3854 VISIT(c, expr, s->v.Index.value);
3855 return compiler_handle_subscr(c, "index", ctx);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003856 default:
3857 PyErr_Format(PyExc_SystemError,
3858 "invalid slice %d", s->kind);
3859 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003860 }
3861 return 1;
3862}
3863
3864/* do depth-first search of basic block graph, starting with block.
3865 post records the block indices in post-order.
3866
3867 XXX must handle implicit jumps from one block to next
3868*/
3869
3870static void
3871dfs(struct compiler *c, basicblock *b, struct assembler *a)
3872{
3873 int i;
3874 struct instr *instr = NULL;
3875
3876 if (b->b_seen)
3877 return;
3878 b->b_seen = 1;
3879 if (b->b_next != NULL)
3880 dfs(c, b->b_next, a);
3881 for (i = 0; i < b->b_iused; i++) {
3882 instr = &b->b_instr[i];
3883 if (instr->i_jrel || instr->i_jabs)
3884 dfs(c, instr->i_target, a);
3885 }
3886 a->a_postorder[a->a_nblocks++] = b;
3887}
3888
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003889static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3891{
3892 int i;
3893 struct instr *instr;
3894 if (b->b_seen || b->b_startdepth >= depth)
3895 return maxdepth;
3896 b->b_seen = 1;
3897 b->b_startdepth = depth;
3898 for (i = 0; i < b->b_iused; i++) {
3899 instr = &b->b_instr[i];
3900 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3901 if (depth > maxdepth)
3902 maxdepth = depth;
3903 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3904 if (instr->i_jrel || instr->i_jabs) {
3905 maxdepth = stackdepth_walk(c, instr->i_target,
3906 depth, maxdepth);
3907 if (instr->i_opcode == JUMP_ABSOLUTE ||
3908 instr->i_opcode == JUMP_FORWARD) {
3909 goto out; /* remaining code is dead */
3910 }
3911 }
3912 }
3913 if (b->b_next)
3914 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3915out:
3916 b->b_seen = 0;
3917 return maxdepth;
3918}
3919
3920/* Find the flow path that needs the largest stack. We assume that
3921 * cycles in the flow graph have no net effect on the stack depth.
3922 */
3923static int
3924stackdepth(struct compiler *c)
3925{
3926 basicblock *b, *entryblock;
3927 entryblock = NULL;
3928 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3929 b->b_seen = 0;
3930 b->b_startdepth = INT_MIN;
3931 entryblock = b;
3932 }
3933 return stackdepth_walk(c, entryblock, 0, 0);
3934}
3935
3936static int
3937assemble_init(struct assembler *a, int nblocks, int firstlineno)
3938{
3939 memset(a, 0, sizeof(struct assembler));
3940 a->a_lineno = firstlineno;
3941 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3942 if (!a->a_bytecode)
3943 return 0;
3944 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3945 if (!a->a_lnotab)
3946 return 0;
3947 a->a_postorder = (basicblock **)PyObject_Malloc(
3948 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003949 if (!a->a_postorder) {
3950 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003952 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003953 return 1;
3954}
3955
3956static void
3957assemble_free(struct assembler *a)
3958{
3959 Py_XDECREF(a->a_bytecode);
3960 Py_XDECREF(a->a_lnotab);
3961 if (a->a_postorder)
3962 PyObject_Free(a->a_postorder);
3963}
3964
3965/* Return the size of a basic block in bytes. */
3966
3967static int
3968instrsize(struct instr *instr)
3969{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003970 if (!instr->i_hasarg)
3971 return 1;
3972 if (instr->i_oparg > 0xffff)
3973 return 6;
3974 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003975}
3976
3977static int
3978blocksize(basicblock *b)
3979{
3980 int i;
3981 int size = 0;
3982
3983 for (i = 0; i < b->b_iused; i++)
3984 size += instrsize(&b->b_instr[i]);
3985 return size;
3986}
3987
3988/* All about a_lnotab.
3989
3990c_lnotab is an array of unsigned bytes disguised as a Python string.
3991It is used to map bytecode offsets to source code line #s (when needed
3992for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003993
Tim Peters2a7f3842001-06-09 09:26:21 +00003994The array is conceptually a list of
3995 (bytecode offset increment, line number increment)
3996pairs. The details are important and delicate, best illustrated by example:
3997
3998 byte code offset source code line number
3999 0 1
4000 6 2
4001 50 7
4002 350 307
4003 361 308
4004
4005The first trick is that these numbers aren't stored, only the increments
4006from one row to the next (this doesn't really work, but it's a start):
4007
4008 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4009
4010The second trick is that an unsigned byte can't hold negative values, or
4011values larger than 255, so (a) there's a deep assumption that byte code
4012offsets and their corresponding line #s both increase monotonically, and (b)
4013if at least one column jumps by more than 255 from one row to the next, more
4014than one pair is written to the table. In case #b, there's no way to know
4015from looking at the table later how many were written. That's the delicate
4016part. A user of c_lnotab desiring to find the source line number
4017corresponding to a bytecode address A should do something like this
4018
4019 lineno = addr = 0
4020 for addr_incr, line_incr in c_lnotab:
4021 addr += addr_incr
4022 if addr > A:
4023 return lineno
4024 lineno += line_incr
4025
4026In order for this to work, when the addr field increments by more than 255,
4027the line # increment in each pair generated must be 0 until the remaining addr
4028increment is < 256. So, in the example above, com_set_lineno should not (as
4029was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
4030255, 0, 45, 255, 0, 45.
4031*/
4032
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004033static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004034assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004035{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004036 int d_bytecode, d_lineno;
4037 int len;
4038 char *lnotab;
4039
4040 d_bytecode = a->a_offset - a->a_lineno_off;
4041 d_lineno = i->i_lineno - a->a_lineno;
4042
4043 assert(d_bytecode >= 0);
4044 assert(d_lineno >= 0);
4045
4046 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004047 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004048
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004049 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004050 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004051 nbytes = a->a_lnotab_off + 2 * ncodes;
4052 len = PyString_GET_SIZE(a->a_lnotab);
4053 if (nbytes >= len) {
4054 if (len * 2 < nbytes)
4055 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004056 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057 len *= 2;
4058 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4059 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004060 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004062 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063 *lnotab++ = 255;
4064 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004065 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066 d_bytecode -= ncodes * 255;
4067 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004068 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004069 assert(d_bytecode <= 255);
4070 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004071 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004072 nbytes = a->a_lnotab_off + 2 * ncodes;
4073 len = PyString_GET_SIZE(a->a_lnotab);
4074 if (nbytes >= len) {
4075 if (len * 2 < nbytes)
4076 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004077 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004078 len *= 2;
4079 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4080 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004081 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4083 *lnotab++ = 255;
4084 *lnotab++ = d_bytecode;
4085 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004086 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004087 *lnotab++ = 255;
4088 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004089 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090 d_lineno -= ncodes * 255;
4091 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004092 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004093
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004094 len = PyString_GET_SIZE(a->a_lnotab);
4095 if (a->a_lnotab_off + 2 >= len) {
4096 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004097 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004098 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004099 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004100
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004101 a->a_lnotab_off += 2;
4102 if (d_bytecode) {
4103 *lnotab++ = d_bytecode;
4104 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004105 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004106 else { /* First line of a block; def stmt, etc. */
4107 *lnotab++ = 0;
4108 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004109 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110 a->a_lineno = i->i_lineno;
4111 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004112 return 1;
4113}
4114
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115/* assemble_emit()
4116 Extend the bytecode with a new instruction.
4117 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004118*/
4119
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004120static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004122{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004123 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 int len = PyString_GET_SIZE(a->a_bytecode);
4125 char *code;
4126
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004127 size = instrsize(i);
4128 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004129 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004130 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004131 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004132 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004133 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134 if (a->a_offset + size >= len) {
4135 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004136 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004137 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4139 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004140 if (size == 6) {
4141 assert(i->i_hasarg);
4142 *code++ = (char)EXTENDED_ARG;
4143 *code++ = ext & 0xff;
4144 *code++ = ext >> 8;
4145 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004146 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004148 if (i->i_hasarg) {
4149 assert(size == 3 || size == 6);
4150 *code++ = arg & 0xff;
4151 *code++ = arg >> 8;
4152 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004154}
4155
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004156static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004158{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004160 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004161 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004162
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004163 /* Compute the size of each block and fixup jump args.
4164 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004165start:
4166 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004168 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169 bsize = blocksize(b);
4170 b->b_offset = totsize;
4171 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004172 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004173 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004174 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4175 bsize = b->b_offset;
4176 for (i = 0; i < b->b_iused; i++) {
4177 struct instr *instr = &b->b_instr[i];
4178 /* Relative jumps are computed relative to
4179 the instruction pointer after fetching
4180 the jump instruction.
4181 */
4182 bsize += instrsize(instr);
4183 if (instr->i_jabs)
4184 instr->i_oparg = instr->i_target->b_offset;
4185 else if (instr->i_jrel) {
4186 int delta = instr->i_target->b_offset - bsize;
4187 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004188 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004189 else
4190 continue;
4191 if (instr->i_oparg > 0xffff)
4192 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004193 }
4194 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004195
4196 /* XXX: This is an awful hack that could hurt performance, but
4197 on the bright side it should work until we come up
4198 with a better solution.
4199
4200 In the meantime, should the goto be dropped in favor
4201 of a loop?
4202
4203 The issue is that in the first loop blocksize() is called
4204 which calls instrsize() which requires i_oparg be set
4205 appropriately. There is a bootstrap problem because
4206 i_oparg is calculated in the second loop above.
4207
4208 So we loop until we stop seeing new EXTENDED_ARGs.
4209 The only EXTENDED_ARGs that could be popping up are
4210 ones in jump instructions. So this should converge
4211 fairly quickly.
4212 */
4213 if (last_extended_arg_count != extended_arg_count) {
4214 last_extended_arg_count = extended_arg_count;
4215 goto start;
4216 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004217}
4218
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004219static PyObject *
4220dict_keys_inorder(PyObject *dict, int offset)
4221{
4222 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004223 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004224
4225 tuple = PyTuple_New(size);
4226 if (tuple == NULL)
4227 return NULL;
4228 while (PyDict_Next(dict, &pos, &k, &v)) {
4229 i = PyInt_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004230 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004231 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004232 assert((i - offset) < size);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004234 PyTuple_SET_ITEM(tuple, i - offset, k);
4235 }
4236 return tuple;
4237}
4238
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004239static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004241{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004242 PySTEntryObject *ste = c->u->u_ste;
4243 int flags = 0, n;
4244 if (ste->ste_type != ModuleBlock)
4245 flags |= CO_NEWLOCALS;
4246 if (ste->ste_type == FunctionBlock) {
4247 if (!ste->ste_unoptimized)
4248 flags |= CO_OPTIMIZED;
4249 if (ste->ste_nested)
4250 flags |= CO_NESTED;
4251 if (ste->ste_generator)
4252 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004253 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004254 if (ste->ste_varargs)
4255 flags |= CO_VARARGS;
4256 if (ste->ste_varkeywords)
4257 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004258 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004259 flags |= CO_GENERATOR;
4260 if (c->c_flags->cf_flags & CO_FUTURE_DIVISION)
4261 flags |= CO_FUTURE_DIVISION;
4262 n = PyDict_Size(c->u->u_freevars);
4263 if (n < 0)
4264 return -1;
4265 if (n == 0) {
4266 n = PyDict_Size(c->u->u_cellvars);
4267 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004268 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004269 if (n == 0) {
4270 flags |= CO_NOFREE;
4271 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004272 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004273
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004274 return flags;
4275}
4276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004277static PyCodeObject *
4278makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004279{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280 PyObject *tmp;
4281 PyCodeObject *co = NULL;
4282 PyObject *consts = NULL;
4283 PyObject *names = NULL;
4284 PyObject *varnames = NULL;
4285 PyObject *filename = NULL;
4286 PyObject *name = NULL;
4287 PyObject *freevars = NULL;
4288 PyObject *cellvars = NULL;
4289 PyObject *bytecode = NULL;
4290 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292 tmp = dict_keys_inorder(c->u->u_consts, 0);
4293 if (!tmp)
4294 goto error;
4295 consts = PySequence_List(tmp); /* optimize_code requires a list */
4296 Py_DECREF(tmp);
4297
4298 names = dict_keys_inorder(c->u->u_names, 0);
4299 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4300 if (!consts || !names || !varnames)
4301 goto error;
4302
4303 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4304 if (!cellvars)
4305 goto error;
4306 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4307 if (!freevars)
4308 goto error;
4309 filename = PyString_FromString(c->c_filename);
4310 if (!filename)
4311 goto error;
4312
4313 nlocals = PyDict_Size(c->u->u_varnames);
4314 flags = compute_code_flags(c);
4315 if (flags < 0)
4316 goto error;
4317
4318 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4319 if (!bytecode)
4320 goto error;
4321
4322 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4323 if (!tmp)
4324 goto error;
4325 Py_DECREF(consts);
4326 consts = tmp;
4327
4328 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4329 bytecode, consts, names, varnames,
4330 freevars, cellvars,
4331 filename, c->u->u_name,
4332 c->u->u_firstlineno,
4333 a->a_lnotab);
4334 error:
4335 Py_XDECREF(consts);
4336 Py_XDECREF(names);
4337 Py_XDECREF(varnames);
4338 Py_XDECREF(filename);
4339 Py_XDECREF(name);
4340 Py_XDECREF(freevars);
4341 Py_XDECREF(cellvars);
4342 Py_XDECREF(bytecode);
4343 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004344}
4345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346static PyCodeObject *
4347assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004348{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349 basicblock *b, *entryblock;
4350 struct assembler a;
4351 int i, j, nblocks;
4352 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004353
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004354 /* Make sure every block that falls off the end returns None.
4355 XXX NEXT_BLOCK() isn't quite right, because if the last
4356 block ends with a jump or return b_next shouldn't set.
4357 */
4358 if (!c->u->u_curblock->b_return) {
4359 NEXT_BLOCK(c);
4360 if (addNone)
4361 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4362 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004363 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004364
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365 nblocks = 0;
4366 entryblock = NULL;
4367 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4368 nblocks++;
4369 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004370 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004371
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004372 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4373 goto error;
4374 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004375
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004376 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004377 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004378
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004379 /* Emit code in reverse postorder from dfs. */
4380 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004381 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382 for (j = 0; j < b->b_iused; j++)
4383 if (!assemble_emit(&a, &b->b_instr[j]))
4384 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004385 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004386
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004387 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4388 goto error;
4389 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4390 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004391
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004392 co = makecode(c, &a);
4393 error:
4394 assemble_free(&a);
4395 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004396}