blob: 945a281235869b9d41129402de85d5e764c03b21 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
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 *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200_Py_Mangle(PyObject *privateobj, 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. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 const char *p, *name = PyString_AsString(ident);
205 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 if (privateobj == NULL || !PyString_Check(privateobj) ||
208 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000209 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 nlen = strlen(name);
214 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 /* Strip leading underscores from class name */
219 while (*p == '_')
220 p++;
221 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000222 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
227 if (!ident)
228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 buffer = PyString_AS_STRING(ident);
231 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232 strncpy(buffer+1, p, plen);
233 strcpy(buffer+1+plen, name);
234 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000235}
236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237static int
238compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000239{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 c->c_stack = PyList_New(0);
243 if (!c->c_stack)
244 return 0;
245
246 return 1;
247}
248
249PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000250PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252{
253 struct compiler c;
254 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyCompilerFlags local_flags;
256 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000257
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000258 if (!__doc__) {
259 __doc__ = PyString_InternFromString("__doc__");
260 if (!__doc__)
261 return NULL;
262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
264 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000265 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000267 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_future = PyFuture_FromAST(mod, filename);
269 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000270 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000272 local_flags.cf_flags = 0;
273 flags = &local_flags;
274 }
275 merged = c.c_future->ff_features | flags->cf_flags;
276 c.c_future->ff_features = merged;
277 flags->cf_flags = merged;
278 c.c_flags = flags;
279 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280
281 c.c_st = PySymtable_Build(mod, filename, c.c_future);
282 if (c.c_st == NULL) {
283 if (!PyErr_Occurred())
284 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000285 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286 }
287
288 /* XXX initialize to NULL for now, need to handle */
289 c.c_encoding = NULL;
290
291 co = compiler_mod(&c, mod);
292
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000295 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 return co;
297}
298
299PyCodeObject *
300PyNode_Compile(struct _node *n, const char *filename)
301{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000302 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000305 if (!arena)
306 return NULL;
307 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000308 if (mod)
309 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000310 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000311 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000312}
313
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000314static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317 if (c->c_st)
318 PySymtable_Free(c->c_st);
319 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322}
323
Guido van Rossum79f25d91997-04-29 20:08:16 +0000324static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000326{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000327 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328 PyObject *v, *k;
329 PyObject *dict = PyDict_New();
330 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 n = PyList_Size(list);
333 for (i = 0; i < n; i++) {
334 v = PyInt_FromLong(i);
335 if (!v) {
336 Py_DECREF(dict);
337 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000338 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000339 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
342 Py_XDECREF(k);
343 Py_DECREF(v);
344 Py_DECREF(dict);
345 return NULL;
346 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000347 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000349 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350 return dict;
351}
352
353/* Return new dict containing names from src that match scope(s).
354
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000355src is a symbol table dictionary. If the scope of a name matches
356either scope_type or flag is set, insert it into the new dict. The
357values are integers, starting at offset and increasing by one for
358each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359*/
360
361static PyObject *
362dictbytype(PyObject *src, int scope_type, int flag, int offset)
363{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000364 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365 PyObject *k, *v, *dest = PyDict_New();
366
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000367 assert(offset >= 0);
368 if (dest == NULL)
369 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370
371 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000372 /* XXX this should probably be a macro in symtable.h */
373 assert(PyInt_Check(v));
374 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
377 PyObject *tuple, *item = PyInt_FromLong(i);
378 if (item == NULL) {
379 Py_DECREF(dest);
380 return NULL;
381 }
382 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
385 Py_DECREF(item);
386 Py_DECREF(dest);
387 Py_XDECREF(tuple);
388 return NULL;
389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000391 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393 }
394 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000395}
396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000397/*
398
399Leave this debugging code for just a little longer.
400
401static void
402compiler_display_symbols(PyObject *name, PyObject *symbols)
403{
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000404PyObject *key, *value;
405int flags;
406Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
409while (PyDict_Next(symbols, &pos, &key, &value)) {
410flags = PyInt_AsLong(value);
411fprintf(stderr, "var %s:", PyString_AS_STRING(key));
412if (flags & DEF_GLOBAL)
413fprintf(stderr, " declared_global");
414if (flags & DEF_LOCAL)
415fprintf(stderr, " local");
416if (flags & DEF_PARAM)
417fprintf(stderr, " param");
418if (flags & DEF_STAR)
419fprintf(stderr, " stararg");
420if (flags & DEF_DOUBLESTAR)
421fprintf(stderr, " starstar");
422if (flags & DEF_INTUPLE)
423fprintf(stderr, " tuple");
424if (flags & DEF_FREE)
425fprintf(stderr, " free");
426if (flags & DEF_FREE_GLOBAL)
427fprintf(stderr, " global");
428if (flags & DEF_FREE_CLASS)
429fprintf(stderr, " free/class");
430if (flags & DEF_IMPORT)
431fprintf(stderr, " import");
432fprintf(stderr, "\n");
433}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000434 fprintf(stderr, "\n");
435}
436*/
437
438static void
439compiler_unit_check(struct compiler_unit *u)
440{
441 basicblock *block;
442 for (block = u->u_blocks; block != NULL; block = block->b_list) {
443 assert(block != (void *)0xcbcbcbcb);
444 assert(block != (void *)0xfbfbfbfb);
445 assert(block != (void *)0xdbdbdbdb);
446 if (block->b_instr != NULL) {
447 assert(block->b_ialloc > 0);
448 assert(block->b_iused > 0);
449 assert(block->b_ialloc >= block->b_iused);
450 }
451 else {
452 assert (block->b_iused == 0);
453 assert (block->b_ialloc == 0);
454 }
455 }
456}
457
458static void
459compiler_unit_free(struct compiler_unit *u)
460{
461 basicblock *b, *next;
462
463 compiler_unit_check(u);
464 b = u->u_blocks;
465 while (b != NULL) {
466 if (b->b_instr)
467 PyObject_Free((void *)b->b_instr);
468 next = b->b_list;
469 PyObject_Free((void *)b);
470 b = next;
471 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000472 Py_CLEAR(u->u_ste);
473 Py_CLEAR(u->u_name);
474 Py_CLEAR(u->u_consts);
475 Py_CLEAR(u->u_names);
476 Py_CLEAR(u->u_varnames);
477 Py_CLEAR(u->u_freevars);
478 Py_CLEAR(u->u_cellvars);
479 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480 PyObject_Free(u);
481}
482
483static int
484compiler_enter_scope(struct compiler *c, identifier name, void *key,
485 int lineno)
486{
487 struct compiler_unit *u;
488
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
490 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000491 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000492 PyErr_NoMemory();
493 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000494 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000495 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496 u->u_argcount = 0;
497 u->u_ste = PySymtable_Lookup(c->c_st, key);
498 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000499 compiler_unit_free(u);
500 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501 }
502 Py_INCREF(name);
503 u->u_name = name;
504 u->u_varnames = list2dict(u->u_ste->ste_varnames);
505 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 if (!u->u_varnames || !u->u_cellvars) {
507 compiler_unit_free(u);
508 return 0;
509 }
510
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000513 if (!u->u_freevars) {
514 compiler_unit_free(u);
515 return 0;
516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
518 u->u_blocks = NULL;
519 u->u_tmpname = 0;
520 u->u_nfblocks = 0;
521 u->u_firstlineno = lineno;
522 u->u_lineno = 0;
523 u->u_lineno_set = false;
524 u->u_consts = PyDict_New();
525 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000526 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 return 0;
528 }
529 u->u_names = PyDict_New();
530 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000531 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532 return 0;
533 }
534
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000535 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536
537 /* Push the old compiler_unit on the stack. */
538 if (c->u) {
539 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000540 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
541 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000542 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543 return 0;
544 }
545 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000546 u->u_private = c->u->u_private;
547 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548 }
549 c->u = u;
550
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000551 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000552 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553 return 0;
554
555 return 1;
556}
557
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000558static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559compiler_exit_scope(struct compiler *c)
560{
561 int n;
562 PyObject *wrapper;
563
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000564 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000565 compiler_unit_free(c->u);
566 /* Restore c->u to the parent unit. */
567 n = PyList_GET_SIZE(c->c_stack) - 1;
568 if (n >= 0) {
569 wrapper = PyList_GET_ITEM(c->c_stack, n);
570 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000571 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000572 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000574 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575 compiler_unit_check(c->u);
576 }
577 else
578 c->u = NULL;
579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580}
581
Guido van Rossumc2e20742006-02-27 22:32:47 +0000582/* Allocate a new "anonymous" local variable.
583 Used by list comprehensions and with statements.
584*/
585
586static PyObject *
587compiler_new_tmpname(struct compiler *c)
588{
589 char tmpname[256];
590 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
591 return PyString_FromString(tmpname);
592}
593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594/* Allocate a new block and return a pointer to it.
595 Returns NULL on error.
596*/
597
598static basicblock *
599compiler_new_block(struct compiler *c)
600{
601 basicblock *b;
602 struct compiler_unit *u;
603
604 u = c->u;
605 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000606 if (b == NULL) {
607 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612 b->b_list = u->u_blocks;
613 u->u_blocks = b;
614 return b;
615}
616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617static basicblock *
618compiler_use_new_block(struct compiler *c)
619{
620 basicblock *block = compiler_new_block(c);
621 if (block == NULL)
622 return NULL;
623 c->u->u_curblock = block;
624 return block;
625}
626
627static basicblock *
628compiler_next_block(struct compiler *c)
629{
630 basicblock *block = compiler_new_block(c);
631 if (block == NULL)
632 return NULL;
633 c->u->u_curblock->b_next = block;
634 c->u->u_curblock = block;
635 return block;
636}
637
638static basicblock *
639compiler_use_next_block(struct compiler *c, basicblock *block)
640{
641 assert(block != NULL);
642 c->u->u_curblock->b_next = block;
643 c->u->u_curblock = block;
644 return block;
645}
646
647/* Returns the offset of the next instruction in the current block's
648 b_instr array. Resizes the b_instr as necessary.
649 Returns -1 on failure.
650 */
651
652static int
653compiler_next_instr(struct compiler *c, basicblock *b)
654{
655 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 b->b_instr = (struct instr *)PyObject_Malloc(
658 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659 if (b->b_instr == NULL) {
660 PyErr_NoMemory();
661 return -1;
662 }
663 b->b_ialloc = DEFAULT_BLOCK_SIZE;
664 memset((char *)b->b_instr, 0,
665 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000668 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669 size_t oldsize, newsize;
670 oldsize = b->b_ialloc * sizeof(struct instr);
671 newsize = oldsize << 1;
672 if (newsize == 0) {
673 PyErr_NoMemory();
674 return -1;
675 }
676 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000678 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679 if (tmp == NULL) {
680 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000681 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000682 }
683 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
685 }
686 return b->b_iused++;
687}
688
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000689/* Set the i_lineno member of the instruction at offse off if the
690 line number for the current expression/statement (?) has not
691 already been set. If it has been set, the call has no effect.
692
693 Every time a new node is b
694 */
695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696static void
697compiler_set_lineno(struct compiler *c, int off)
698{
699 basicblock *b;
700 if (c->u->u_lineno_set)
701 return;
702 c->u->u_lineno_set = true;
703 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000704 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705}
706
707static int
708opcode_stack_effect(int opcode, int oparg)
709{
710 switch (opcode) {
711 case POP_TOP:
712 return -1;
713 case ROT_TWO:
714 case ROT_THREE:
715 return 0;
716 case DUP_TOP:
717 return 1;
718 case ROT_FOUR:
719 return 0;
720
721 case UNARY_POSITIVE:
722 case UNARY_NEGATIVE:
723 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724 case UNARY_INVERT:
725 return 0;
726
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000727 case LIST_APPEND:
728 return -2;
729
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 case BINARY_POWER:
731 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732 case BINARY_MODULO:
733 case BINARY_ADD:
734 case BINARY_SUBTRACT:
735 case BINARY_SUBSCR:
736 case BINARY_FLOOR_DIVIDE:
737 case BINARY_TRUE_DIVIDE:
738 return -1;
739 case INPLACE_FLOOR_DIVIDE:
740 case INPLACE_TRUE_DIVIDE:
741 return -1;
742
743 case SLICE+0:
744 return 1;
745 case SLICE+1:
746 return 0;
747 case SLICE+2:
748 return 0;
749 case SLICE+3:
750 return -1;
751
752 case STORE_SLICE+0:
753 return -2;
754 case STORE_SLICE+1:
755 return -3;
756 case STORE_SLICE+2:
757 return -3;
758 case STORE_SLICE+3:
759 return -4;
760
761 case DELETE_SLICE+0:
762 return -1;
763 case DELETE_SLICE+1:
764 return -2;
765 case DELETE_SLICE+2:
766 return -2;
767 case DELETE_SLICE+3:
768 return -3;
769
770 case INPLACE_ADD:
771 case INPLACE_SUBTRACT:
772 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773 case INPLACE_MODULO:
774 return -1;
775 case STORE_SUBSCR:
776 return -3;
777 case DELETE_SUBSCR:
778 return -2;
779
780 case BINARY_LSHIFT:
781 case BINARY_RSHIFT:
782 case BINARY_AND:
783 case BINARY_XOR:
784 case BINARY_OR:
785 return -1;
786 case INPLACE_POWER:
787 return -1;
788 case GET_ITER:
789 return 0;
790
791 case PRINT_EXPR:
792 return -1;
793 case PRINT_ITEM:
794 return -1;
795 case PRINT_NEWLINE:
796 return 0;
797 case PRINT_ITEM_TO:
798 return -2;
799 case PRINT_NEWLINE_TO:
800 return -1;
801 case INPLACE_LSHIFT:
802 case INPLACE_RSHIFT:
803 case INPLACE_AND:
804 case INPLACE_XOR:
805 case INPLACE_OR:
806 return -1;
807 case BREAK_LOOP:
808 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000809 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000810 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000811 case LOAD_LOCALS:
812 return 1;
813 case RETURN_VALUE:
814 return -1;
815 case IMPORT_STAR:
816 return -1;
817 case EXEC_STMT:
818 return -3;
819 case YIELD_VALUE:
820 return 0;
821
822 case POP_BLOCK:
823 return 0;
824 case END_FINALLY:
825 return -1; /* or -2 or -3 if exception occurred */
826 case BUILD_CLASS:
827 return -2;
828
829 case STORE_NAME:
830 return -1;
831 case DELETE_NAME:
832 return 0;
833 case UNPACK_SEQUENCE:
834 return oparg-1;
835 case FOR_ITER:
836 return 1;
837
838 case STORE_ATTR:
839 return -2;
840 case DELETE_ATTR:
841 return -1;
842 case STORE_GLOBAL:
843 return -1;
844 case DELETE_GLOBAL:
845 return 0;
846 case DUP_TOPX:
847 return oparg;
848 case LOAD_CONST:
849 return 1;
850 case LOAD_NAME:
851 return 1;
852 case BUILD_TUPLE:
853 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000854 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855 return 1-oparg;
856 case BUILD_MAP:
857 return 1;
858 case LOAD_ATTR:
859 return 0;
860 case COMPARE_OP:
861 return -1;
862 case IMPORT_NAME:
863 return 0;
864 case IMPORT_FROM:
865 return 1;
866
867 case JUMP_FORWARD:
868 case JUMP_IF_FALSE:
869 case JUMP_IF_TRUE:
870 case JUMP_ABSOLUTE:
871 return 0;
872
873 case LOAD_GLOBAL:
874 return 1;
875
876 case CONTINUE_LOOP:
877 return 0;
878 case SETUP_LOOP:
879 return 0;
880 case SETUP_EXCEPT:
881 case SETUP_FINALLY:
882 return 3; /* actually pushed by an exception */
883
884 case LOAD_FAST:
885 return 1;
886 case STORE_FAST:
887 return -1;
888 case DELETE_FAST:
889 return 0;
890
891 case RAISE_VARARGS:
892 return -oparg;
893#define NARGS(o) (((o) % 256) + 2*((o) / 256))
894 case CALL_FUNCTION:
895 return -NARGS(oparg);
896 case CALL_FUNCTION_VAR:
897 case CALL_FUNCTION_KW:
898 return -NARGS(oparg)-1;
899 case CALL_FUNCTION_VAR_KW:
900 return -NARGS(oparg)-2;
901#undef NARGS
902 case MAKE_FUNCTION:
903 return -oparg;
904 case BUILD_SLICE:
905 if (oparg == 3)
906 return -2;
907 else
908 return -1;
909
910 case MAKE_CLOSURE:
911 return -oparg;
912 case LOAD_CLOSURE:
913 return 1;
914 case LOAD_DEREF:
915 return 1;
916 case STORE_DEREF:
917 return -1;
918 default:
919 fprintf(stderr, "opcode = %d\n", opcode);
920 Py_FatalError("opcode_stack_effect()");
921
922 }
923 return 0; /* not reachable */
924}
925
926/* Add an opcode with no argument.
927 Returns 0 on failure, 1 on success.
928*/
929
930static int
931compiler_addop(struct compiler *c, int opcode)
932{
933 basicblock *b;
934 struct instr *i;
935 int off;
936 off = compiler_next_instr(c, c->u->u_curblock);
937 if (off < 0)
938 return 0;
939 b = c->u->u_curblock;
940 i = &b->b_instr[off];
941 i->i_opcode = opcode;
942 i->i_hasarg = 0;
943 if (opcode == RETURN_VALUE)
944 b->b_return = 1;
945 compiler_set_lineno(c, off);
946 return 1;
947}
948
949static int
950compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
951{
952 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000953 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000955 /* necessary to make sure types aren't coerced (e.g., int and long) */
956 t = PyTuple_Pack(2, o, o->ob_type);
957 if (t == NULL)
958 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
960 v = PyDict_GetItem(dict, t);
961 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000962 if (PyErr_Occurred())
963 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964 arg = PyDict_Size(dict);
965 v = PyInt_FromLong(arg);
966 if (!v) {
967 Py_DECREF(t);
968 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000969 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970 if (PyDict_SetItem(dict, t, v) < 0) {
971 Py_DECREF(t);
972 Py_DECREF(v);
973 return -1;
974 }
975 Py_DECREF(v);
976 }
977 else
978 arg = PyInt_AsLong(v);
979 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981}
982
983static int
984compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
985 PyObject *o)
986{
987 int arg = compiler_add_o(c, dict, o);
988 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000989 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990 return compiler_addop_i(c, opcode, arg);
991}
992
993static int
994compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000995 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000996{
997 int arg;
998 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
999 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001 arg = compiler_add_o(c, dict, mangled);
1002 Py_DECREF(mangled);
1003 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005 return compiler_addop_i(c, opcode, arg);
1006}
1007
1008/* Add an opcode with an integer argument.
1009 Returns 0 on failure, 1 on success.
1010*/
1011
1012static int
1013compiler_addop_i(struct compiler *c, int opcode, int oparg)
1014{
1015 struct instr *i;
1016 int off;
1017 off = compiler_next_instr(c, c->u->u_curblock);
1018 if (off < 0)
1019 return 0;
1020 i = &c->u->u_curblock->b_instr[off];
1021 i->i_opcode = opcode;
1022 i->i_oparg = oparg;
1023 i->i_hasarg = 1;
1024 compiler_set_lineno(c, off);
1025 return 1;
1026}
1027
1028static int
1029compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1030{
1031 struct instr *i;
1032 int off;
1033
1034 assert(b != NULL);
1035 off = compiler_next_instr(c, c->u->u_curblock);
1036 if (off < 0)
1037 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038 i = &c->u->u_curblock->b_instr[off];
1039 i->i_opcode = opcode;
1040 i->i_target = b;
1041 i->i_hasarg = 1;
1042 if (absolute)
1043 i->i_jabs = 1;
1044 else
1045 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001046 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047 return 1;
1048}
1049
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001050/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1051 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052 it as the current block. NEXT_BLOCK() also creates an implicit jump
1053 from the current block to the new block.
1054*/
1055
1056/* XXX The returns inside these macros make it impossible to decref
1057 objects created in the local function.
1058*/
1059
1060
1061#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001062 if (compiler_use_new_block((C)) == NULL) \
1063 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064}
1065
1066#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001067 if (compiler_next_block((C)) == NULL) \
1068 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069}
1070
1071#define ADDOP(C, OP) { \
1072 if (!compiler_addop((C), (OP))) \
1073 return 0; \
1074}
1075
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001076#define ADDOP_IN_SCOPE(C, OP) { \
1077 if (!compiler_addop((C), (OP))) { \
1078 compiler_exit_scope(c); \
1079 return 0; \
1080 } \
1081}
1082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083#define ADDOP_O(C, OP, O, TYPE) { \
1084 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1085 return 0; \
1086}
1087
1088#define ADDOP_NAME(C, OP, O, TYPE) { \
1089 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1090 return 0; \
1091}
1092
1093#define ADDOP_I(C, OP, O) { \
1094 if (!compiler_addop_i((C), (OP), (O))) \
1095 return 0; \
1096}
1097
1098#define ADDOP_JABS(C, OP, O) { \
1099 if (!compiler_addop_j((C), (OP), (O), 1)) \
1100 return 0; \
1101}
1102
1103#define ADDOP_JREL(C, OP, O) { \
1104 if (!compiler_addop_j((C), (OP), (O), 0)) \
1105 return 0; \
1106}
1107
1108/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1109 the ASDL name to synthesize the name of the C type and the visit function.
1110*/
1111
1112#define VISIT(C, TYPE, V) {\
1113 if (!compiler_visit_ ## TYPE((C), (V))) \
1114 return 0; \
1115}
1116
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001117#define VISIT_IN_SCOPE(C, TYPE, V) {\
1118 if (!compiler_visit_ ## TYPE((C), (V))) { \
1119 compiler_exit_scope(c); \
1120 return 0; \
1121 } \
1122}
1123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124#define VISIT_SLICE(C, V, CTX) {\
1125 if (!compiler_visit_slice((C), (V), (CTX))) \
1126 return 0; \
1127}
1128
1129#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001133 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134 if (!compiler_visit_ ## TYPE((C), elt)) \
1135 return 0; \
1136 } \
1137}
1138
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001141 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001144 if (!compiler_visit_ ## TYPE((C), elt)) { \
1145 compiler_exit_scope(c); \
1146 return 0; \
1147 } \
1148 } \
1149}
1150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151static int
1152compiler_isdocstring(stmt_ty s)
1153{
1154 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return s->v.Expr.value->kind == Str_kind;
1157}
1158
1159/* Compile a sequence of statements, checking for a docstring. */
1160
1161static int
1162compiler_body(struct compiler *c, asdl_seq *stmts)
1163{
1164 int i = 0;
1165 stmt_ty st;
1166
1167 if (!asdl_seq_LEN(stmts))
1168 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001169 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 if (compiler_isdocstring(st)) {
1171 i = 1;
1172 VISIT(c, expr, st->v.Expr.value);
1173 if (!compiler_nameop(c, __doc__, Store))
1174 return 0;
1175 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001176 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001177 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 return 1;
1179}
1180
1181static PyCodeObject *
1182compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001183{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001184 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001185 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 static PyObject *module;
1187 if (!module) {
1188 module = PyString_FromString("<module>");
1189 if (!module)
1190 return NULL;
1191 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001192 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1193 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001194 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 switch (mod->kind) {
1196 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001197 if (!compiler_body(c, mod->v.Module.body)) {
1198 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 break;
1202 case Interactive_kind:
1203 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001204 VISIT_SEQ_IN_SCOPE(c, stmt,
1205 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 break;
1207 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001208 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 break;
1211 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001212 PyErr_SetString(PyExc_SystemError,
1213 "suite should not be possible");
1214 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001215 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001216 PyErr_Format(PyExc_SystemError,
1217 "module kind %d should not be possible",
1218 mod->kind);
1219 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 co = assemble(c, addNone);
1222 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001223 return co;
1224}
1225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226/* The test for LOCAL must come before the test for FREE in order to
1227 handle classes where name is both local and free. The local var is
1228 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001229*/
1230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231static int
1232get_ref_type(struct compiler *c, PyObject *name)
1233{
1234 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001235 if (scope == 0) {
1236 char buf[350];
1237 PyOS_snprintf(buf, sizeof(buf),
1238 "unknown scope for %.100s in %.100s(%s) in %s\n"
1239 "symbols: %s\nlocals: %s\nglobals: %s\n",
1240 PyString_AS_STRING(name),
1241 PyString_AS_STRING(c->u->u_name),
1242 PyObject_REPR(c->u->u_ste->ste_id),
1243 c->c_filename,
1244 PyObject_REPR(c->u->u_ste->ste_symbols),
1245 PyObject_REPR(c->u->u_varnames),
1246 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001248 Py_FatalError(buf);
1249 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254static int
1255compiler_lookup_arg(PyObject *dict, PyObject *name)
1256{
1257 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001260 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001262 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001264 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 return PyInt_AS_LONG(v);
1266}
1267
1268static int
1269compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1270{
1271 int i, free = PyCode_GetNumFree(co);
1272 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001273 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1274 ADDOP_I(c, MAKE_FUNCTION, args);
1275 return 1;
1276 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 for (i = 0; i < free; ++i) {
1278 /* Bypass com_addop_varname because it will generate
1279 LOAD_DEREF but LOAD_CLOSURE is needed.
1280 */
1281 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1282 int arg, reftype;
1283
1284 /* Special case: If a class contains a method with a
1285 free variable that has the same name as a method,
1286 the name will be considered free *and* local in the
1287 class. It should be handled by the closure, as
1288 well as by the normal name loookup logic.
1289 */
1290 reftype = get_ref_type(c, name);
1291 if (reftype == CELL)
1292 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1293 else /* (reftype == FREE) */
1294 arg = compiler_lookup_arg(c->u->u_freevars, name);
1295 if (arg == -1) {
1296 printf("lookup %s in %s %d %d\n"
1297 "freevars of %s: %s\n",
1298 PyObject_REPR(name),
1299 PyString_AS_STRING(c->u->u_name),
1300 reftype, arg,
1301 PyString_AS_STRING(co->co_name),
1302 PyObject_REPR(co->co_freevars));
1303 Py_FatalError("compiler_make_closure()");
1304 }
1305 ADDOP_I(c, LOAD_CLOSURE, arg);
1306 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001309 ADDOP_I(c, MAKE_CLOSURE, args);
1310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
1314compiler_decorators(struct compiler *c, asdl_seq* decos)
1315{
1316 int i;
1317
1318 if (!decos)
1319 return 1;
1320
1321 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 }
1324 return 1;
1325}
1326
1327static int
1328compiler_arguments(struct compiler *c, arguments_ty args)
1329{
1330 int i;
1331 int n = asdl_seq_LEN(args->args);
1332 /* Correctly handle nested argument lists */
1333 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001334 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 if (arg->kind == Tuple_kind) {
1336 PyObject *id = PyString_FromFormat(".%d", i);
1337 if (id == NULL) {
1338 return 0;
1339 }
1340 if (!compiler_nameop(c, id, Load)) {
1341 Py_DECREF(id);
1342 return 0;
1343 }
1344 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001345 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 }
1347 }
1348 return 1;
1349}
1350
1351static int
1352compiler_function(struct compiler *c, stmt_ty s)
1353{
1354 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001355 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 arguments_ty args = s->v.FunctionDef.args;
1357 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001358 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 int i, n, docstring;
1360
1361 assert(s->kind == FunctionDef_kind);
1362
1363 if (!compiler_decorators(c, decos))
1364 return 0;
1365 if (args->defaults)
1366 VISIT_SEQ(c, expr, args->defaults);
1367 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1368 s->lineno))
1369 return 0;
1370
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001371 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001372 docstring = compiler_isdocstring(st);
1373 if (docstring)
1374 first_const = st->v.Expr.value->v.Str.s;
1375 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001376 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001377 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001378 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001380 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381 compiler_arguments(c, args);
1382
1383 c->u->u_argcount = asdl_seq_LEN(args->args);
1384 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001385 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1388 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389 }
1390 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001391 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392 if (co == NULL)
1393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001395 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001396 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397
1398 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1399 ADDOP_I(c, CALL_FUNCTION, 1);
1400 }
1401
1402 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1403}
1404
1405static int
1406compiler_class(struct compiler *c, stmt_ty s)
1407{
1408 int n;
1409 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001410 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411 /* push class name on stack, needed by BUILD_CLASS */
1412 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1413 /* push the tuple of base classes on the stack */
1414 n = asdl_seq_LEN(s->v.ClassDef.bases);
1415 if (n > 0)
1416 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1417 ADDOP_I(c, BUILD_TUPLE, n);
1418 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1419 s->lineno))
1420 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001421 c->u->u_private = s->v.ClassDef.name;
1422 Py_INCREF(c->u->u_private);
1423 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001424 if (!str || !compiler_nameop(c, str, Load)) {
1425 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001426 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001428 }
1429
1430 Py_DECREF(str);
1431 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432 if (!str || !compiler_nameop(c, str, Store)) {
1433 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001434 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001436 }
1437 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001439 if (!compiler_body(c, s->v.ClassDef.body)) {
1440 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001442 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001444 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1445 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001447 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448 if (co == NULL)
1449 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001451 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001452 Py_DECREF(co);
1453
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 ADDOP_I(c, CALL_FUNCTION, 0);
1455 ADDOP(c, BUILD_CLASS);
1456 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1457 return 0;
1458 return 1;
1459}
1460
1461static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001462compiler_ifexp(struct compiler *c, expr_ty e)
1463{
1464 basicblock *end, *next;
1465
1466 assert(e->kind == IfExp_kind);
1467 end = compiler_new_block(c);
1468 if (end == NULL)
1469 return 0;
1470 next = compiler_new_block(c);
1471 if (next == NULL)
1472 return 0;
1473 VISIT(c, expr, e->v.IfExp.test);
1474 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1475 ADDOP(c, POP_TOP);
1476 VISIT(c, expr, e->v.IfExp.body);
1477 ADDOP_JREL(c, JUMP_FORWARD, end);
1478 compiler_use_next_block(c, next);
1479 ADDOP(c, POP_TOP);
1480 VISIT(c, expr, e->v.IfExp.orelse);
1481 compiler_use_next_block(c, end);
1482 return 1;
1483}
1484
1485static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486compiler_lambda(struct compiler *c, expr_ty e)
1487{
1488 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001489 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490 arguments_ty args = e->v.Lambda.args;
1491 assert(e->kind == Lambda_kind);
1492
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001493 if (!name) {
1494 name = PyString_InternFromString("<lambda>");
1495 if (!name)
1496 return 0;
1497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498
1499 if (args->defaults)
1500 VISIT_SEQ(c, expr, args->defaults);
1501 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1502 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001503
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001504 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505 compiler_arguments(c, args);
1506
1507 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001508 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1509 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001511 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512 if (co == NULL)
1513 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001515 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001516 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517
1518 return 1;
1519}
1520
1521static int
1522compiler_print(struct compiler *c, stmt_ty s)
1523{
1524 int i, n;
1525 bool dest;
1526
1527 assert(s->kind == Print_kind);
1528 n = asdl_seq_LEN(s->v.Print.values);
1529 dest = false;
1530 if (s->v.Print.dest) {
1531 VISIT(c, expr, s->v.Print.dest);
1532 dest = true;
1533 }
1534 for (i = 0; i < n; i++) {
1535 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1536 if (dest) {
1537 ADDOP(c, DUP_TOP);
1538 VISIT(c, expr, e);
1539 ADDOP(c, ROT_TWO);
1540 ADDOP(c, PRINT_ITEM_TO);
1541 }
1542 else {
1543 VISIT(c, expr, e);
1544 ADDOP(c, PRINT_ITEM);
1545 }
1546 }
1547 if (s->v.Print.nl) {
1548 if (dest)
1549 ADDOP(c, PRINT_NEWLINE_TO)
1550 else
1551 ADDOP(c, PRINT_NEWLINE)
1552 }
1553 else if (dest)
1554 ADDOP(c, POP_TOP);
1555 return 1;
1556}
1557
1558static int
1559compiler_if(struct compiler *c, stmt_ty s)
1560{
1561 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001562 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001563 assert(s->kind == If_kind);
1564 end = compiler_new_block(c);
1565 if (end == NULL)
1566 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001567 next = compiler_new_block(c);
1568 if (next == NULL)
1569 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001570
1571 constant = expr_constant(s->v.If.test);
1572 /* constant = 0: "if 0"
1573 * constant = 1: "if 1", "if 2", ...
1574 * constant = -1: rest */
1575 if (constant == 0) {
1576 if (s->v.If.orelse)
1577 VISIT_SEQ(c, stmt, s->v.If.orelse);
1578 } else if (constant == 1) {
1579 VISIT_SEQ(c, stmt, s->v.If.body);
1580 } else {
1581 VISIT(c, expr, s->v.If.test);
1582 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1583 ADDOP(c, POP_TOP);
1584 VISIT_SEQ(c, stmt, s->v.If.body);
1585 ADDOP_JREL(c, JUMP_FORWARD, end);
1586 compiler_use_next_block(c, next);
1587 ADDOP(c, POP_TOP);
1588 if (s->v.If.orelse)
1589 VISIT_SEQ(c, stmt, s->v.If.orelse);
1590 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591 compiler_use_next_block(c, end);
1592 return 1;
1593}
1594
1595static int
1596compiler_for(struct compiler *c, stmt_ty s)
1597{
1598 basicblock *start, *cleanup, *end;
1599
1600 start = compiler_new_block(c);
1601 cleanup = compiler_new_block(c);
1602 end = compiler_new_block(c);
1603 if (start == NULL || end == NULL || cleanup == NULL)
1604 return 0;
1605 ADDOP_JREL(c, SETUP_LOOP, end);
1606 if (!compiler_push_fblock(c, LOOP, start))
1607 return 0;
1608 VISIT(c, expr, s->v.For.iter);
1609 ADDOP(c, GET_ITER);
1610 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001611 /* XXX(nnorwitz): is there a better way to handle this?
1612 for loops are special, we want to be able to trace them
1613 each time around, so we need to set an extra line number. */
1614 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615 ADDOP_JREL(c, FOR_ITER, cleanup);
1616 VISIT(c, expr, s->v.For.target);
1617 VISIT_SEQ(c, stmt, s->v.For.body);
1618 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1619 compiler_use_next_block(c, cleanup);
1620 ADDOP(c, POP_BLOCK);
1621 compiler_pop_fblock(c, LOOP, start);
1622 VISIT_SEQ(c, stmt, s->v.For.orelse);
1623 compiler_use_next_block(c, end);
1624 return 1;
1625}
1626
1627static int
1628compiler_while(struct compiler *c, stmt_ty s)
1629{
1630 basicblock *loop, *orelse, *end, *anchor = NULL;
1631 int constant = expr_constant(s->v.While.test);
1632
1633 if (constant == 0)
1634 return 1;
1635 loop = compiler_new_block(c);
1636 end = compiler_new_block(c);
1637 if (constant == -1) {
1638 anchor = compiler_new_block(c);
1639 if (anchor == NULL)
1640 return 0;
1641 }
1642 if (loop == NULL || end == NULL)
1643 return 0;
1644 if (s->v.While.orelse) {
1645 orelse = compiler_new_block(c);
1646 if (orelse == NULL)
1647 return 0;
1648 }
1649 else
1650 orelse = NULL;
1651
1652 ADDOP_JREL(c, SETUP_LOOP, end);
1653 compiler_use_next_block(c, loop);
1654 if (!compiler_push_fblock(c, LOOP, loop))
1655 return 0;
1656 if (constant == -1) {
1657 VISIT(c, expr, s->v.While.test);
1658 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1659 ADDOP(c, POP_TOP);
1660 }
1661 VISIT_SEQ(c, stmt, s->v.While.body);
1662 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1663
1664 /* XXX should the two POP instructions be in a separate block
1665 if there is no else clause ?
1666 */
1667
1668 if (constant == -1) {
1669 compiler_use_next_block(c, anchor);
1670 ADDOP(c, POP_TOP);
1671 ADDOP(c, POP_BLOCK);
1672 }
1673 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001674 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 VISIT_SEQ(c, stmt, s->v.While.orelse);
1676 compiler_use_next_block(c, end);
1677
1678 return 1;
1679}
1680
1681static int
1682compiler_continue(struct compiler *c)
1683{
1684 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1685 int i;
1686
1687 if (!c->u->u_nfblocks)
1688 return compiler_error(c, LOOP_ERROR_MSG);
1689 i = c->u->u_nfblocks - 1;
1690 switch (c->u->u_fblock[i].fb_type) {
1691 case LOOP:
1692 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1693 break;
1694 case EXCEPT:
1695 case FINALLY_TRY:
1696 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1697 ;
1698 if (i == -1)
1699 return compiler_error(c, LOOP_ERROR_MSG);
1700 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1701 break;
1702 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001703 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 "'continue' not supported inside 'finally' clause");
1705 }
1706
1707 return 1;
1708}
1709
1710/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1711
1712 SETUP_FINALLY L
1713 <code for body>
1714 POP_BLOCK
1715 LOAD_CONST <None>
1716 L: <code for finalbody>
1717 END_FINALLY
1718
1719 The special instructions use the block stack. Each block
1720 stack entry contains the instruction that created it (here
1721 SETUP_FINALLY), the level of the value stack at the time the
1722 block stack entry was created, and a label (here L).
1723
1724 SETUP_FINALLY:
1725 Pushes the current value stack level and the label
1726 onto the block stack.
1727 POP_BLOCK:
1728 Pops en entry from the block stack, and pops the value
1729 stack until its level is the same as indicated on the
1730 block stack. (The label is ignored.)
1731 END_FINALLY:
1732 Pops a variable number of entries from the *value* stack
1733 and re-raises the exception they specify. The number of
1734 entries popped depends on the (pseudo) exception type.
1735
1736 The block stack is unwound when an exception is raised:
1737 when a SETUP_FINALLY entry is found, the exception is pushed
1738 onto the value stack (and the exception condition is cleared),
1739 and the interpreter jumps to the label gotten from the block
1740 stack.
1741*/
1742
1743static int
1744compiler_try_finally(struct compiler *c, stmt_ty s)
1745{
1746 basicblock *body, *end;
1747 body = compiler_new_block(c);
1748 end = compiler_new_block(c);
1749 if (body == NULL || end == NULL)
1750 return 0;
1751
1752 ADDOP_JREL(c, SETUP_FINALLY, end);
1753 compiler_use_next_block(c, body);
1754 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1755 return 0;
1756 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1757 ADDOP(c, POP_BLOCK);
1758 compiler_pop_fblock(c, FINALLY_TRY, body);
1759
1760 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1761 compiler_use_next_block(c, end);
1762 if (!compiler_push_fblock(c, FINALLY_END, end))
1763 return 0;
1764 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1765 ADDOP(c, END_FINALLY);
1766 compiler_pop_fblock(c, FINALLY_END, end);
1767
1768 return 1;
1769}
1770
1771/*
1772 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1773 (The contents of the value stack is shown in [], with the top
1774 at the right; 'tb' is trace-back info, 'val' the exception's
1775 associated value, and 'exc' the exception.)
1776
1777 Value stack Label Instruction Argument
1778 [] SETUP_EXCEPT L1
1779 [] <code for S>
1780 [] POP_BLOCK
1781 [] JUMP_FORWARD L0
1782
1783 [tb, val, exc] L1: DUP )
1784 [tb, val, exc, exc] <evaluate E1> )
1785 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1786 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1787 [tb, val, exc, 1] POP )
1788 [tb, val, exc] POP
1789 [tb, val] <assign to V1> (or POP if no V1)
1790 [tb] POP
1791 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001792 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793
1794 [tb, val, exc, 0] L2: POP
1795 [tb, val, exc] DUP
1796 .............................etc.......................
1797
1798 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001799 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
1801 [] L0: <next statement>
1802
1803 Of course, parts are not generated if Vi or Ei is not present.
1804*/
1805static int
1806compiler_try_except(struct compiler *c, stmt_ty s)
1807{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001808 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 int i, n;
1810
1811 body = compiler_new_block(c);
1812 except = compiler_new_block(c);
1813 orelse = compiler_new_block(c);
1814 end = compiler_new_block(c);
1815 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1816 return 0;
1817 ADDOP_JREL(c, SETUP_EXCEPT, except);
1818 compiler_use_next_block(c, body);
1819 if (!compiler_push_fblock(c, EXCEPT, body))
1820 return 0;
1821 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1822 ADDOP(c, POP_BLOCK);
1823 compiler_pop_fblock(c, EXCEPT, body);
1824 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1825 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1826 compiler_use_next_block(c, except);
1827 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001828 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 s->v.TryExcept.handlers, i);
1830 if (!handler->type && i < n-1)
1831 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001832 c->u->u_lineno_set = false;
1833 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 except = compiler_new_block(c);
1835 if (except == NULL)
1836 return 0;
1837 if (handler->type) {
1838 ADDOP(c, DUP_TOP);
1839 VISIT(c, expr, handler->type);
1840 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1841 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1842 ADDOP(c, POP_TOP);
1843 }
1844 ADDOP(c, POP_TOP);
1845 if (handler->name) {
1846 VISIT(c, expr, handler->name);
1847 }
1848 else {
1849 ADDOP(c, POP_TOP);
1850 }
1851 ADDOP(c, POP_TOP);
1852 VISIT_SEQ(c, stmt, handler->body);
1853 ADDOP_JREL(c, JUMP_FORWARD, end);
1854 compiler_use_next_block(c, except);
1855 if (handler->type)
1856 ADDOP(c, POP_TOP);
1857 }
1858 ADDOP(c, END_FINALLY);
1859 compiler_use_next_block(c, orelse);
1860 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1861 compiler_use_next_block(c, end);
1862 return 1;
1863}
1864
1865static int
1866compiler_import_as(struct compiler *c, identifier name, identifier asname)
1867{
1868 /* The IMPORT_NAME opcode was already generated. This function
1869 merely needs to bind the result to a name.
1870
1871 If there is a dot in name, we need to split it and emit a
1872 LOAD_ATTR for each name.
1873 */
1874 const char *src = PyString_AS_STRING(name);
1875 const char *dot = strchr(src, '.');
1876 if (dot) {
1877 /* Consume the base module name to get the first attribute */
1878 src = dot + 1;
1879 while (dot) {
1880 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001881 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001883 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001885 if (!attr)
1886 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001888 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889 src = dot + 1;
1890 }
1891 }
1892 return compiler_nameop(c, asname, Store);
1893}
1894
1895static int
1896compiler_import(struct compiler *c, stmt_ty s)
1897{
1898 /* The Import node stores a module name like a.b.c as a single
1899 string. This is convenient for all cases except
1900 import a.b.c as d
1901 where we need to parse that string to extract the individual
1902 module names.
1903 XXX Perhaps change the representation to make this case simpler?
1904 */
1905 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001906
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001908 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001910 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911
Guido van Rossum45aecf42006-03-15 04:58:47 +00001912 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001913 if (level == NULL)
1914 return 0;
1915
1916 ADDOP_O(c, LOAD_CONST, level, consts);
1917 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1919 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1920
1921 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001922 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001923 if (!r)
1924 return r;
1925 }
1926 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 identifier tmp = alias->name;
1928 const char *base = PyString_AS_STRING(alias->name);
1929 char *dot = strchr(base, '.');
1930 if (dot)
1931 tmp = PyString_FromStringAndSize(base,
1932 dot - base);
1933 r = compiler_nameop(c, tmp, Store);
1934 if (dot) {
1935 Py_DECREF(tmp);
1936 }
1937 if (!r)
1938 return r;
1939 }
1940 }
1941 return 1;
1942}
1943
1944static int
1945compiler_from_import(struct compiler *c, stmt_ty s)
1946{
1947 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948
1949 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001950 PyObject *level;
1951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952 if (!names)
1953 return 0;
1954
Guido van Rossum45aecf42006-03-15 04:58:47 +00001955 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001956 if (!level) {
1957 Py_DECREF(names);
1958 return 0;
1959 }
1960
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961 /* build up the names */
1962 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001963 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964 Py_INCREF(alias->name);
1965 PyTuple_SET_ITEM(names, i, alias->name);
1966 }
1967
1968 if (s->lineno > c->c_future->ff_lineno) {
1969 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1970 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001971 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972 Py_DECREF(names);
1973 return compiler_error(c,
1974 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001975 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
1977 }
1978 }
1979
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001980 ADDOP_O(c, LOAD_CONST, level, consts);
1981 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001983 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1985 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001986 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 identifier store_name;
1988
1989 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1990 assert(n == 1);
1991 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001992 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 }
1994
1995 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1996 store_name = alias->name;
1997 if (alias->asname)
1998 store_name = alias->asname;
1999
2000 if (!compiler_nameop(c, store_name, Store)) {
2001 Py_DECREF(names);
2002 return 0;
2003 }
2004 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002005 /* remove imported module */
2006 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 return 1;
2008}
2009
2010static int
2011compiler_assert(struct compiler *c, stmt_ty s)
2012{
2013 static PyObject *assertion_error = NULL;
2014 basicblock *end;
2015
2016 if (Py_OptimizeFlag)
2017 return 1;
2018 if (assertion_error == NULL) {
2019 assertion_error = PyString_FromString("AssertionError");
2020 if (assertion_error == NULL)
2021 return 0;
2022 }
2023 VISIT(c, expr, s->v.Assert.test);
2024 end = compiler_new_block(c);
2025 if (end == NULL)
2026 return 0;
2027 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2028 ADDOP(c, POP_TOP);
2029 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2030 if (s->v.Assert.msg) {
2031 VISIT(c, expr, s->v.Assert.msg);
2032 ADDOP_I(c, RAISE_VARARGS, 2);
2033 }
2034 else {
2035 ADDOP_I(c, RAISE_VARARGS, 1);
2036 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002037 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 ADDOP(c, POP_TOP);
2039 return 1;
2040}
2041
2042static int
2043compiler_visit_stmt(struct compiler *c, stmt_ty s)
2044{
2045 int i, n;
2046
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002047 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048 c->u->u_lineno = s->lineno;
2049 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002050
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002052 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002054 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002056 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 if (c->u->u_ste->ste_type != FunctionBlock)
2058 return compiler_error(c, "'return' outside function");
2059 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 VISIT(c, expr, s->v.Return.value);
2061 }
2062 else
2063 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2064 ADDOP(c, RETURN_VALUE);
2065 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002066 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 VISIT_SEQ(c, expr, s->v.Delete.targets)
2068 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002069 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070 n = asdl_seq_LEN(s->v.Assign.targets);
2071 VISIT(c, expr, s->v.Assign.value);
2072 for (i = 0; i < n; i++) {
2073 if (i < n - 1)
2074 ADDOP(c, DUP_TOP);
2075 VISIT(c, expr,
2076 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2077 }
2078 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002081 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002083 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002085 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002087 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 n = 0;
2091 if (s->v.Raise.type) {
2092 VISIT(c, expr, s->v.Raise.type);
2093 n++;
2094 if (s->v.Raise.inst) {
2095 VISIT(c, expr, s->v.Raise.inst);
2096 n++;
2097 if (s->v.Raise.tback) {
2098 VISIT(c, expr, s->v.Raise.tback);
2099 n++;
2100 }
2101 }
2102 }
2103 ADDOP_I(c, RAISE_VARARGS, n);
2104 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002107 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002111 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002113 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002115 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116 VISIT(c, expr, s->v.Exec.body);
2117 if (s->v.Exec.globals) {
2118 VISIT(c, expr, s->v.Exec.globals);
2119 if (s->v.Exec.locals) {
2120 VISIT(c, expr, s->v.Exec.locals);
2121 } else {
2122 ADDOP(c, DUP_TOP);
2123 }
2124 } else {
2125 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2126 ADDOP(c, DUP_TOP);
2127 }
2128 ADDOP(c, EXEC_STMT);
2129 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002130 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002132 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002134 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 ADDOP(c, PRINT_EXPR);
2136 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002137 else if (s->v.Expr.value->kind != Str_kind &&
2138 s->v.Expr.value->kind != Num_kind) {
2139 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140 ADDOP(c, POP_TOP);
2141 }
2142 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002143 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002145 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 if (!c->u->u_nfblocks)
2147 return compiler_error(c, "'break' outside loop");
2148 ADDOP(c, BREAK_LOOP);
2149 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002150 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002152 case With_kind:
2153 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 }
2155 return 1;
2156}
2157
2158static int
2159unaryop(unaryop_ty op)
2160{
2161 switch (op) {
2162 case Invert:
2163 return UNARY_INVERT;
2164 case Not:
2165 return UNARY_NOT;
2166 case UAdd:
2167 return UNARY_POSITIVE;
2168 case USub:
2169 return UNARY_NEGATIVE;
2170 }
2171 return 0;
2172}
2173
2174static int
2175binop(struct compiler *c, operator_ty op)
2176{
2177 switch (op) {
2178 case Add:
2179 return BINARY_ADD;
2180 case Sub:
2181 return BINARY_SUBTRACT;
2182 case Mult:
2183 return BINARY_MULTIPLY;
2184 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002185 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 case Mod:
2187 return BINARY_MODULO;
2188 case Pow:
2189 return BINARY_POWER;
2190 case LShift:
2191 return BINARY_LSHIFT;
2192 case RShift:
2193 return BINARY_RSHIFT;
2194 case BitOr:
2195 return BINARY_OR;
2196 case BitXor:
2197 return BINARY_XOR;
2198 case BitAnd:
2199 return BINARY_AND;
2200 case FloorDiv:
2201 return BINARY_FLOOR_DIVIDE;
2202 }
2203 return 0;
2204}
2205
2206static int
2207cmpop(cmpop_ty op)
2208{
2209 switch (op) {
2210 case Eq:
2211 return PyCmp_EQ;
2212 case NotEq:
2213 return PyCmp_NE;
2214 case Lt:
2215 return PyCmp_LT;
2216 case LtE:
2217 return PyCmp_LE;
2218 case Gt:
2219 return PyCmp_GT;
2220 case GtE:
2221 return PyCmp_GE;
2222 case Is:
2223 return PyCmp_IS;
2224 case IsNot:
2225 return PyCmp_IS_NOT;
2226 case In:
2227 return PyCmp_IN;
2228 case NotIn:
2229 return PyCmp_NOT_IN;
2230 }
2231 return PyCmp_BAD;
2232}
2233
2234static int
2235inplace_binop(struct compiler *c, operator_ty op)
2236{
2237 switch (op) {
2238 case Add:
2239 return INPLACE_ADD;
2240 case Sub:
2241 return INPLACE_SUBTRACT;
2242 case Mult:
2243 return INPLACE_MULTIPLY;
2244 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002245 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246 case Mod:
2247 return INPLACE_MODULO;
2248 case Pow:
2249 return INPLACE_POWER;
2250 case LShift:
2251 return INPLACE_LSHIFT;
2252 case RShift:
2253 return INPLACE_RSHIFT;
2254 case BitOr:
2255 return INPLACE_OR;
2256 case BitXor:
2257 return INPLACE_XOR;
2258 case BitAnd:
2259 return INPLACE_AND;
2260 case FloorDiv:
2261 return INPLACE_FLOOR_DIVIDE;
2262 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002263 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002264 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 return 0;
2266}
2267
2268static int
2269compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2270{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002271 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2273
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002274 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002275 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 /* XXX AugStore isn't used anywhere! */
2277
2278 /* First check for assignment to __debug__. Param? */
2279 if ((ctx == Store || ctx == AugStore || ctx == Del)
2280 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2281 return compiler_error(c, "can not assign to __debug__");
2282 }
2283
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002284 mangled = _Py_Mangle(c->u->u_private, name);
2285 if (!mangled)
2286 return 0;
2287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 op = 0;
2289 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002290 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 switch (scope) {
2292 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 optype = OP_DEREF;
2295 break;
2296 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002297 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 optype = OP_DEREF;
2299 break;
2300 case LOCAL:
2301 if (c->u->u_ste->ste_type == FunctionBlock)
2302 optype = OP_FAST;
2303 break;
2304 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002305 if (c->u->u_ste->ste_type == FunctionBlock &&
2306 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 optype = OP_GLOBAL;
2308 break;
2309 case GLOBAL_EXPLICIT:
2310 optype = OP_GLOBAL;
2311 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002312 default:
2313 /* scope can be 0 */
2314 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315 }
2316
2317 /* XXX Leave assert here, but handle __doc__ and the like better */
2318 assert(scope || PyString_AS_STRING(name)[0] == '_');
2319
2320 switch (optype) {
2321 case OP_DEREF:
2322 switch (ctx) {
2323 case Load: op = LOAD_DEREF; break;
2324 case Store: op = STORE_DEREF; break;
2325 case AugLoad:
2326 case AugStore:
2327 break;
2328 case Del:
2329 PyErr_Format(PyExc_SyntaxError,
2330 "can not delete variable '%s' referenced "
2331 "in nested scope",
2332 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002333 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002336 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002337 PyErr_SetString(PyExc_SystemError,
2338 "param invalid for deref variable");
2339 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340 }
2341 break;
2342 case OP_FAST:
2343 switch (ctx) {
2344 case Load: op = LOAD_FAST; break;
2345 case Store: op = STORE_FAST; break;
2346 case Del: op = DELETE_FAST; break;
2347 case AugLoad:
2348 case AugStore:
2349 break;
2350 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002351 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002352 PyErr_SetString(PyExc_SystemError,
2353 "param invalid for local variable");
2354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002356 ADDOP_O(c, op, mangled, varnames);
2357 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358 return 1;
2359 case OP_GLOBAL:
2360 switch (ctx) {
2361 case Load: op = LOAD_GLOBAL; break;
2362 case Store: op = STORE_GLOBAL; break;
2363 case Del: op = DELETE_GLOBAL; break;
2364 case AugLoad:
2365 case AugStore:
2366 break;
2367 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002368 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002369 PyErr_SetString(PyExc_SystemError,
2370 "param invalid for global variable");
2371 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372 }
2373 break;
2374 case OP_NAME:
2375 switch (ctx) {
2376 case Load: op = LOAD_NAME; break;
2377 case Store: op = STORE_NAME; break;
2378 case Del: op = DELETE_NAME; break;
2379 case AugLoad:
2380 case AugStore:
2381 break;
2382 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002383 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002384 PyErr_SetString(PyExc_SystemError,
2385 "param invalid for name variable");
2386 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387 }
2388 break;
2389 }
2390
2391 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002392 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002393 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002394 if (arg < 0)
2395 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002396 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397}
2398
2399static int
2400compiler_boolop(struct compiler *c, expr_ty e)
2401{
2402 basicblock *end;
2403 int jumpi, i, n;
2404 asdl_seq *s;
2405
2406 assert(e->kind == BoolOp_kind);
2407 if (e->v.BoolOp.op == And)
2408 jumpi = JUMP_IF_FALSE;
2409 else
2410 jumpi = JUMP_IF_TRUE;
2411 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002412 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413 return 0;
2414 s = e->v.BoolOp.values;
2415 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002416 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002418 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419 ADDOP_JREL(c, jumpi, end);
2420 ADDOP(c, POP_TOP)
2421 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002422 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423 compiler_use_next_block(c, end);
2424 return 1;
2425}
2426
2427static int
2428compiler_list(struct compiler *c, expr_ty e)
2429{
2430 int n = asdl_seq_LEN(e->v.List.elts);
2431 if (e->v.List.ctx == Store) {
2432 ADDOP_I(c, UNPACK_SEQUENCE, n);
2433 }
2434 VISIT_SEQ(c, expr, e->v.List.elts);
2435 if (e->v.List.ctx == Load) {
2436 ADDOP_I(c, BUILD_LIST, n);
2437 }
2438 return 1;
2439}
2440
2441static int
2442compiler_tuple(struct compiler *c, expr_ty e)
2443{
2444 int n = asdl_seq_LEN(e->v.Tuple.elts);
2445 if (e->v.Tuple.ctx == Store) {
2446 ADDOP_I(c, UNPACK_SEQUENCE, n);
2447 }
2448 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2449 if (e->v.Tuple.ctx == Load) {
2450 ADDOP_I(c, BUILD_TUPLE, n);
2451 }
2452 return 1;
2453}
2454
2455static int
2456compiler_compare(struct compiler *c, expr_ty e)
2457{
2458 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002459 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460
2461 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2462 VISIT(c, expr, e->v.Compare.left);
2463 n = asdl_seq_LEN(e->v.Compare.ops);
2464 assert(n > 0);
2465 if (n > 1) {
2466 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002467 if (cleanup == NULL)
2468 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002469 VISIT(c, expr,
2470 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 }
2472 for (i = 1; i < n; i++) {
2473 ADDOP(c, DUP_TOP);
2474 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002476 cmpop((cmpop_ty)(asdl_seq_GET(
2477 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2479 NEXT_BLOCK(c);
2480 ADDOP(c, POP_TOP);
2481 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002482 VISIT(c, expr,
2483 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002485 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002487 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 if (n > 1) {
2489 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002490 if (end == NULL)
2491 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002492 ADDOP_JREL(c, JUMP_FORWARD, end);
2493 compiler_use_next_block(c, cleanup);
2494 ADDOP(c, ROT_TWO);
2495 ADDOP(c, POP_TOP);
2496 compiler_use_next_block(c, end);
2497 }
2498 return 1;
2499}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002500#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501
2502static int
2503compiler_call(struct compiler *c, expr_ty e)
2504{
2505 int n, code = 0;
2506
2507 VISIT(c, expr, e->v.Call.func);
2508 n = asdl_seq_LEN(e->v.Call.args);
2509 VISIT_SEQ(c, expr, e->v.Call.args);
2510 if (e->v.Call.keywords) {
2511 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2512 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2513 }
2514 if (e->v.Call.starargs) {
2515 VISIT(c, expr, e->v.Call.starargs);
2516 code |= 1;
2517 }
2518 if (e->v.Call.kwargs) {
2519 VISIT(c, expr, e->v.Call.kwargs);
2520 code |= 2;
2521 }
2522 switch (code) {
2523 case 0:
2524 ADDOP_I(c, CALL_FUNCTION, n);
2525 break;
2526 case 1:
2527 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2528 break;
2529 case 2:
2530 ADDOP_I(c, CALL_FUNCTION_KW, n);
2531 break;
2532 case 3:
2533 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2534 break;
2535 }
2536 return 1;
2537}
2538
2539static int
2540compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002541 asdl_seq *generators, int gen_index,
2542 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543{
2544 /* generate code for the iterator, then each of the ifs,
2545 and then write to the element */
2546
2547 comprehension_ty l;
2548 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002549 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550
2551 start = compiler_new_block(c);
2552 skip = compiler_new_block(c);
2553 if_cleanup = compiler_new_block(c);
2554 anchor = compiler_new_block(c);
2555
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002556 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2557 anchor == NULL)
2558 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002560 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561 VISIT(c, expr, l->iter);
2562 ADDOP(c, GET_ITER);
2563 compiler_use_next_block(c, start);
2564 ADDOP_JREL(c, FOR_ITER, anchor);
2565 NEXT_BLOCK(c);
2566 VISIT(c, expr, l->target);
2567
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002568 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569 n = asdl_seq_LEN(l->ifs);
2570 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002571 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572 VISIT(c, expr, e);
2573 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2574 NEXT_BLOCK(c);
2575 ADDOP(c, POP_TOP);
2576 }
2577
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002578 if (++gen_index < asdl_seq_LEN(generators))
2579 if (!compiler_listcomp_generator(c, tmpname,
2580 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 /* only append after the last for generator */
2584 if (gen_index >= asdl_seq_LEN(generators)) {
2585 if (!compiler_nameop(c, tmpname, Load))
2586 return 0;
2587 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002588 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002589
2590 compiler_use_next_block(c, skip);
2591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 for (i = 0; i < n; i++) {
2593 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002594 if (i == 0)
2595 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596 ADDOP(c, POP_TOP);
2597 }
2598 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2599 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002600 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002602 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 return 0;
2604
2605 return 1;
2606}
2607
2608static int
2609compiler_listcomp(struct compiler *c, expr_ty e)
2610{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002612 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613 static identifier append;
2614 asdl_seq *generators = e->v.ListComp.generators;
2615
2616 assert(e->kind == ListComp_kind);
2617 if (!append) {
2618 append = PyString_InternFromString("append");
2619 if (!append)
2620 return 0;
2621 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002622 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 if (!tmp)
2624 return 0;
2625 ADDOP_I(c, BUILD_LIST, 0);
2626 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002628 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2629 e->v.ListComp.elt);
2630 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 return rc;
2632}
2633
2634static int
2635compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636 asdl_seq *generators, int gen_index,
2637 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638{
2639 /* generate code for the iterator, then each of the ifs,
2640 and then write to the element */
2641
2642 comprehension_ty ge;
2643 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002644 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645
2646 start = compiler_new_block(c);
2647 skip = compiler_new_block(c);
2648 if_cleanup = compiler_new_block(c);
2649 anchor = compiler_new_block(c);
2650 end = compiler_new_block(c);
2651
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 anchor == NULL || end == NULL)
2654 return 0;
2655
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002656 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 ADDOP_JREL(c, SETUP_LOOP, end);
2658 if (!compiler_push_fblock(c, LOOP, start))
2659 return 0;
2660
2661 if (gen_index == 0) {
2662 /* Receive outermost iter as an implicit argument */
2663 c->u->u_argcount = 1;
2664 ADDOP_I(c, LOAD_FAST, 0);
2665 }
2666 else {
2667 /* Sub-iter - calculate on the fly */
2668 VISIT(c, expr, ge->iter);
2669 ADDOP(c, GET_ITER);
2670 }
2671 compiler_use_next_block(c, start);
2672 ADDOP_JREL(c, FOR_ITER, anchor);
2673 NEXT_BLOCK(c);
2674 VISIT(c, expr, ge->target);
2675
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002676 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677 n = asdl_seq_LEN(ge->ifs);
2678 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002679 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 VISIT(c, expr, e);
2681 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2682 NEXT_BLOCK(c);
2683 ADDOP(c, POP_TOP);
2684 }
2685
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002686 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2688 return 0;
2689
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002690 /* only append after the last 'for' generator */
2691 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 VISIT(c, expr, elt);
2693 ADDOP(c, YIELD_VALUE);
2694 ADDOP(c, POP_TOP);
2695
2696 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002697 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 for (i = 0; i < n; i++) {
2699 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 compiler_use_next_block(c, if_cleanup);
2702
2703 ADDOP(c, POP_TOP);
2704 }
2705 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2706 compiler_use_next_block(c, anchor);
2707 ADDOP(c, POP_BLOCK);
2708 compiler_pop_fblock(c, LOOP, start);
2709 compiler_use_next_block(c, end);
2710
2711 return 1;
2712}
2713
2714static int
2715compiler_genexp(struct compiler *c, expr_ty e)
2716{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002717 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 PyCodeObject *co;
2719 expr_ty outermost_iter = ((comprehension_ty)
2720 (asdl_seq_GET(e->v.GeneratorExp.generators,
2721 0)))->iter;
2722
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002723 if (!name) {
2724 name = PyString_FromString("<genexpr>");
2725 if (!name)
2726 return 0;
2727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728
2729 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2730 return 0;
2731 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2732 e->v.GeneratorExp.elt);
2733 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002734 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 if (co == NULL)
2736 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002738 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002739 Py_DECREF(co);
2740
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741 VISIT(c, expr, outermost_iter);
2742 ADDOP(c, GET_ITER);
2743 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
2745 return 1;
2746}
2747
2748static int
2749compiler_visit_keyword(struct compiler *c, keyword_ty k)
2750{
2751 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2752 VISIT(c, expr, k->value);
2753 return 1;
2754}
2755
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002756/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 whether they are true or false.
2758
2759 Return values: 1 for true, 0 for false, -1 for non-constant.
2760 */
2761
2762static int
2763expr_constant(expr_ty e)
2764{
2765 switch (e->kind) {
2766 case Num_kind:
2767 return PyObject_IsTrue(e->v.Num.n);
2768 case Str_kind:
2769 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002770 case Name_kind:
2771 /* __debug__ is not assignable, so we can optimize
2772 * it away in if and while statements */
2773 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2774 "__debug__") == 0)
2775 return ! Py_OptimizeFlag;
2776 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777 default:
2778 return -1;
2779 }
2780}
2781
Guido van Rossumc2e20742006-02-27 22:32:47 +00002782/*
2783 Implements the with statement from PEP 343.
2784
2785 The semantics outlined in that PEP are as follows:
2786
2787 with EXPR as VAR:
2788 BLOCK
2789
2790 It is implemented roughly as:
2791
Thomas Wouters477c8d52006-05-27 19:21:47 +00002792 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002793 exit = context.__exit__ # not calling it
2794 value = context.__enter__()
2795 try:
2796 VAR = value # if VAR present in the syntax
2797 BLOCK
2798 finally:
2799 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002800 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002802 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002803 exit(*exc)
2804 */
2805static int
2806compiler_with(struct compiler *c, stmt_ty s)
2807{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002808 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002809 basicblock *block, *finally;
2810 identifier tmpexit, tmpvalue = NULL;
2811
2812 assert(s->kind == With_kind);
2813
Guido van Rossumc2e20742006-02-27 22:32:47 +00002814 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 enter_attr = PyString_InternFromString("__enter__");
2816 if (!enter_attr)
2817 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002818 }
2819 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 exit_attr = PyString_InternFromString("__exit__");
2821 if (!exit_attr)
2822 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002823 }
2824
2825 block = compiler_new_block(c);
2826 finally = compiler_new_block(c);
2827 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002828 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002829
2830 /* Create a temporary variable to hold context.__exit__ */
2831 tmpexit = compiler_new_tmpname(c);
2832 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002833 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834 PyArena_AddPyObject(c->c_arena, tmpexit);
2835
2836 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002837 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002838 We need to do this rather than preserving it on the stack
2839 because SETUP_FINALLY remembers the stack level.
2840 We need to do the assignment *inside* the try/finally
2841 so that context.__exit__() is called when the assignment
2842 fails. But we need to call context.__enter__() *before*
2843 the try/finally so that if it fails we won't call
2844 context.__exit__().
2845 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002846 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002847 if (tmpvalue == NULL)
2848 return 0;
2849 PyArena_AddPyObject(c->c_arena, tmpvalue);
2850 }
2851
Thomas Wouters477c8d52006-05-27 19:21:47 +00002852 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002853 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002854
2855 /* Squirrel away context.__exit__ */
2856 ADDOP(c, DUP_TOP);
2857 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2858 if (!compiler_nameop(c, tmpexit, Store))
2859 return 0;
2860
2861 /* Call context.__enter__() */
2862 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2863 ADDOP_I(c, CALL_FUNCTION, 0);
2864
2865 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002866 /* Store it in tmpvalue */
2867 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002868 return 0;
2869 }
2870 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002871 /* Discard result from context.__enter__() */
2872 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002873 }
2874
2875 /* Start the try block */
2876 ADDOP_JREL(c, SETUP_FINALLY, finally);
2877
2878 compiler_use_next_block(c, block);
2879 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002880 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002881 }
2882
2883 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002884 /* Bind saved result of context.__enter__() to VAR */
2885 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002886 !compiler_nameop(c, tmpvalue, Del))
2887 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002888 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002889 }
2890
2891 /* BLOCK code */
2892 VISIT_SEQ(c, stmt, s->v.With.body);
2893
2894 /* End of try block; start the finally block */
2895 ADDOP(c, POP_BLOCK);
2896 compiler_pop_fblock(c, FINALLY_TRY, block);
2897
2898 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2899 compiler_use_next_block(c, finally);
2900 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002901 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002902
2903 /* Finally block starts; push tmpexit and issue our magic opcode. */
2904 if (!compiler_nameop(c, tmpexit, Load) ||
2905 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002906 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002907 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908
2909 /* Finally block ends. */
2910 ADDOP(c, END_FINALLY);
2911 compiler_pop_fblock(c, FINALLY_END, finally);
2912 return 1;
2913}
2914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915static int
2916compiler_visit_expr(struct compiler *c, expr_ty e)
2917{
2918 int i, n;
2919
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002920 /* If expr e has a different line number than the last expr/stmt,
2921 set a new line number for the next instruction.
2922 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 if (e->lineno > c->u->u_lineno) {
2924 c->u->u_lineno = e->lineno;
2925 c->u->u_lineno_set = false;
2926 }
2927 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002928 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002930 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 VISIT(c, expr, e->v.BinOp.left);
2932 VISIT(c, expr, e->v.BinOp.right);
2933 ADDOP(c, binop(c, e->v.BinOp.op));
2934 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002935 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 VISIT(c, expr, e->v.UnaryOp.operand);
2937 ADDOP(c, unaryop(e->v.UnaryOp.op));
2938 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002939 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002941 case IfExp_kind:
2942 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002943 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 /* XXX get rid of arg? */
2945 ADDOP_I(c, BUILD_MAP, 0);
2946 n = asdl_seq_LEN(e->v.Dict.values);
2947 /* We must arrange things just right for STORE_SUBSCR.
2948 It wants the stack to look like (value) (dict) (key) */
2949 for (i = 0; i < n; i++) {
2950 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002951 VISIT(c, expr,
2952 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002954 VISIT(c, expr,
2955 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 ADDOP(c, STORE_SUBSCR);
2957 }
2958 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002959 case Set_kind:
2960 n = asdl_seq_LEN(e->v.Set.elts);
2961 VISIT_SEQ(c, expr, e->v.Set.elts);
2962 ADDOP_I(c, BUILD_SET, n);
2963 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002964 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002966 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 return compiler_genexp(c, e);
2968 case Yield_kind:
2969 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002970 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 /*
2972 for (i = 0; i < c->u->u_nfblocks; i++) {
2973 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2974 return compiler_error(
2975 c, "'yield' not allowed in a 'try' "
2976 "block with a 'finally' clause");
2977 }
2978 */
2979 if (e->v.Yield.value) {
2980 VISIT(c, expr, e->v.Yield.value);
2981 }
2982 else {
2983 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2984 }
2985 ADDOP(c, YIELD_VALUE);
2986 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002987 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002988 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002989 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002991 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2993 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002994 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2996 break;
2997 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002998 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 if (e->v.Attribute.ctx != AugStore)
3000 VISIT(c, expr, e->v.Attribute.value);
3001 switch (e->v.Attribute.ctx) {
3002 case AugLoad:
3003 ADDOP(c, DUP_TOP);
3004 /* Fall through to load */
3005 case Load:
3006 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3007 break;
3008 case AugStore:
3009 ADDOP(c, ROT_TWO);
3010 /* Fall through to save */
3011 case Store:
3012 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3013 break;
3014 case Del:
3015 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3016 break;
3017 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003018 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003019 PyErr_SetString(PyExc_SystemError,
3020 "param invalid in attribute expression");
3021 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022 }
3023 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003024 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025 switch (e->v.Subscript.ctx) {
3026 case AugLoad:
3027 VISIT(c, expr, e->v.Subscript.value);
3028 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3029 break;
3030 case Load:
3031 VISIT(c, expr, e->v.Subscript.value);
3032 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3033 break;
3034 case AugStore:
3035 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3036 break;
3037 case Store:
3038 VISIT(c, expr, e->v.Subscript.value);
3039 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3040 break;
3041 case Del:
3042 VISIT(c, expr, e->v.Subscript.value);
3043 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3044 break;
3045 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003046 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003047 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003048 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003049 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 }
3051 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003052 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3054 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003055 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058 return compiler_tuple(c, e);
3059 }
3060 return 1;
3061}
3062
3063static int
3064compiler_augassign(struct compiler *c, stmt_ty s)
3065{
3066 expr_ty e = s->v.AugAssign.target;
3067 expr_ty auge;
3068
3069 assert(s->kind == AugAssign_kind);
3070
3071 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003072 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003074 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003075 if (auge == NULL)
3076 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 VISIT(c, expr, auge);
3078 VISIT(c, expr, s->v.AugAssign.value);
3079 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3080 auge->v.Attribute.ctx = AugStore;
3081 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082 break;
3083 case Subscript_kind:
3084 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003085 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003086 if (auge == NULL)
3087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 VISIT(c, expr, auge);
3089 VISIT(c, expr, s->v.AugAssign.value);
3090 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003091 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003093 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003095 if (!compiler_nameop(c, e->v.Name.id, Load))
3096 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003097 VISIT(c, expr, s->v.AugAssign.value);
3098 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3099 return compiler_nameop(c, e->v.Name.id, Store);
3100 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003101 PyErr_Format(PyExc_SystemError,
3102 "invalid node type (%d) for augmented assignment",
3103 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003104 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105 }
3106 return 1;
3107}
3108
3109static int
3110compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3111{
3112 struct fblockinfo *f;
3113 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3114 return 0;
3115 f = &c->u->u_fblock[c->u->u_nfblocks++];
3116 f->fb_type = t;
3117 f->fb_block = b;
3118 return 1;
3119}
3120
3121static void
3122compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3123{
3124 struct compiler_unit *u = c->u;
3125 assert(u->u_nfblocks > 0);
3126 u->u_nfblocks--;
3127 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3128 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3129}
3130
3131/* Raises a SyntaxError and returns 0.
3132 If something goes wrong, a different exception may be raised.
3133*/
3134
3135static int
3136compiler_error(struct compiler *c, const char *errstr)
3137{
3138 PyObject *loc;
3139 PyObject *u = NULL, *v = NULL;
3140
3141 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3142 if (!loc) {
3143 Py_INCREF(Py_None);
3144 loc = Py_None;
3145 }
3146 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3147 Py_None, loc);
3148 if (!u)
3149 goto exit;
3150 v = Py_BuildValue("(zO)", errstr, u);
3151 if (!v)
3152 goto exit;
3153 PyErr_SetObject(PyExc_SyntaxError, v);
3154 exit:
3155 Py_DECREF(loc);
3156 Py_XDECREF(u);
3157 Py_XDECREF(v);
3158 return 0;
3159}
3160
3161static int
3162compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003163 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003165 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 /* XXX this code is duplicated */
3168 switch (ctx) {
3169 case AugLoad: /* fall through to Load */
3170 case Load: op = BINARY_SUBSCR; break;
3171 case AugStore:/* fall through to Store */
3172 case Store: op = STORE_SUBSCR; break;
3173 case Del: op = DELETE_SUBSCR; break;
3174 case Param:
3175 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003176 "invalid %s kind %d in subscript\n",
3177 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003178 return 0;
3179 }
3180 if (ctx == AugLoad) {
3181 ADDOP_I(c, DUP_TOPX, 2);
3182 }
3183 else if (ctx == AugStore) {
3184 ADDOP(c, ROT_THREE);
3185 }
3186 ADDOP(c, op);
3187 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188}
3189
3190static int
3191compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3192{
3193 int n = 2;
3194 assert(s->kind == Slice_kind);
3195
3196 /* only handles the cases where BUILD_SLICE is emitted */
3197 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 }
3200 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003201 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 }
3207 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003208 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209 }
3210
3211 if (s->v.Slice.step) {
3212 n++;
3213 VISIT(c, expr, s->v.Slice.step);
3214 }
3215 ADDOP_I(c, BUILD_SLICE, n);
3216 return 1;
3217}
3218
3219static int
3220compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3221{
3222 int op = 0, slice_offset = 0, stack_count = 0;
3223
3224 assert(s->v.Slice.step == NULL);
3225 if (s->v.Slice.lower) {
3226 slice_offset++;
3227 stack_count++;
3228 if (ctx != AugStore)
3229 VISIT(c, expr, s->v.Slice.lower);
3230 }
3231 if (s->v.Slice.upper) {
3232 slice_offset += 2;
3233 stack_count++;
3234 if (ctx != AugStore)
3235 VISIT(c, expr, s->v.Slice.upper);
3236 }
3237
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003238 if (ctx == AugLoad) {
3239 switch (stack_count) {
3240 case 0: ADDOP(c, DUP_TOP); break;
3241 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3242 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3243 }
3244 }
3245 else if (ctx == AugStore) {
3246 switch (stack_count) {
3247 case 0: ADDOP(c, ROT_TWO); break;
3248 case 1: ADDOP(c, ROT_THREE); break;
3249 case 2: ADDOP(c, ROT_FOUR); break;
3250 }
3251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
3253 switch (ctx) {
3254 case AugLoad: /* fall through to Load */
3255 case Load: op = SLICE; break;
3256 case AugStore:/* fall through to Store */
3257 case Store: op = STORE_SLICE; break;
3258 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003259 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003260 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003261 PyErr_SetString(PyExc_SystemError,
3262 "param invalid in simple slice");
3263 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 }
3265
3266 ADDOP(c, op + slice_offset);
3267 return 1;
3268}
3269
3270static int
3271compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3272 expr_context_ty ctx)
3273{
3274 switch (s->kind) {
3275 case Ellipsis_kind:
3276 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3277 break;
3278 case Slice_kind:
3279 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 case Index_kind:
3281 VISIT(c, expr, s->v.Index.value);
3282 break;
3283 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003284 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003285 PyErr_SetString(PyExc_SystemError,
3286 "extended slice invalid in nested slice");
3287 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288 }
3289 return 1;
3290}
3291
3292
3293static int
3294compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3295{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003296 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003298 case Index_kind:
3299 kindname = "index";
3300 if (ctx != AugStore) {
3301 VISIT(c, expr, s->v.Index.value);
3302 }
3303 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003305 kindname = "ellipsis";
3306 if (ctx != AugStore) {
3307 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3308 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309 break;
3310 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003311 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003312 if (!s->v.Slice.step)
3313 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003314 if (ctx != AugStore) {
3315 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 return 0;
3317 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003318 break;
3319 case ExtSlice_kind:
3320 kindname = "extended slice";
3321 if (ctx != AugStore) {
3322 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3323 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003324 slice_ty sub = (slice_ty)asdl_seq_GET(
3325 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003326 if (!compiler_visit_nested_slice(c, sub, ctx))
3327 return 0;
3328 }
3329 ADDOP_I(c, BUILD_TUPLE, n);
3330 }
3331 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003332 default:
3333 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003334 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003335 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003337 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338}
3339
3340/* do depth-first search of basic block graph, starting with block.
3341 post records the block indices in post-order.
3342
3343 XXX must handle implicit jumps from one block to next
3344*/
3345
3346static void
3347dfs(struct compiler *c, basicblock *b, struct assembler *a)
3348{
3349 int i;
3350 struct instr *instr = NULL;
3351
3352 if (b->b_seen)
3353 return;
3354 b->b_seen = 1;
3355 if (b->b_next != NULL)
3356 dfs(c, b->b_next, a);
3357 for (i = 0; i < b->b_iused; i++) {
3358 instr = &b->b_instr[i];
3359 if (instr->i_jrel || instr->i_jabs)
3360 dfs(c, instr->i_target, a);
3361 }
3362 a->a_postorder[a->a_nblocks++] = b;
3363}
3364
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003365static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3367{
3368 int i;
3369 struct instr *instr;
3370 if (b->b_seen || b->b_startdepth >= depth)
3371 return maxdepth;
3372 b->b_seen = 1;
3373 b->b_startdepth = depth;
3374 for (i = 0; i < b->b_iused; i++) {
3375 instr = &b->b_instr[i];
3376 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3377 if (depth > maxdepth)
3378 maxdepth = depth;
3379 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3380 if (instr->i_jrel || instr->i_jabs) {
3381 maxdepth = stackdepth_walk(c, instr->i_target,
3382 depth, maxdepth);
3383 if (instr->i_opcode == JUMP_ABSOLUTE ||
3384 instr->i_opcode == JUMP_FORWARD) {
3385 goto out; /* remaining code is dead */
3386 }
3387 }
3388 }
3389 if (b->b_next)
3390 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3391out:
3392 b->b_seen = 0;
3393 return maxdepth;
3394}
3395
3396/* Find the flow path that needs the largest stack. We assume that
3397 * cycles in the flow graph have no net effect on the stack depth.
3398 */
3399static int
3400stackdepth(struct compiler *c)
3401{
3402 basicblock *b, *entryblock;
3403 entryblock = NULL;
3404 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3405 b->b_seen = 0;
3406 b->b_startdepth = INT_MIN;
3407 entryblock = b;
3408 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003409 if (!entryblock)
3410 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003411 return stackdepth_walk(c, entryblock, 0, 0);
3412}
3413
3414static int
3415assemble_init(struct assembler *a, int nblocks, int firstlineno)
3416{
3417 memset(a, 0, sizeof(struct assembler));
3418 a->a_lineno = firstlineno;
3419 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3420 if (!a->a_bytecode)
3421 return 0;
3422 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3423 if (!a->a_lnotab)
3424 return 0;
3425 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003426 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003427 if (!a->a_postorder) {
3428 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003429 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003430 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431 return 1;
3432}
3433
3434static void
3435assemble_free(struct assembler *a)
3436{
3437 Py_XDECREF(a->a_bytecode);
3438 Py_XDECREF(a->a_lnotab);
3439 if (a->a_postorder)
3440 PyObject_Free(a->a_postorder);
3441}
3442
3443/* Return the size of a basic block in bytes. */
3444
3445static int
3446instrsize(struct instr *instr)
3447{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003448 if (!instr->i_hasarg)
3449 return 1;
3450 if (instr->i_oparg > 0xffff)
3451 return 6;
3452 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453}
3454
3455static int
3456blocksize(basicblock *b)
3457{
3458 int i;
3459 int size = 0;
3460
3461 for (i = 0; i < b->b_iused; i++)
3462 size += instrsize(&b->b_instr[i]);
3463 return size;
3464}
3465
3466/* All about a_lnotab.
3467
3468c_lnotab is an array of unsigned bytes disguised as a Python string.
3469It is used to map bytecode offsets to source code line #s (when needed
3470for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003471
Tim Peters2a7f3842001-06-09 09:26:21 +00003472The array is conceptually a list of
3473 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003474pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003475
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003476 byte code offset source code line number
3477 0 1
3478 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003479 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003480 350 307
3481 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003482
3483The first trick is that these numbers aren't stored, only the increments
3484from one row to the next (this doesn't really work, but it's a start):
3485
3486 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3487
3488The second trick is that an unsigned byte can't hold negative values, or
3489values larger than 255, so (a) there's a deep assumption that byte code
3490offsets and their corresponding line #s both increase monotonically, and (b)
3491if at least one column jumps by more than 255 from one row to the next, more
3492than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003494part. A user of c_lnotab desiring to find the source line number
3495corresponding to a bytecode address A should do something like this
3496
3497 lineno = addr = 0
3498 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003499 addr += addr_incr
3500 if addr > A:
3501 return lineno
3502 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003503
3504In order for this to work, when the addr field increments by more than 255,
3505the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003506increment is < 256. So, in the example above, assemble_lnotab (it used
3507to be called com_set_lineno) should not (as was actually done until 2.2)
3508expand 300, 300 to 255, 255, 45, 45,
3509 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003510*/
3511
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003512static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003513assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003514{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515 int d_bytecode, d_lineno;
3516 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003517 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518
3519 d_bytecode = a->a_offset - a->a_lineno_off;
3520 d_lineno = i->i_lineno - a->a_lineno;
3521
3522 assert(d_bytecode >= 0);
3523 assert(d_lineno >= 0);
3524
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003525 /* XXX(nnorwitz): is there a better way to handle this?
3526 for loops are special, we want to be able to trace them
3527 each time around, so we need to set an extra line number. */
3528 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003529 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003532 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533 nbytes = a->a_lnotab_off + 2 * ncodes;
3534 len = PyString_GET_SIZE(a->a_lnotab);
3535 if (nbytes >= len) {
3536 if (len * 2 < nbytes)
3537 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003538 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 len *= 2;
3540 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3541 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003542 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003543 lnotab = (unsigned char *)
3544 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003545 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 *lnotab++ = 255;
3547 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003548 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 d_bytecode -= ncodes * 255;
3550 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003551 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 assert(d_bytecode <= 255);
3553 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003554 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 nbytes = a->a_lnotab_off + 2 * ncodes;
3556 len = PyString_GET_SIZE(a->a_lnotab);
3557 if (nbytes >= len) {
3558 if (len * 2 < nbytes)
3559 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003560 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 len *= 2;
3562 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3563 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003564 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003565 lnotab = (unsigned char *)
3566 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003568 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003570 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003572 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003573 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 d_lineno -= ncodes * 255;
3575 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003576 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003577
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578 len = PyString_GET_SIZE(a->a_lnotab);
3579 if (a->a_lnotab_off + 2 >= len) {
3580 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003581 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003582 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003583 lnotab = (unsigned char *)
3584 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003585
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 a->a_lnotab_off += 2;
3587 if (d_bytecode) {
3588 *lnotab++ = d_bytecode;
3589 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003590 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003591 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 *lnotab++ = 0;
3593 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595 a->a_lineno = i->i_lineno;
3596 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003597 return 1;
3598}
3599
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600/* assemble_emit()
3601 Extend the bytecode with a new instruction.
3602 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003603*/
3604
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003605static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003607{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003608 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003609 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610 char *code;
3611
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003612 size = instrsize(i);
3613 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003615 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003618 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619 if (a->a_offset + size >= len) {
3620 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003621 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3624 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003625 if (size == 6) {
3626 assert(i->i_hasarg);
3627 *code++ = (char)EXTENDED_ARG;
3628 *code++ = ext & 0xff;
3629 *code++ = ext >> 8;
3630 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003631 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003633 if (i->i_hasarg) {
3634 assert(size == 3 || size == 6);
3635 *code++ = arg & 0xff;
3636 *code++ = arg >> 8;
3637 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003639}
3640
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003641static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003643{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003645 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003646 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 /* Compute the size of each block and fixup jump args.
3649 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003650start:
3651 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003653 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 bsize = blocksize(b);
3655 b->b_offset = totsize;
3656 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003657 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003658 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3660 bsize = b->b_offset;
3661 for (i = 0; i < b->b_iused; i++) {
3662 struct instr *instr = &b->b_instr[i];
3663 /* Relative jumps are computed relative to
3664 the instruction pointer after fetching
3665 the jump instruction.
3666 */
3667 bsize += instrsize(instr);
3668 if (instr->i_jabs)
3669 instr->i_oparg = instr->i_target->b_offset;
3670 else if (instr->i_jrel) {
3671 int delta = instr->i_target->b_offset - bsize;
3672 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003673 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003674 else
3675 continue;
3676 if (instr->i_oparg > 0xffff)
3677 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003678 }
3679 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003680
3681 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003682 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003683 with a better solution.
3684
3685 In the meantime, should the goto be dropped in favor
3686 of a loop?
3687
3688 The issue is that in the first loop blocksize() is called
3689 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003690 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003691 i_oparg is calculated in the second loop above.
3692
3693 So we loop until we stop seeing new EXTENDED_ARGs.
3694 The only EXTENDED_ARGs that could be popping up are
3695 ones in jump instructions. So this should converge
3696 fairly quickly.
3697 */
3698 if (last_extended_arg_count != extended_arg_count) {
3699 last_extended_arg_count = extended_arg_count;
3700 goto start;
3701 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003702}
3703
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003704static PyObject *
3705dict_keys_inorder(PyObject *dict, int offset)
3706{
3707 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003708 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003709
3710 tuple = PyTuple_New(size);
3711 if (tuple == NULL)
3712 return NULL;
3713 while (PyDict_Next(dict, &pos, &k, &v)) {
3714 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003715 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003716 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003717 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003718 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003719 PyTuple_SET_ITEM(tuple, i - offset, k);
3720 }
3721 return tuple;
3722}
3723
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003724static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003726{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727 PySTEntryObject *ste = c->u->u_ste;
3728 int flags = 0, n;
3729 if (ste->ste_type != ModuleBlock)
3730 flags |= CO_NEWLOCALS;
3731 if (ste->ste_type == FunctionBlock) {
3732 if (!ste->ste_unoptimized)
3733 flags |= CO_OPTIMIZED;
3734 if (ste->ste_nested)
3735 flags |= CO_NESTED;
3736 if (ste->ste_generator)
3737 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003738 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 if (ste->ste_varargs)
3740 flags |= CO_VARARGS;
3741 if (ste->ste_varkeywords)
3742 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003743 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003745
3746 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003747 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003748
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003749 n = PyDict_Size(c->u->u_freevars);
3750 if (n < 0)
3751 return -1;
3752 if (n == 0) {
3753 n = PyDict_Size(c->u->u_cellvars);
3754 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003755 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756 if (n == 0) {
3757 flags |= CO_NOFREE;
3758 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003759 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003760
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003761 return flags;
3762}
3763
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764static PyCodeObject *
3765makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003766{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767 PyObject *tmp;
3768 PyCodeObject *co = NULL;
3769 PyObject *consts = NULL;
3770 PyObject *names = NULL;
3771 PyObject *varnames = NULL;
3772 PyObject *filename = NULL;
3773 PyObject *name = NULL;
3774 PyObject *freevars = NULL;
3775 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003776 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003778
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779 tmp = dict_keys_inorder(c->u->u_consts, 0);
3780 if (!tmp)
3781 goto error;
3782 consts = PySequence_List(tmp); /* optimize_code requires a list */
3783 Py_DECREF(tmp);
3784
3785 names = dict_keys_inorder(c->u->u_names, 0);
3786 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3787 if (!consts || !names || !varnames)
3788 goto error;
3789
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003790 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3791 if (!cellvars)
3792 goto error;
3793 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3794 if (!freevars)
3795 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 filename = PyString_FromString(c->c_filename);
3797 if (!filename)
3798 goto error;
3799
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003800 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801 flags = compute_code_flags(c);
3802 if (flags < 0)
3803 goto error;
3804
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003805 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806 if (!bytecode)
3807 goto error;
3808
3809 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3810 if (!tmp)
3811 goto error;
3812 Py_DECREF(consts);
3813 consts = tmp;
3814
3815 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3816 bytecode, consts, names, varnames,
3817 freevars, cellvars,
3818 filename, c->u->u_name,
3819 c->u->u_firstlineno,
3820 a->a_lnotab);
3821 error:
3822 Py_XDECREF(consts);
3823 Py_XDECREF(names);
3824 Py_XDECREF(varnames);
3825 Py_XDECREF(filename);
3826 Py_XDECREF(name);
3827 Py_XDECREF(freevars);
3828 Py_XDECREF(cellvars);
3829 Py_XDECREF(bytecode);
3830 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003831}
3832
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003833
3834/* For debugging purposes only */
3835#if 0
3836static void
3837dump_instr(const struct instr *i)
3838{
3839 const char *jrel = i->i_jrel ? "jrel " : "";
3840 const char *jabs = i->i_jabs ? "jabs " : "";
3841 char arg[128];
3842
3843 *arg = '\0';
3844 if (i->i_hasarg)
3845 sprintf(arg, "arg: %d ", i->i_oparg);
3846
3847 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3848 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3849}
3850
3851static void
3852dump_basicblock(const basicblock *b)
3853{
3854 const char *seen = b->b_seen ? "seen " : "";
3855 const char *b_return = b->b_return ? "return " : "";
3856 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3857 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3858 if (b->b_instr) {
3859 int i;
3860 for (i = 0; i < b->b_iused; i++) {
3861 fprintf(stderr, " [%02d] ", i);
3862 dump_instr(b->b_instr + i);
3863 }
3864 }
3865}
3866#endif
3867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868static PyCodeObject *
3869assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003870{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871 basicblock *b, *entryblock;
3872 struct assembler a;
3873 int i, j, nblocks;
3874 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 /* Make sure every block that falls off the end returns None.
3877 XXX NEXT_BLOCK() isn't quite right, because if the last
3878 block ends with a jump or return b_next shouldn't set.
3879 */
3880 if (!c->u->u_curblock->b_return) {
3881 NEXT_BLOCK(c);
3882 if (addNone)
3883 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3884 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003885 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887 nblocks = 0;
3888 entryblock = NULL;
3889 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3890 nblocks++;
3891 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003892 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003893
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003894 /* Set firstlineno if it wasn't explicitly set. */
3895 if (!c->u->u_firstlineno) {
3896 if (entryblock && entryblock->b_instr)
3897 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3898 else
3899 c->u->u_firstlineno = 1;
3900 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3902 goto error;
3903 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003904
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003906 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003907
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908 /* Emit code in reverse postorder from dfs. */
3909 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003910 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911 for (j = 0; j < b->b_iused; j++)
3912 if (!assemble_emit(&a, &b->b_instr[j]))
3913 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003914 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003915
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3917 goto error;
3918 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3919 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003920
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921 co = makecode(c, &a);
3922 error:
3923 assemble_free(&a);
3924 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003925}