blob: 067c04d12af55eda346afb4615264c37dcc07284 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000146 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
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 *
Anthony Baxter7b782b62006-04-11 12:01:56 +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;
Neal Norwitz84167d02006-08-12 01:45:47 +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 }
Anthony Baxter7b782b62006-04-11 12:01:56 +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;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000303 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +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)
Neal Norwitz14bc4e42006-04-10 06:57:06 +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;
Georg Brandl5c170fd2006-03-17 19:03:25 +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);
Georg Brandl7784f122006-05-26 20:04:44 +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++;
Georg Brandl7784f122006-05-26 20:04:44 +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 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +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
Anthony Baxter7b782b62006-04-11 12:01:56 +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);
Neal Norwitzd12bd012006-07-21 07:59:47 +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));
Neal Norwitzd12bd012006-07-21 07:59:47 +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);
Neal Norwitzb59d08c2006-07-22 16:20:49 +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);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000571 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000573 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000574 compiler_unit_check(c->u);
575 }
576 else
577 c->u = NULL;
578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579}
580
Guido van Rossumc2e20742006-02-27 22:32:47 +0000581/* Allocate a new "anonymous" local variable.
582 Used by list comprehensions and with statements.
583*/
584
585static PyObject *
586compiler_new_tmpname(struct compiler *c)
587{
588 char tmpname[256];
589 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
590 return PyString_FromString(tmpname);
591}
592
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593/* Allocate a new block and return a pointer to it.
594 Returns NULL on error.
595*/
596
597static basicblock *
598compiler_new_block(struct compiler *c)
599{
600 basicblock *b;
601 struct compiler_unit *u;
602
603 u = c->u;
604 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000605 if (b == NULL) {
606 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +0000610 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 b->b_list = u->u_blocks;
612 u->u_blocks = b;
613 return b;
614}
615
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616static basicblock *
617compiler_use_new_block(struct compiler *c)
618{
619 basicblock *block = compiler_new_block(c);
620 if (block == NULL)
621 return NULL;
622 c->u->u_curblock = block;
623 return block;
624}
625
626static basicblock *
627compiler_next_block(struct compiler *c)
628{
629 basicblock *block = compiler_new_block(c);
630 if (block == NULL)
631 return NULL;
632 c->u->u_curblock->b_next = block;
633 c->u->u_curblock = block;
634 return block;
635}
636
637static basicblock *
638compiler_use_next_block(struct compiler *c, basicblock *block)
639{
640 assert(block != NULL);
641 c->u->u_curblock->b_next = block;
642 c->u->u_curblock = block;
643 return block;
644}
645
646/* Returns the offset of the next instruction in the current block's
647 b_instr array. Resizes the b_instr as necessary.
648 Returns -1 on failure.
649 */
650
651static int
652compiler_next_instr(struct compiler *c, basicblock *b)
653{
654 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000655 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000656 b->b_instr = (struct instr *)PyObject_Malloc(
657 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658 if (b->b_instr == NULL) {
659 PyErr_NoMemory();
660 return -1;
661 }
662 b->b_ialloc = DEFAULT_BLOCK_SIZE;
663 memset((char *)b->b_instr, 0,
664 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000665 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000667 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668 size_t oldsize, newsize;
669 oldsize = b->b_ialloc * sizeof(struct instr);
670 newsize = oldsize << 1;
671 if (newsize == 0) {
672 PyErr_NoMemory();
673 return -1;
674 }
675 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000676 tmp = (struct instr *)PyObject_Realloc(
Anthony Baxter7b782b62006-04-11 12:01:56 +0000677 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000678 if (tmp == NULL) {
679 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000680 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000681 }
682 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
684 }
685 return b->b_iused++;
686}
687
Jeremy Hylton12603c42006-04-01 16:18:02 +0000688/* Set the i_lineno member of the instruction at offse off if the
689 line number for the current expression/statement (?) has not
690 already been set. If it has been set, the call has no effect.
691
692 Every time a new node is b
693 */
694
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000695static void
696compiler_set_lineno(struct compiler *c, int off)
697{
698 basicblock *b;
699 if (c->u->u_lineno_set)
700 return;
701 c->u->u_lineno_set = true;
702 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000703 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704}
705
706static int
707opcode_stack_effect(int opcode, int oparg)
708{
709 switch (opcode) {
710 case POP_TOP:
711 return -1;
712 case ROT_TWO:
713 case ROT_THREE:
714 return 0;
715 case DUP_TOP:
716 return 1;
717 case ROT_FOUR:
718 return 0;
719
720 case UNARY_POSITIVE:
721 case UNARY_NEGATIVE:
722 case UNARY_NOT:
723 case UNARY_CONVERT:
724 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:
732 case BINARY_DIVIDE:
733 case BINARY_MODULO:
734 case BINARY_ADD:
735 case BINARY_SUBTRACT:
736 case BINARY_SUBSCR:
737 case BINARY_FLOOR_DIVIDE:
738 case BINARY_TRUE_DIVIDE:
739 return -1;
740 case INPLACE_FLOOR_DIVIDE:
741 case INPLACE_TRUE_DIVIDE:
742 return -1;
743
744 case SLICE+0:
745 return 1;
746 case SLICE+1:
747 return 0;
748 case SLICE+2:
749 return 0;
750 case SLICE+3:
751 return -1;
752
753 case STORE_SLICE+0:
754 return -2;
755 case STORE_SLICE+1:
756 return -3;
757 case STORE_SLICE+2:
758 return -3;
759 case STORE_SLICE+3:
760 return -4;
761
762 case DELETE_SLICE+0:
763 return -1;
764 case DELETE_SLICE+1:
765 return -2;
766 case DELETE_SLICE+2:
767 return -2;
768 case DELETE_SLICE+3:
769 return -3;
770
771 case INPLACE_ADD:
772 case INPLACE_SUBTRACT:
773 case INPLACE_MULTIPLY:
774 case INPLACE_DIVIDE:
775 case INPLACE_MODULO:
776 return -1;
777 case STORE_SUBSCR:
778 return -3;
779 case DELETE_SUBSCR:
780 return -2;
781
782 case BINARY_LSHIFT:
783 case BINARY_RSHIFT:
784 case BINARY_AND:
785 case BINARY_XOR:
786 case BINARY_OR:
787 return -1;
788 case INPLACE_POWER:
789 return -1;
790 case GET_ITER:
791 return 0;
792
793 case PRINT_EXPR:
794 return -1;
795 case PRINT_ITEM:
796 return -1;
797 case PRINT_NEWLINE:
798 return 0;
799 case PRINT_ITEM_TO:
800 return -2;
801 case PRINT_NEWLINE_TO:
802 return -1;
803 case INPLACE_LSHIFT:
804 case INPLACE_RSHIFT:
805 case INPLACE_AND:
806 case INPLACE_XOR:
807 case INPLACE_OR:
808 return -1;
809 case BREAK_LOOP:
810 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000811 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000812 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813 case LOAD_LOCALS:
814 return 1;
815 case RETURN_VALUE:
816 return -1;
817 case IMPORT_STAR:
818 return -1;
819 case EXEC_STMT:
820 return -3;
821 case YIELD_VALUE:
822 return 0;
823
824 case POP_BLOCK:
825 return 0;
826 case END_FINALLY:
827 return -1; /* or -2 or -3 if exception occurred */
828 case BUILD_CLASS:
829 return -2;
830
831 case STORE_NAME:
832 return -1;
833 case DELETE_NAME:
834 return 0;
835 case UNPACK_SEQUENCE:
836 return oparg-1;
837 case FOR_ITER:
838 return 1;
839
840 case STORE_ATTR:
841 return -2;
842 case DELETE_ATTR:
843 return -1;
844 case STORE_GLOBAL:
845 return -1;
846 case DELETE_GLOBAL:
847 return 0;
848 case DUP_TOPX:
849 return oparg;
850 case LOAD_CONST:
851 return 1;
852 case LOAD_NAME:
853 return 1;
854 case BUILD_TUPLE:
855 case BUILD_LIST:
856 return 1-oparg;
857 case BUILD_MAP:
858 return 1;
859 case LOAD_ATTR:
860 return 0;
861 case COMPARE_OP:
862 return -1;
863 case IMPORT_NAME:
864 return 0;
865 case IMPORT_FROM:
866 return 1;
867
868 case JUMP_FORWARD:
869 case JUMP_IF_FALSE:
870 case JUMP_IF_TRUE:
871 case JUMP_ABSOLUTE:
872 return 0;
873
874 case LOAD_GLOBAL:
875 return 1;
876
877 case CONTINUE_LOOP:
878 return 0;
879 case SETUP_LOOP:
880 return 0;
881 case SETUP_EXCEPT:
882 case SETUP_FINALLY:
883 return 3; /* actually pushed by an exception */
884
885 case LOAD_FAST:
886 return 1;
887 case STORE_FAST:
888 return -1;
889 case DELETE_FAST:
890 return 0;
891
892 case RAISE_VARARGS:
893 return -oparg;
894#define NARGS(o) (((o) % 256) + 2*((o) / 256))
895 case CALL_FUNCTION:
896 return -NARGS(oparg);
897 case CALL_FUNCTION_VAR:
898 case CALL_FUNCTION_KW:
899 return -NARGS(oparg)-1;
900 case CALL_FUNCTION_VAR_KW:
901 return -NARGS(oparg)-2;
902#undef NARGS
903 case MAKE_FUNCTION:
904 return -oparg;
905 case BUILD_SLICE:
906 if (oparg == 3)
907 return -2;
908 else
909 return -1;
910
911 case MAKE_CLOSURE:
912 return -oparg;
913 case LOAD_CLOSURE:
914 return 1;
915 case LOAD_DEREF:
916 return 1;
917 case STORE_DEREF:
918 return -1;
919 default:
920 fprintf(stderr, "opcode = %d\n", opcode);
921 Py_FatalError("opcode_stack_effect()");
922
923 }
924 return 0; /* not reachable */
925}
926
927/* Add an opcode with no argument.
928 Returns 0 on failure, 1 on success.
929*/
930
931static int
932compiler_addop(struct compiler *c, int opcode)
933{
934 basicblock *b;
935 struct instr *i;
936 int off;
937 off = compiler_next_instr(c, c->u->u_curblock);
938 if (off < 0)
939 return 0;
940 b = c->u->u_curblock;
941 i = &b->b_instr[off];
942 i->i_opcode = opcode;
943 i->i_hasarg = 0;
944 if (opcode == RETURN_VALUE)
945 b->b_return = 1;
946 compiler_set_lineno(c, off);
947 return 1;
948}
949
950static int
951compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
952{
953 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000954 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000955
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000956 /* necessary to make sure types aren't coerced (e.g., int and long) */
957 t = PyTuple_Pack(2, o, o->ob_type);
958 if (t == NULL)
959 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000960
961 v = PyDict_GetItem(dict, t);
962 if (!v) {
963 arg = PyDict_Size(dict);
964 v = PyInt_FromLong(arg);
965 if (!v) {
966 Py_DECREF(t);
967 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000968 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969 if (PyDict_SetItem(dict, t, v) < 0) {
970 Py_DECREF(t);
971 Py_DECREF(v);
972 return -1;
973 }
974 Py_DECREF(v);
975 }
976 else
977 arg = PyInt_AsLong(v);
978 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000979 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980}
981
982static int
983compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
984 PyObject *o)
985{
986 int arg = compiler_add_o(c, dict, o);
987 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000988 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989 return compiler_addop_i(c, opcode, arg);
990}
991
992static int
993compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000994 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000995{
996 int arg;
997 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
998 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000999 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000 arg = compiler_add_o(c, dict, mangled);
1001 Py_DECREF(mangled);
1002 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001003 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004 return compiler_addop_i(c, opcode, arg);
1005}
1006
1007/* Add an opcode with an integer argument.
1008 Returns 0 on failure, 1 on success.
1009*/
1010
1011static int
1012compiler_addop_i(struct compiler *c, int opcode, int oparg)
1013{
1014 struct instr *i;
1015 int off;
1016 off = compiler_next_instr(c, c->u->u_curblock);
1017 if (off < 0)
1018 return 0;
1019 i = &c->u->u_curblock->b_instr[off];
1020 i->i_opcode = opcode;
1021 i->i_oparg = oparg;
1022 i->i_hasarg = 1;
1023 compiler_set_lineno(c, off);
1024 return 1;
1025}
1026
1027static int
1028compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1029{
1030 struct instr *i;
1031 int off;
1032
1033 assert(b != NULL);
1034 off = compiler_next_instr(c, c->u->u_curblock);
1035 if (off < 0)
1036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037 i = &c->u->u_curblock->b_instr[off];
1038 i->i_opcode = opcode;
1039 i->i_target = b;
1040 i->i_hasarg = 1;
1041 if (absolute)
1042 i->i_jabs = 1;
1043 else
1044 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001045 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046 return 1;
1047}
1048
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001049/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1050 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051 it as the current block. NEXT_BLOCK() also creates an implicit jump
1052 from the current block to the new block.
1053*/
1054
1055/* XXX The returns inside these macros make it impossible to decref
1056 objects created in the local function.
1057*/
1058
1059
1060#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001061 if (compiler_use_new_block((C)) == NULL) \
1062 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063}
1064
1065#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001066 if (compiler_next_block((C)) == NULL) \
1067 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068}
1069
1070#define ADDOP(C, OP) { \
1071 if (!compiler_addop((C), (OP))) \
1072 return 0; \
1073}
1074
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001075#define ADDOP_IN_SCOPE(C, OP) { \
1076 if (!compiler_addop((C), (OP))) { \
1077 compiler_exit_scope(c); \
1078 return 0; \
1079 } \
1080}
1081
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082#define ADDOP_O(C, OP, O, TYPE) { \
1083 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1084 return 0; \
1085}
1086
1087#define ADDOP_NAME(C, OP, O, TYPE) { \
1088 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1089 return 0; \
1090}
1091
1092#define ADDOP_I(C, OP, O) { \
1093 if (!compiler_addop_i((C), (OP), (O))) \
1094 return 0; \
1095}
1096
1097#define ADDOP_JABS(C, OP, O) { \
1098 if (!compiler_addop_j((C), (OP), (O), 1)) \
1099 return 0; \
1100}
1101
1102#define ADDOP_JREL(C, OP, O) { \
1103 if (!compiler_addop_j((C), (OP), (O), 0)) \
1104 return 0; \
1105}
1106
1107/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1108 the ASDL name to synthesize the name of the C type and the visit function.
1109*/
1110
1111#define VISIT(C, TYPE, V) {\
1112 if (!compiler_visit_ ## TYPE((C), (V))) \
1113 return 0; \
1114}
1115
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001116#define VISIT_IN_SCOPE(C, TYPE, V) {\
1117 if (!compiler_visit_ ## TYPE((C), (V))) { \
1118 compiler_exit_scope(c); \
1119 return 0; \
1120 } \
1121}
1122
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123#define VISIT_SLICE(C, V, CTX) {\
1124 if (!compiler_visit_slice((C), (V), (CTX))) \
1125 return 0; \
1126}
1127
1128#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001129 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001131 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001132 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001133 if (!compiler_visit_ ## TYPE((C), elt)) \
1134 return 0; \
1135 } \
1136}
1137
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001138#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001139 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001140 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001141 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001142 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001143 if (!compiler_visit_ ## TYPE((C), elt)) { \
1144 compiler_exit_scope(c); \
1145 return 0; \
1146 } \
1147 } \
1148}
1149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150static int
1151compiler_isdocstring(stmt_ty s)
1152{
1153 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001154 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 return s->v.Expr.value->kind == Str_kind;
1156}
1157
1158/* Compile a sequence of statements, checking for a docstring. */
1159
1160static int
1161compiler_body(struct compiler *c, asdl_seq *stmts)
1162{
1163 int i = 0;
1164 stmt_ty st;
1165
1166 if (!asdl_seq_LEN(stmts))
1167 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001168 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 if (compiler_isdocstring(st)) {
1170 i = 1;
1171 VISIT(c, expr, st->v.Expr.value);
1172 if (!compiler_nameop(c, __doc__, Store))
1173 return 0;
1174 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001175 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001176 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 return 1;
1178}
1179
1180static PyCodeObject *
1181compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001182{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001183 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 static PyObject *module;
1186 if (!module) {
1187 module = PyString_FromString("<module>");
1188 if (!module)
1189 return NULL;
1190 }
Neal Norwitzed657552006-07-10 00:04:44 +00001191 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1192 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001193 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 switch (mod->kind) {
1195 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001196 if (!compiler_body(c, mod->v.Module.body)) {
1197 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 break;
1201 case Interactive_kind:
1202 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001203 VISIT_SEQ_IN_SCOPE(c, stmt,
1204 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 break;
1206 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001207 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001208 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 break;
1210 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001211 PyErr_SetString(PyExc_SystemError,
1212 "suite should not be possible");
1213 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001214 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001215 PyErr_Format(PyExc_SystemError,
1216 "module kind %d should not be possible",
1217 mod->kind);
1218 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220 co = assemble(c, addNone);
1221 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001222 return co;
1223}
1224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225/* The test for LOCAL must come before the test for FREE in order to
1226 handle classes where name is both local and free. The local var is
1227 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001228*/
1229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230static int
1231get_ref_type(struct compiler *c, PyObject *name)
1232{
1233 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001234 if (scope == 0) {
1235 char buf[350];
1236 PyOS_snprintf(buf, sizeof(buf),
1237 "unknown scope for %.100s in %.100s(%s) in %s\n"
1238 "symbols: %s\nlocals: %s\nglobals: %s\n",
1239 PyString_AS_STRING(name),
1240 PyString_AS_STRING(c->u->u_name),
1241 PyObject_REPR(c->u->u_ste->ste_id),
1242 c->c_filename,
1243 PyObject_REPR(c->u->u_ste->ste_symbols),
1244 PyObject_REPR(c->u->u_varnames),
1245 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 Py_FatalError(buf);
1248 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001249
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251}
1252
1253static int
1254compiler_lookup_arg(PyObject *dict, PyObject *name)
1255{
1256 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001257 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001261 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001263 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264 return PyInt_AS_LONG(v);
1265}
1266
1267static int
1268compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1269{
1270 int i, free = PyCode_GetNumFree(co);
1271 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1273 ADDOP_I(c, MAKE_FUNCTION, args);
1274 return 1;
1275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 for (i = 0; i < free; ++i) {
1277 /* Bypass com_addop_varname because it will generate
1278 LOAD_DEREF but LOAD_CLOSURE is needed.
1279 */
1280 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1281 int arg, reftype;
1282
1283 /* Special case: If a class contains a method with a
1284 free variable that has the same name as a method,
1285 the name will be considered free *and* local in the
1286 class. It should be handled by the closure, as
1287 well as by the normal name loookup logic.
1288 */
1289 reftype = get_ref_type(c, name);
1290 if (reftype == CELL)
1291 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1292 else /* (reftype == FREE) */
1293 arg = compiler_lookup_arg(c->u->u_freevars, name);
1294 if (arg == -1) {
1295 printf("lookup %s in %s %d %d\n"
1296 "freevars of %s: %s\n",
1297 PyObject_REPR(name),
1298 PyString_AS_STRING(c->u->u_name),
1299 reftype, arg,
1300 PyString_AS_STRING(co->co_name),
1301 PyObject_REPR(co->co_freevars));
1302 Py_FatalError("compiler_make_closure()");
1303 }
1304 ADDOP_I(c, LOAD_CLOSURE, arg);
1305 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001306 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001308 ADDOP_I(c, MAKE_CLOSURE, args);
1309 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
1312static int
1313compiler_decorators(struct compiler *c, asdl_seq* decos)
1314{
1315 int i;
1316
1317 if (!decos)
1318 return 1;
1319
1320 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001321 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322 }
1323 return 1;
1324}
1325
1326static int
1327compiler_arguments(struct compiler *c, arguments_ty args)
1328{
1329 int i;
1330 int n = asdl_seq_LEN(args->args);
1331 /* Correctly handle nested argument lists */
1332 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001333 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 if (arg->kind == Tuple_kind) {
1335 PyObject *id = PyString_FromFormat(".%d", i);
1336 if (id == NULL) {
1337 return 0;
1338 }
1339 if (!compiler_nameop(c, id, Load)) {
1340 Py_DECREF(id);
1341 return 0;
1342 }
1343 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001344 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 }
1346 }
1347 return 1;
1348}
1349
1350static int
1351compiler_function(struct compiler *c, stmt_ty s)
1352{
1353 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001354 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 arguments_ty args = s->v.FunctionDef.args;
1356 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001357 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358 int i, n, docstring;
1359
1360 assert(s->kind == FunctionDef_kind);
1361
1362 if (!compiler_decorators(c, decos))
1363 return 0;
1364 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001365 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1367 s->lineno))
1368 return 0;
1369
Anthony Baxter7b782b62006-04-11 12:01:56 +00001370 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001371 docstring = compiler_isdocstring(st);
1372 if (docstring)
1373 first_const = st->v.Expr.value->v.Str.s;
1374 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001375 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001376 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001377 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001379 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 compiler_arguments(c, args);
1381
1382 c->u->u_argcount = asdl_seq_LEN(args->args);
1383 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001384 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001386 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1387 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388 }
1389 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001390 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 if (co == NULL)
1392 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001394 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001395 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396
1397 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1398 ADDOP_I(c, CALL_FUNCTION, 1);
1399 }
1400
1401 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1402}
1403
1404static int
1405compiler_class(struct compiler *c, stmt_ty s)
1406{
1407 int n;
1408 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001409 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410 /* push class name on stack, needed by BUILD_CLASS */
1411 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1412 /* push the tuple of base classes on the stack */
1413 n = asdl_seq_LEN(s->v.ClassDef.bases);
1414 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001415 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416 ADDOP_I(c, BUILD_TUPLE, n);
1417 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1418 s->lineno))
1419 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001420 c->u->u_private = s->v.ClassDef.name;
1421 Py_INCREF(c->u->u_private);
1422 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423 if (!str || !compiler_nameop(c, str, Load)) {
1424 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001425 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001427 }
1428
1429 Py_DECREF(str);
1430 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 if (!str || !compiler_nameop(c, str, Store)) {
1432 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001433 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001435 }
1436 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001438 if (!compiler_body(c, s->v.ClassDef.body)) {
1439 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001441 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001443 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1444 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001446 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447 if (co == NULL)
1448 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001450 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001451 Py_DECREF(co);
1452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 ADDOP_I(c, CALL_FUNCTION, 0);
1454 ADDOP(c, BUILD_CLASS);
1455 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1456 return 0;
1457 return 1;
1458}
1459
1460static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001461compiler_ifexp(struct compiler *c, expr_ty e)
1462{
1463 basicblock *end, *next;
1464
1465 assert(e->kind == IfExp_kind);
1466 end = compiler_new_block(c);
1467 if (end == NULL)
1468 return 0;
1469 next = compiler_new_block(c);
1470 if (next == NULL)
1471 return 0;
1472 VISIT(c, expr, e->v.IfExp.test);
1473 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1474 ADDOP(c, POP_TOP);
1475 VISIT(c, expr, e->v.IfExp.body);
1476 ADDOP_JREL(c, JUMP_FORWARD, end);
1477 compiler_use_next_block(c, next);
1478 ADDOP(c, POP_TOP);
1479 VISIT(c, expr, e->v.IfExp.orelse);
1480 compiler_use_next_block(c, end);
1481 return 1;
1482}
1483
1484static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485compiler_lambda(struct compiler *c, expr_ty e)
1486{
1487 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001488 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489 arguments_ty args = e->v.Lambda.args;
1490 assert(e->kind == Lambda_kind);
1491
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001492 if (!name) {
1493 name = PyString_InternFromString("<lambda>");
1494 if (!name)
1495 return 0;
1496 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497
1498 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001499 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1501 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001502
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001503 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504 compiler_arguments(c, args);
1505
1506 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001507 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1508 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001510 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511 if (co == NULL)
1512 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001514 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001515 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516
1517 return 1;
1518}
1519
1520static int
1521compiler_print(struct compiler *c, stmt_ty s)
1522{
1523 int i, n;
1524 bool dest;
1525
1526 assert(s->kind == Print_kind);
1527 n = asdl_seq_LEN(s->v.Print.values);
1528 dest = false;
1529 if (s->v.Print.dest) {
1530 VISIT(c, expr, s->v.Print.dest);
1531 dest = true;
1532 }
1533 for (i = 0; i < n; i++) {
1534 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1535 if (dest) {
1536 ADDOP(c, DUP_TOP);
1537 VISIT(c, expr, e);
1538 ADDOP(c, ROT_TWO);
1539 ADDOP(c, PRINT_ITEM_TO);
1540 }
1541 else {
1542 VISIT(c, expr, e);
1543 ADDOP(c, PRINT_ITEM);
1544 }
1545 }
1546 if (s->v.Print.nl) {
1547 if (dest)
1548 ADDOP(c, PRINT_NEWLINE_TO)
1549 else
1550 ADDOP(c, PRINT_NEWLINE)
1551 }
1552 else if (dest)
1553 ADDOP(c, POP_TOP);
1554 return 1;
1555}
1556
1557static int
1558compiler_if(struct compiler *c, stmt_ty s)
1559{
1560 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001561 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562 assert(s->kind == If_kind);
1563 end = compiler_new_block(c);
1564 if (end == NULL)
1565 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001566 next = compiler_new_block(c);
1567 if (next == NULL)
1568 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001569
1570 constant = expr_constant(s->v.If.test);
1571 /* constant = 0: "if 0"
1572 * constant = 1: "if 1", "if 2", ...
1573 * constant = -1: rest */
1574 if (constant == 0) {
1575 if (s->v.If.orelse)
1576 VISIT_SEQ(c, stmt, s->v.If.orelse);
1577 } else if (constant == 1) {
1578 VISIT_SEQ(c, stmt, s->v.If.body);
1579 } else {
1580 VISIT(c, expr, s->v.If.test);
1581 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1582 ADDOP(c, POP_TOP);
1583 VISIT_SEQ(c, stmt, s->v.If.body);
1584 ADDOP_JREL(c, JUMP_FORWARD, end);
1585 compiler_use_next_block(c, next);
1586 ADDOP(c, POP_TOP);
1587 if (s->v.If.orelse)
1588 VISIT_SEQ(c, stmt, s->v.If.orelse);
1589 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590 compiler_use_next_block(c, end);
1591 return 1;
1592}
1593
1594static int
1595compiler_for(struct compiler *c, stmt_ty s)
1596{
1597 basicblock *start, *cleanup, *end;
1598
1599 start = compiler_new_block(c);
1600 cleanup = compiler_new_block(c);
1601 end = compiler_new_block(c);
1602 if (start == NULL || end == NULL || cleanup == NULL)
1603 return 0;
1604 ADDOP_JREL(c, SETUP_LOOP, end);
1605 if (!compiler_push_fblock(c, LOOP, start))
1606 return 0;
1607 VISIT(c, expr, s->v.For.iter);
1608 ADDOP(c, GET_ITER);
1609 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001610 /* XXX(nnorwitz): is there a better way to handle this?
1611 for loops are special, we want to be able to trace them
1612 each time around, so we need to set an extra line number. */
1613 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001614 ADDOP_JREL(c, FOR_ITER, cleanup);
1615 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001616 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001617 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1618 compiler_use_next_block(c, cleanup);
1619 ADDOP(c, POP_BLOCK);
1620 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001621 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622 compiler_use_next_block(c, end);
1623 return 1;
1624}
1625
1626static int
1627compiler_while(struct compiler *c, stmt_ty s)
1628{
1629 basicblock *loop, *orelse, *end, *anchor = NULL;
1630 int constant = expr_constant(s->v.While.test);
1631
1632 if (constant == 0)
1633 return 1;
1634 loop = compiler_new_block(c);
1635 end = compiler_new_block(c);
1636 if (constant == -1) {
1637 anchor = compiler_new_block(c);
1638 if (anchor == NULL)
1639 return 0;
1640 }
1641 if (loop == NULL || end == NULL)
1642 return 0;
1643 if (s->v.While.orelse) {
1644 orelse = compiler_new_block(c);
1645 if (orelse == NULL)
1646 return 0;
1647 }
1648 else
1649 orelse = NULL;
1650
1651 ADDOP_JREL(c, SETUP_LOOP, end);
1652 compiler_use_next_block(c, loop);
1653 if (!compiler_push_fblock(c, LOOP, loop))
1654 return 0;
1655 if (constant == -1) {
1656 VISIT(c, expr, s->v.While.test);
1657 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1658 ADDOP(c, POP_TOP);
1659 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001660 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001661 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1662
1663 /* XXX should the two POP instructions be in a separate block
1664 if there is no else clause ?
1665 */
1666
1667 if (constant == -1) {
1668 compiler_use_next_block(c, anchor);
1669 ADDOP(c, POP_TOP);
1670 ADDOP(c, POP_BLOCK);
1671 }
1672 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001673 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001674 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 compiler_use_next_block(c, end);
1676
1677 return 1;
1678}
1679
1680static int
1681compiler_continue(struct compiler *c)
1682{
1683 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1684 int i;
1685
1686 if (!c->u->u_nfblocks)
1687 return compiler_error(c, LOOP_ERROR_MSG);
1688 i = c->u->u_nfblocks - 1;
1689 switch (c->u->u_fblock[i].fb_type) {
1690 case LOOP:
1691 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1692 break;
1693 case EXCEPT:
1694 case FINALLY_TRY:
1695 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1696 ;
1697 if (i == -1)
1698 return compiler_error(c, LOOP_ERROR_MSG);
1699 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1700 break;
1701 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001702 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703 "'continue' not supported inside 'finally' clause");
1704 }
1705
1706 return 1;
1707}
1708
1709/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1710
1711 SETUP_FINALLY L
1712 <code for body>
1713 POP_BLOCK
1714 LOAD_CONST <None>
1715 L: <code for finalbody>
1716 END_FINALLY
1717
1718 The special instructions use the block stack. Each block
1719 stack entry contains the instruction that created it (here
1720 SETUP_FINALLY), the level of the value stack at the time the
1721 block stack entry was created, and a label (here L).
1722
1723 SETUP_FINALLY:
1724 Pushes the current value stack level and the label
1725 onto the block stack.
1726 POP_BLOCK:
1727 Pops en entry from the block stack, and pops the value
1728 stack until its level is the same as indicated on the
1729 block stack. (The label is ignored.)
1730 END_FINALLY:
1731 Pops a variable number of entries from the *value* stack
1732 and re-raises the exception they specify. The number of
1733 entries popped depends on the (pseudo) exception type.
1734
1735 The block stack is unwound when an exception is raised:
1736 when a SETUP_FINALLY entry is found, the exception is pushed
1737 onto the value stack (and the exception condition is cleared),
1738 and the interpreter jumps to the label gotten from the block
1739 stack.
1740*/
1741
1742static int
1743compiler_try_finally(struct compiler *c, stmt_ty s)
1744{
1745 basicblock *body, *end;
1746 body = compiler_new_block(c);
1747 end = compiler_new_block(c);
1748 if (body == NULL || end == NULL)
1749 return 0;
1750
1751 ADDOP_JREL(c, SETUP_FINALLY, end);
1752 compiler_use_next_block(c, body);
1753 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1754 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001755 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001756 ADDOP(c, POP_BLOCK);
1757 compiler_pop_fblock(c, FINALLY_TRY, body);
1758
1759 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1760 compiler_use_next_block(c, end);
1761 if (!compiler_push_fblock(c, FINALLY_END, end))
1762 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001763 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764 ADDOP(c, END_FINALLY);
1765 compiler_pop_fblock(c, FINALLY_END, end);
1766
1767 return 1;
1768}
1769
1770/*
1771 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1772 (The contents of the value stack is shown in [], with the top
1773 at the right; 'tb' is trace-back info, 'val' the exception's
1774 associated value, and 'exc' the exception.)
1775
1776 Value stack Label Instruction Argument
1777 [] SETUP_EXCEPT L1
1778 [] <code for S>
1779 [] POP_BLOCK
1780 [] JUMP_FORWARD L0
1781
1782 [tb, val, exc] L1: DUP )
1783 [tb, val, exc, exc] <evaluate E1> )
1784 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1785 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1786 [tb, val, exc, 1] POP )
1787 [tb, val, exc] POP
1788 [tb, val] <assign to V1> (or POP if no V1)
1789 [tb] POP
1790 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001791 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792
1793 [tb, val, exc, 0] L2: POP
1794 [tb, val, exc] DUP
1795 .............................etc.......................
1796
1797 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001798 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799
1800 [] L0: <next statement>
1801
1802 Of course, parts are not generated if Vi or Ei is not present.
1803*/
1804static int
1805compiler_try_except(struct compiler *c, stmt_ty s)
1806{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001807 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 int i, n;
1809
1810 body = compiler_new_block(c);
1811 except = compiler_new_block(c);
1812 orelse = compiler_new_block(c);
1813 end = compiler_new_block(c);
1814 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1815 return 0;
1816 ADDOP_JREL(c, SETUP_EXCEPT, except);
1817 compiler_use_next_block(c, body);
1818 if (!compiler_push_fblock(c, EXCEPT, body))
1819 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001820 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821 ADDOP(c, POP_BLOCK);
1822 compiler_pop_fblock(c, EXCEPT, body);
1823 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1824 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1825 compiler_use_next_block(c, except);
1826 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001827 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828 s->v.TryExcept.handlers, i);
1829 if (!handler->type && i < n-1)
1830 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00001831 c->u->u_lineno_set = false;
1832 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833 except = compiler_new_block(c);
1834 if (except == NULL)
1835 return 0;
1836 if (handler->type) {
1837 ADDOP(c, DUP_TOP);
1838 VISIT(c, expr, handler->type);
1839 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1840 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1841 ADDOP(c, POP_TOP);
1842 }
1843 ADDOP(c, POP_TOP);
1844 if (handler->name) {
1845 VISIT(c, expr, handler->name);
1846 }
1847 else {
1848 ADDOP(c, POP_TOP);
1849 }
1850 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001851 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852 ADDOP_JREL(c, JUMP_FORWARD, end);
1853 compiler_use_next_block(c, except);
1854 if (handler->type)
1855 ADDOP(c, POP_TOP);
1856 }
1857 ADDOP(c, END_FINALLY);
1858 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001859 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860 compiler_use_next_block(c, end);
1861 return 1;
1862}
1863
1864static int
1865compiler_import_as(struct compiler *c, identifier name, identifier asname)
1866{
1867 /* The IMPORT_NAME opcode was already generated. This function
1868 merely needs to bind the result to a name.
1869
1870 If there is a dot in name, we need to split it and emit a
1871 LOAD_ATTR for each name.
1872 */
1873 const char *src = PyString_AS_STRING(name);
1874 const char *dot = strchr(src, '.');
1875 if (dot) {
1876 /* Consume the base module name to get the first attribute */
1877 src = dot + 1;
1878 while (dot) {
1879 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001880 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001882 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001884 if (!attr)
1885 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001887 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888 src = dot + 1;
1889 }
1890 }
1891 return compiler_nameop(c, asname, Store);
1892}
1893
1894static int
1895compiler_import(struct compiler *c, stmt_ty s)
1896{
1897 /* The Import node stores a module name like a.b.c as a single
1898 string. This is convenient for all cases except
1899 import a.b.c as d
1900 where we need to parse that string to extract the individual
1901 module names.
1902 XXX Perhaps change the representation to make this case simpler?
1903 */
1904 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001905
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001907 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001909 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910
Neal Norwitzcbce2802006-04-03 06:26:32 +00001911 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001912 level = PyInt_FromLong(0);
1913 else
1914 level = PyInt_FromLong(-1);
1915
1916 if (level == NULL)
1917 return 0;
1918
1919 ADDOP_O(c, LOAD_CONST, level, consts);
1920 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1922 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1923
1924 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001925 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001926 if (!r)
1927 return r;
1928 }
1929 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930 identifier tmp = alias->name;
1931 const char *base = PyString_AS_STRING(alias->name);
1932 char *dot = strchr(base, '.');
1933 if (dot)
1934 tmp = PyString_FromStringAndSize(base,
1935 dot - base);
1936 r = compiler_nameop(c, tmp, Store);
1937 if (dot) {
1938 Py_DECREF(tmp);
1939 }
1940 if (!r)
1941 return r;
1942 }
1943 }
1944 return 1;
1945}
1946
1947static int
1948compiler_from_import(struct compiler *c, stmt_ty s)
1949{
1950 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951
1952 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001953 PyObject *level;
1954
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955 if (!names)
1956 return 0;
1957
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001958 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001959 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001960 level = PyInt_FromLong(-1);
1961 else
1962 level = PyInt_FromLong(s->v.ImportFrom.level);
1963
1964 if (!level) {
1965 Py_DECREF(names);
1966 return 0;
1967 }
1968
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969 /* build up the names */
1970 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001971 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972 Py_INCREF(alias->name);
1973 PyTuple_SET_ITEM(names, i, alias->name);
1974 }
1975
1976 if (s->lineno > c->c_future->ff_lineno) {
1977 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1978 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001979 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 Py_DECREF(names);
1981 return compiler_error(c,
1982 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001983 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984
1985 }
1986 }
1987
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001988 ADDOP_O(c, LOAD_CONST, level, consts);
1989 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001991 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1993 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001994 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995 identifier store_name;
1996
1997 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1998 assert(n == 1);
1999 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002000 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 }
2002
2003 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2004 store_name = alias->name;
2005 if (alias->asname)
2006 store_name = alias->asname;
2007
2008 if (!compiler_nameop(c, store_name, Store)) {
2009 Py_DECREF(names);
2010 return 0;
2011 }
2012 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002013 /* remove imported module */
2014 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 return 1;
2016}
2017
2018static int
2019compiler_assert(struct compiler *c, stmt_ty s)
2020{
2021 static PyObject *assertion_error = NULL;
2022 basicblock *end;
2023
2024 if (Py_OptimizeFlag)
2025 return 1;
2026 if (assertion_error == NULL) {
2027 assertion_error = PyString_FromString("AssertionError");
2028 if (assertion_error == NULL)
2029 return 0;
2030 }
2031 VISIT(c, expr, s->v.Assert.test);
2032 end = compiler_new_block(c);
2033 if (end == NULL)
2034 return 0;
2035 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2036 ADDOP(c, POP_TOP);
2037 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2038 if (s->v.Assert.msg) {
2039 VISIT(c, expr, s->v.Assert.msg);
2040 ADDOP_I(c, RAISE_VARARGS, 2);
2041 }
2042 else {
2043 ADDOP_I(c, RAISE_VARARGS, 1);
2044 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002045 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002046 ADDOP(c, POP_TOP);
2047 return 1;
2048}
2049
2050static int
2051compiler_visit_stmt(struct compiler *c, stmt_ty s)
2052{
2053 int i, n;
2054
Jeremy Hylton12603c42006-04-01 16:18:02 +00002055 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056 c->u->u_lineno = s->lineno;
2057 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002058
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002060 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002062 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002064 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 if (c->u->u_ste->ste_type != FunctionBlock)
2066 return compiler_error(c, "'return' outside function");
2067 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 VISIT(c, expr, s->v.Return.value);
2069 }
2070 else
2071 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2072 ADDOP(c, RETURN_VALUE);
2073 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002074 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002075 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002077 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 n = asdl_seq_LEN(s->v.Assign.targets);
2079 VISIT(c, expr, s->v.Assign.value);
2080 for (i = 0; i < n; i++) {
2081 if (i < n - 1)
2082 ADDOP(c, DUP_TOP);
2083 VISIT(c, expr,
2084 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2085 }
2086 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002087 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002091 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002093 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 n = 0;
2099 if (s->v.Raise.type) {
2100 VISIT(c, expr, s->v.Raise.type);
2101 n++;
2102 if (s->v.Raise.inst) {
2103 VISIT(c, expr, s->v.Raise.inst);
2104 n++;
2105 if (s->v.Raise.tback) {
2106 VISIT(c, expr, s->v.Raise.tback);
2107 n++;
2108 }
2109 }
2110 }
2111 ADDOP_I(c, RAISE_VARARGS, n);
2112 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002113 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002115 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002117 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002119 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002121 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002123 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 VISIT(c, expr, s->v.Exec.body);
2125 if (s->v.Exec.globals) {
2126 VISIT(c, expr, s->v.Exec.globals);
2127 if (s->v.Exec.locals) {
2128 VISIT(c, expr, s->v.Exec.locals);
2129 } else {
2130 ADDOP(c, DUP_TOP);
2131 }
2132 } else {
2133 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2134 ADDOP(c, DUP_TOP);
2135 }
2136 ADDOP(c, EXEC_STMT);
2137 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002138 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002140 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002142 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143 ADDOP(c, PRINT_EXPR);
2144 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002145 else if (s->v.Expr.value->kind != Str_kind &&
2146 s->v.Expr.value->kind != Num_kind) {
2147 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148 ADDOP(c, POP_TOP);
2149 }
2150 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002151 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002153 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 if (!c->u->u_nfblocks)
2155 return compiler_error(c, "'break' outside loop");
2156 ADDOP(c, BREAK_LOOP);
2157 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002158 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002160 case With_kind:
2161 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162 }
2163 return 1;
2164}
2165
2166static int
2167unaryop(unaryop_ty op)
2168{
2169 switch (op) {
2170 case Invert:
2171 return UNARY_INVERT;
2172 case Not:
2173 return UNARY_NOT;
2174 case UAdd:
2175 return UNARY_POSITIVE;
2176 case USub:
2177 return UNARY_NEGATIVE;
2178 }
2179 return 0;
2180}
2181
2182static int
2183binop(struct compiler *c, operator_ty op)
2184{
2185 switch (op) {
2186 case Add:
2187 return BINARY_ADD;
2188 case Sub:
2189 return BINARY_SUBTRACT;
2190 case Mult:
2191 return BINARY_MULTIPLY;
2192 case Div:
2193 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2194 return BINARY_TRUE_DIVIDE;
2195 else
2196 return BINARY_DIVIDE;
2197 case Mod:
2198 return BINARY_MODULO;
2199 case Pow:
2200 return BINARY_POWER;
2201 case LShift:
2202 return BINARY_LSHIFT;
2203 case RShift:
2204 return BINARY_RSHIFT;
2205 case BitOr:
2206 return BINARY_OR;
2207 case BitXor:
2208 return BINARY_XOR;
2209 case BitAnd:
2210 return BINARY_AND;
2211 case FloorDiv:
2212 return BINARY_FLOOR_DIVIDE;
2213 }
2214 return 0;
2215}
2216
2217static int
2218cmpop(cmpop_ty op)
2219{
2220 switch (op) {
2221 case Eq:
2222 return PyCmp_EQ;
2223 case NotEq:
2224 return PyCmp_NE;
2225 case Lt:
2226 return PyCmp_LT;
2227 case LtE:
2228 return PyCmp_LE;
2229 case Gt:
2230 return PyCmp_GT;
2231 case GtE:
2232 return PyCmp_GE;
2233 case Is:
2234 return PyCmp_IS;
2235 case IsNot:
2236 return PyCmp_IS_NOT;
2237 case In:
2238 return PyCmp_IN;
2239 case NotIn:
2240 return PyCmp_NOT_IN;
2241 }
2242 return PyCmp_BAD;
2243}
2244
2245static int
2246inplace_binop(struct compiler *c, operator_ty op)
2247{
2248 switch (op) {
2249 case Add:
2250 return INPLACE_ADD;
2251 case Sub:
2252 return INPLACE_SUBTRACT;
2253 case Mult:
2254 return INPLACE_MULTIPLY;
2255 case Div:
2256 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2257 return INPLACE_TRUE_DIVIDE;
2258 else
2259 return INPLACE_DIVIDE;
2260 case Mod:
2261 return INPLACE_MODULO;
2262 case Pow:
2263 return INPLACE_POWER;
2264 case LShift:
2265 return INPLACE_LSHIFT;
2266 case RShift:
2267 return INPLACE_RSHIFT;
2268 case BitOr:
2269 return INPLACE_OR;
2270 case BitXor:
2271 return INPLACE_XOR;
2272 case BitAnd:
2273 return INPLACE_AND;
2274 case FloorDiv:
2275 return INPLACE_FLOOR_DIVIDE;
2276 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002277 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002278 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 return 0;
2280}
2281
2282static int
2283compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2284{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002285 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2287
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002288 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002289 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 /* XXX AugStore isn't used anywhere! */
2291
2292 /* First check for assignment to __debug__. Param? */
2293 if ((ctx == Store || ctx == AugStore || ctx == Del)
2294 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2295 return compiler_error(c, "can not assign to __debug__");
2296 }
2297
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002298 mangled = _Py_Mangle(c->u->u_private, name);
2299 if (!mangled)
2300 return 0;
2301
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 op = 0;
2303 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002304 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 switch (scope) {
2306 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002307 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308 optype = OP_DEREF;
2309 break;
2310 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002311 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 optype = OP_DEREF;
2313 break;
2314 case LOCAL:
2315 if (c->u->u_ste->ste_type == FunctionBlock)
2316 optype = OP_FAST;
2317 break;
2318 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002319 if (c->u->u_ste->ste_type == FunctionBlock &&
2320 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 optype = OP_GLOBAL;
2322 break;
2323 case GLOBAL_EXPLICIT:
2324 optype = OP_GLOBAL;
2325 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002326 default:
2327 /* scope can be 0 */
2328 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 }
2330
2331 /* XXX Leave assert here, but handle __doc__ and the like better */
2332 assert(scope || PyString_AS_STRING(name)[0] == '_');
2333
2334 switch (optype) {
2335 case OP_DEREF:
2336 switch (ctx) {
2337 case Load: op = LOAD_DEREF; break;
2338 case Store: op = STORE_DEREF; break;
2339 case AugLoad:
2340 case AugStore:
2341 break;
2342 case Del:
2343 PyErr_Format(PyExc_SyntaxError,
2344 "can not delete variable '%s' referenced "
2345 "in nested scope",
2346 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002347 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002350 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002351 PyErr_SetString(PyExc_SystemError,
2352 "param invalid for deref variable");
2353 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354 }
2355 break;
2356 case OP_FAST:
2357 switch (ctx) {
2358 case Load: op = LOAD_FAST; break;
2359 case Store: op = STORE_FAST; break;
2360 case Del: op = DELETE_FAST; break;
2361 case AugLoad:
2362 case AugStore:
2363 break;
2364 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002365 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002366 PyErr_SetString(PyExc_SystemError,
2367 "param invalid for local variable");
2368 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002370 ADDOP_O(c, op, mangled, varnames);
2371 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372 return 1;
2373 case OP_GLOBAL:
2374 switch (ctx) {
2375 case Load: op = LOAD_GLOBAL; break;
2376 case Store: op = STORE_GLOBAL; break;
2377 case Del: op = DELETE_GLOBAL; break;
2378 case AugLoad:
2379 case AugStore:
2380 break;
2381 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002382 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002383 PyErr_SetString(PyExc_SystemError,
2384 "param invalid for global variable");
2385 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386 }
2387 break;
2388 case OP_NAME:
2389 switch (ctx) {
2390 case Load: op = LOAD_NAME; break;
2391 case Store: op = STORE_NAME; break;
2392 case Del: op = DELETE_NAME; break;
2393 case AugLoad:
2394 case AugStore:
2395 break;
2396 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002397 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002398 PyErr_SetString(PyExc_SystemError,
2399 "param invalid for name variable");
2400 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401 }
2402 break;
2403 }
2404
2405 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002406 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002407 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002408 if (arg < 0)
2409 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002410 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411}
2412
2413static int
2414compiler_boolop(struct compiler *c, expr_ty e)
2415{
2416 basicblock *end;
2417 int jumpi, i, n;
2418 asdl_seq *s;
2419
2420 assert(e->kind == BoolOp_kind);
2421 if (e->v.BoolOp.op == And)
2422 jumpi = JUMP_IF_FALSE;
2423 else
2424 jumpi = JUMP_IF_TRUE;
2425 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002426 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427 return 0;
2428 s = e->v.BoolOp.values;
2429 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002430 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002432 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433 ADDOP_JREL(c, jumpi, end);
2434 ADDOP(c, POP_TOP)
2435 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002436 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 compiler_use_next_block(c, end);
2438 return 1;
2439}
2440
2441static int
2442compiler_list(struct compiler *c, expr_ty e)
2443{
2444 int n = asdl_seq_LEN(e->v.List.elts);
2445 if (e->v.List.ctx == Store) {
2446 ADDOP_I(c, UNPACK_SEQUENCE, n);
2447 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002448 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002449 if (e->v.List.ctx == Load) {
2450 ADDOP_I(c, BUILD_LIST, n);
2451 }
2452 return 1;
2453}
2454
2455static int
2456compiler_tuple(struct compiler *c, expr_ty e)
2457{
2458 int n = asdl_seq_LEN(e->v.Tuple.elts);
2459 if (e->v.Tuple.ctx == Store) {
2460 ADDOP_I(c, UNPACK_SEQUENCE, n);
2461 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002462 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 if (e->v.Tuple.ctx == Load) {
2464 ADDOP_I(c, BUILD_TUPLE, n);
2465 }
2466 return 1;
2467}
2468
2469static int
2470compiler_compare(struct compiler *c, expr_ty e)
2471{
2472 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002473 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474
2475 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2476 VISIT(c, expr, e->v.Compare.left);
2477 n = asdl_seq_LEN(e->v.Compare.ops);
2478 assert(n > 0);
2479 if (n > 1) {
2480 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002481 if (cleanup == NULL)
2482 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002483 VISIT(c, expr,
2484 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 }
2486 for (i = 1; i < n; i++) {
2487 ADDOP(c, DUP_TOP);
2488 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002490 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00002491 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002492 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2493 NEXT_BLOCK(c);
2494 ADDOP(c, POP_TOP);
2495 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002496 VISIT(c, expr,
2497 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002499 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002501 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002502 if (n > 1) {
2503 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002504 if (end == NULL)
2505 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506 ADDOP_JREL(c, JUMP_FORWARD, end);
2507 compiler_use_next_block(c, cleanup);
2508 ADDOP(c, ROT_TWO);
2509 ADDOP(c, POP_TOP);
2510 compiler_use_next_block(c, end);
2511 }
2512 return 1;
2513}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00002514#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515
2516static int
2517compiler_call(struct compiler *c, expr_ty e)
2518{
2519 int n, code = 0;
2520
2521 VISIT(c, expr, e->v.Call.func);
2522 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002523 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002525 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2527 }
2528 if (e->v.Call.starargs) {
2529 VISIT(c, expr, e->v.Call.starargs);
2530 code |= 1;
2531 }
2532 if (e->v.Call.kwargs) {
2533 VISIT(c, expr, e->v.Call.kwargs);
2534 code |= 2;
2535 }
2536 switch (code) {
2537 case 0:
2538 ADDOP_I(c, CALL_FUNCTION, n);
2539 break;
2540 case 1:
2541 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2542 break;
2543 case 2:
2544 ADDOP_I(c, CALL_FUNCTION_KW, n);
2545 break;
2546 case 3:
2547 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2548 break;
2549 }
2550 return 1;
2551}
2552
2553static int
2554compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002555 asdl_seq *generators, int gen_index,
2556 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557{
2558 /* generate code for the iterator, then each of the ifs,
2559 and then write to the element */
2560
2561 comprehension_ty l;
2562 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002563 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564
2565 start = compiler_new_block(c);
2566 skip = compiler_new_block(c);
2567 if_cleanup = compiler_new_block(c);
2568 anchor = compiler_new_block(c);
2569
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002570 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2571 anchor == NULL)
2572 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573
Anthony Baxter7b782b62006-04-11 12:01:56 +00002574 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575 VISIT(c, expr, l->iter);
2576 ADDOP(c, GET_ITER);
2577 compiler_use_next_block(c, start);
2578 ADDOP_JREL(c, FOR_ITER, anchor);
2579 NEXT_BLOCK(c);
2580 VISIT(c, expr, l->target);
2581
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002582 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583 n = asdl_seq_LEN(l->ifs);
2584 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002585 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 VISIT(c, expr, e);
2587 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2588 NEXT_BLOCK(c);
2589 ADDOP(c, POP_TOP);
2590 }
2591
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002592 if (++gen_index < asdl_seq_LEN(generators))
2593 if (!compiler_listcomp_generator(c, tmpname,
2594 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002597 /* only append after the last for generator */
2598 if (gen_index >= asdl_seq_LEN(generators)) {
2599 if (!compiler_nameop(c, tmpname, Load))
2600 return 0;
2601 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002602 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002603
2604 compiler_use_next_block(c, skip);
2605 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 for (i = 0; i < n; i++) {
2607 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002608 if (i == 0)
2609 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610 ADDOP(c, POP_TOP);
2611 }
2612 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2613 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002616 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 return 0;
2618
2619 return 1;
2620}
2621
2622static int
2623compiler_listcomp(struct compiler *c, expr_ty e)
2624{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002626 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 static identifier append;
2628 asdl_seq *generators = e->v.ListComp.generators;
2629
2630 assert(e->kind == ListComp_kind);
2631 if (!append) {
2632 append = PyString_InternFromString("append");
2633 if (!append)
2634 return 0;
2635 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002636 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637 if (!tmp)
2638 return 0;
2639 ADDOP_I(c, BUILD_LIST, 0);
2640 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002642 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2643 e->v.ListComp.elt);
2644 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 return rc;
2646}
2647
2648static int
2649compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002650 asdl_seq *generators, int gen_index,
2651 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652{
2653 /* generate code for the iterator, then each of the ifs,
2654 and then write to the element */
2655
2656 comprehension_ty ge;
2657 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002658 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659
2660 start = compiler_new_block(c);
2661 skip = compiler_new_block(c);
2662 if_cleanup = compiler_new_block(c);
2663 anchor = compiler_new_block(c);
2664 end = compiler_new_block(c);
2665
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002666 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667 anchor == NULL || end == NULL)
2668 return 0;
2669
Anthony Baxter7b782b62006-04-11 12:01:56 +00002670 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671 ADDOP_JREL(c, SETUP_LOOP, end);
2672 if (!compiler_push_fblock(c, LOOP, start))
2673 return 0;
2674
2675 if (gen_index == 0) {
2676 /* Receive outermost iter as an implicit argument */
2677 c->u->u_argcount = 1;
2678 ADDOP_I(c, LOAD_FAST, 0);
2679 }
2680 else {
2681 /* Sub-iter - calculate on the fly */
2682 VISIT(c, expr, ge->iter);
2683 ADDOP(c, GET_ITER);
2684 }
2685 compiler_use_next_block(c, start);
2686 ADDOP_JREL(c, FOR_ITER, anchor);
2687 NEXT_BLOCK(c);
2688 VISIT(c, expr, ge->target);
2689
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002690 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691 n = asdl_seq_LEN(ge->ifs);
2692 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002693 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 VISIT(c, expr, e);
2695 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2696 NEXT_BLOCK(c);
2697 ADDOP(c, POP_TOP);
2698 }
2699
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2702 return 0;
2703
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 /* only append after the last 'for' generator */
2705 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 VISIT(c, expr, elt);
2707 ADDOP(c, YIELD_VALUE);
2708 ADDOP(c, POP_TOP);
2709
2710 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002711 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 for (i = 0; i < n; i++) {
2713 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002714 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 compiler_use_next_block(c, if_cleanup);
2716
2717 ADDOP(c, POP_TOP);
2718 }
2719 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2720 compiler_use_next_block(c, anchor);
2721 ADDOP(c, POP_BLOCK);
2722 compiler_pop_fblock(c, LOOP, start);
2723 compiler_use_next_block(c, end);
2724
2725 return 1;
2726}
2727
2728static int
2729compiler_genexp(struct compiler *c, expr_ty e)
2730{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002731 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 PyCodeObject *co;
2733 expr_ty outermost_iter = ((comprehension_ty)
2734 (asdl_seq_GET(e->v.GeneratorExp.generators,
2735 0)))->iter;
2736
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002737 if (!name) {
2738 name = PyString_FromString("<genexpr>");
2739 if (!name)
2740 return 0;
2741 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742
2743 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2744 return 0;
2745 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2746 e->v.GeneratorExp.elt);
2747 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002748 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749 if (co == NULL)
2750 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002752 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002753 Py_DECREF(co);
2754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755 VISIT(c, expr, outermost_iter);
2756 ADDOP(c, GET_ITER);
2757 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758
2759 return 1;
2760}
2761
2762static int
2763compiler_visit_keyword(struct compiler *c, keyword_ty k)
2764{
2765 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2766 VISIT(c, expr, k->value);
2767 return 1;
2768}
2769
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002770/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771 whether they are true or false.
2772
2773 Return values: 1 for true, 0 for false, -1 for non-constant.
2774 */
2775
2776static int
2777expr_constant(expr_ty e)
2778{
2779 switch (e->kind) {
2780 case Num_kind:
2781 return PyObject_IsTrue(e->v.Num.n);
2782 case Str_kind:
2783 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002784 case Name_kind:
2785 /* __debug__ is not assignable, so we can optimize
2786 * it away in if and while statements */
2787 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2788 "__debug__") == 0)
2789 return ! Py_OptimizeFlag;
2790 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 default:
2792 return -1;
2793 }
2794}
2795
Guido van Rossumc2e20742006-02-27 22:32:47 +00002796/*
2797 Implements the with statement from PEP 343.
2798
2799 The semantics outlined in that PEP are as follows:
2800
2801 with EXPR as VAR:
2802 BLOCK
2803
2804 It is implemented roughly as:
2805
Guido van Rossumda5b7012006-05-02 19:47:52 +00002806 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002807 exit = context.__exit__ # not calling it
2808 value = context.__enter__()
2809 try:
2810 VAR = value # if VAR present in the syntax
2811 BLOCK
2812 finally:
2813 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002814 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002815 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002817 exit(*exc)
2818 */
2819static int
2820compiler_with(struct compiler *c, stmt_ty s)
2821{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002822 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002823 basicblock *block, *finally;
2824 identifier tmpexit, tmpvalue = NULL;
2825
2826 assert(s->kind == With_kind);
2827
Guido van Rossumc2e20742006-02-27 22:32:47 +00002828 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002829 enter_attr = PyString_InternFromString("__enter__");
2830 if (!enter_attr)
2831 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002832 }
2833 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002834 exit_attr = PyString_InternFromString("__exit__");
2835 if (!exit_attr)
2836 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002837 }
2838
2839 block = compiler_new_block(c);
2840 finally = compiler_new_block(c);
2841 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002843
2844 /* Create a temporary variable to hold context.__exit__ */
2845 tmpexit = compiler_new_tmpname(c);
2846 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002848 PyArena_AddPyObject(c->c_arena, tmpexit);
2849
2850 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002851 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002852 We need to do this rather than preserving it on the stack
2853 because SETUP_FINALLY remembers the stack level.
2854 We need to do the assignment *inside* the try/finally
2855 so that context.__exit__() is called when the assignment
2856 fails. But we need to call context.__enter__() *before*
2857 the try/finally so that if it fails we won't call
2858 context.__exit__().
2859 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002860 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002861 if (tmpvalue == NULL)
2862 return 0;
2863 PyArena_AddPyObject(c->c_arena, tmpvalue);
2864 }
2865
Guido van Rossumda5b7012006-05-02 19:47:52 +00002866 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002867 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002868
2869 /* Squirrel away context.__exit__ */
2870 ADDOP(c, DUP_TOP);
2871 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2872 if (!compiler_nameop(c, tmpexit, Store))
2873 return 0;
2874
2875 /* Call context.__enter__() */
2876 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2877 ADDOP_I(c, CALL_FUNCTION, 0);
2878
2879 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002880 /* Store it in tmpvalue */
2881 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002882 return 0;
2883 }
2884 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002885 /* Discard result from context.__enter__() */
2886 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002887 }
2888
2889 /* Start the try block */
2890 ADDOP_JREL(c, SETUP_FINALLY, finally);
2891
2892 compiler_use_next_block(c, block);
2893 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002894 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002895 }
2896
2897 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002898 /* Bind saved result of context.__enter__() to VAR */
2899 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002900 !compiler_nameop(c, tmpvalue, Del))
2901 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002902 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002903 }
2904
2905 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002906 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002907
2908 /* End of try block; start the finally block */
2909 ADDOP(c, POP_BLOCK);
2910 compiler_pop_fblock(c, FINALLY_TRY, block);
2911
2912 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2913 compiler_use_next_block(c, finally);
2914 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002915 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002916
2917 /* Finally block starts; push tmpexit and issue our magic opcode. */
2918 if (!compiler_nameop(c, tmpexit, Load) ||
2919 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002920 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002921 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002922
2923 /* Finally block ends. */
2924 ADDOP(c, END_FINALLY);
2925 compiler_pop_fblock(c, FINALLY_END, finally);
2926 return 1;
2927}
2928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929static int
2930compiler_visit_expr(struct compiler *c, expr_ty e)
2931{
2932 int i, n;
2933
Jeremy Hylton12603c42006-04-01 16:18:02 +00002934 /* If expr e has a different line number than the last expr/stmt,
2935 set a new line number for the next instruction.
2936 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937 if (e->lineno > c->u->u_lineno) {
2938 c->u->u_lineno = e->lineno;
2939 c->u->u_lineno_set = false;
2940 }
2941 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002942 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002944 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 VISIT(c, expr, e->v.BinOp.left);
2946 VISIT(c, expr, e->v.BinOp.right);
2947 ADDOP(c, binop(c, e->v.BinOp.op));
2948 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002949 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950 VISIT(c, expr, e->v.UnaryOp.operand);
2951 ADDOP(c, unaryop(e->v.UnaryOp.op));
2952 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002953 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002955 case IfExp_kind:
2956 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002957 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 /* XXX get rid of arg? */
2959 ADDOP_I(c, BUILD_MAP, 0);
2960 n = asdl_seq_LEN(e->v.Dict.values);
2961 /* We must arrange things just right for STORE_SUBSCR.
2962 It wants the stack to look like (value) (dict) (key) */
2963 for (i = 0; i < n; i++) {
2964 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002965 VISIT(c, expr,
2966 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002968 VISIT(c, expr,
2969 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970 ADDOP(c, STORE_SUBSCR);
2971 }
2972 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002973 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002975 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 return compiler_genexp(c, e);
2977 case Yield_kind:
2978 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002979 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 /*
2981 for (i = 0; i < c->u->u_nfblocks; i++) {
2982 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2983 return compiler_error(
2984 c, "'yield' not allowed in a 'try' "
2985 "block with a 'finally' clause");
2986 }
2987 */
2988 if (e->v.Yield.value) {
2989 VISIT(c, expr, e->v.Yield.value);
2990 }
2991 else {
2992 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2993 }
2994 ADDOP(c, YIELD_VALUE);
2995 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002996 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002998 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003000 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001 VISIT(c, expr, e->v.Repr.value);
3002 ADDOP(c, UNARY_CONVERT);
3003 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003004 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3006 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003007 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3009 break;
3010 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003011 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012 if (e->v.Attribute.ctx != AugStore)
3013 VISIT(c, expr, e->v.Attribute.value);
3014 switch (e->v.Attribute.ctx) {
3015 case AugLoad:
3016 ADDOP(c, DUP_TOP);
3017 /* Fall through to load */
3018 case Load:
3019 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3020 break;
3021 case AugStore:
3022 ADDOP(c, ROT_TWO);
3023 /* Fall through to save */
3024 case Store:
3025 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3026 break;
3027 case Del:
3028 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3029 break;
3030 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003031 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003032 PyErr_SetString(PyExc_SystemError,
3033 "param invalid in attribute expression");
3034 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 }
3036 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003037 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 switch (e->v.Subscript.ctx) {
3039 case AugLoad:
3040 VISIT(c, expr, e->v.Subscript.value);
3041 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3042 break;
3043 case Load:
3044 VISIT(c, expr, e->v.Subscript.value);
3045 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3046 break;
3047 case AugStore:
3048 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3049 break;
3050 case Store:
3051 VISIT(c, expr, e->v.Subscript.value);
3052 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3053 break;
3054 case Del:
3055 VISIT(c, expr, e->v.Subscript.value);
3056 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3057 break;
3058 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003059 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003060 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003061 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003062 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063 }
3064 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003065 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003066 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3067 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003068 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003069 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 return compiler_tuple(c, e);
3072 }
3073 return 1;
3074}
3075
3076static int
3077compiler_augassign(struct compiler *c, stmt_ty s)
3078{
3079 expr_ty e = s->v.AugAssign.target;
3080 expr_ty auge;
3081
3082 assert(s->kind == AugAssign_kind);
3083
3084 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003085 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003087 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003088 if (auge == NULL)
3089 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090 VISIT(c, expr, auge);
3091 VISIT(c, expr, s->v.AugAssign.value);
3092 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3093 auge->v.Attribute.ctx = AugStore;
3094 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095 break;
3096 case Subscript_kind:
3097 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003098 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003099 if (auge == NULL)
3100 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101 VISIT(c, expr, auge);
3102 VISIT(c, expr, s->v.AugAssign.value);
3103 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003104 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003106 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003108 if (!compiler_nameop(c, e->v.Name.id, Load))
3109 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110 VISIT(c, expr, s->v.AugAssign.value);
3111 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3112 return compiler_nameop(c, e->v.Name.id, Store);
3113 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003114 PyErr_Format(PyExc_SystemError,
3115 "invalid node type (%d) for augmented assignment",
3116 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003117 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118 }
3119 return 1;
3120}
3121
3122static int
3123compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3124{
3125 struct fblockinfo *f;
3126 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3127 return 0;
3128 f = &c->u->u_fblock[c->u->u_nfblocks++];
3129 f->fb_type = t;
3130 f->fb_block = b;
3131 return 1;
3132}
3133
3134static void
3135compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3136{
3137 struct compiler_unit *u = c->u;
3138 assert(u->u_nfblocks > 0);
3139 u->u_nfblocks--;
3140 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3141 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3142}
3143
3144/* Raises a SyntaxError and returns 0.
3145 If something goes wrong, a different exception may be raised.
3146*/
3147
3148static int
3149compiler_error(struct compiler *c, const char *errstr)
3150{
3151 PyObject *loc;
3152 PyObject *u = NULL, *v = NULL;
3153
3154 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3155 if (!loc) {
3156 Py_INCREF(Py_None);
3157 loc = Py_None;
3158 }
3159 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3160 Py_None, loc);
3161 if (!u)
3162 goto exit;
3163 v = Py_BuildValue("(zO)", errstr, u);
3164 if (!v)
3165 goto exit;
3166 PyErr_SetObject(PyExc_SyntaxError, v);
3167 exit:
3168 Py_DECREF(loc);
3169 Py_XDECREF(u);
3170 Py_XDECREF(v);
3171 return 0;
3172}
3173
3174static int
3175compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003176 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003178 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003180 /* XXX this code is duplicated */
3181 switch (ctx) {
3182 case AugLoad: /* fall through to Load */
3183 case Load: op = BINARY_SUBSCR; break;
3184 case AugStore:/* fall through to Store */
3185 case Store: op = STORE_SUBSCR; break;
3186 case Del: op = DELETE_SUBSCR; break;
3187 case Param:
3188 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003189 "invalid %s kind %d in subscript\n",
3190 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003191 return 0;
3192 }
3193 if (ctx == AugLoad) {
3194 ADDOP_I(c, DUP_TOPX, 2);
3195 }
3196 else if (ctx == AugStore) {
3197 ADDOP(c, ROT_THREE);
3198 }
3199 ADDOP(c, op);
3200 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201}
3202
3203static int
3204compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3205{
3206 int n = 2;
3207 assert(s->kind == Slice_kind);
3208
3209 /* only handles the cases where BUILD_SLICE is emitted */
3210 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212 }
3213 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003214 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003215 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003218 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 }
3220 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 }
3223
3224 if (s->v.Slice.step) {
3225 n++;
3226 VISIT(c, expr, s->v.Slice.step);
3227 }
3228 ADDOP_I(c, BUILD_SLICE, n);
3229 return 1;
3230}
3231
3232static int
3233compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3234{
3235 int op = 0, slice_offset = 0, stack_count = 0;
3236
3237 assert(s->v.Slice.step == NULL);
3238 if (s->v.Slice.lower) {
3239 slice_offset++;
3240 stack_count++;
3241 if (ctx != AugStore)
3242 VISIT(c, expr, s->v.Slice.lower);
3243 }
3244 if (s->v.Slice.upper) {
3245 slice_offset += 2;
3246 stack_count++;
3247 if (ctx != AugStore)
3248 VISIT(c, expr, s->v.Slice.upper);
3249 }
3250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003251 if (ctx == AugLoad) {
3252 switch (stack_count) {
3253 case 0: ADDOP(c, DUP_TOP); break;
3254 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3255 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3256 }
3257 }
3258 else if (ctx == AugStore) {
3259 switch (stack_count) {
3260 case 0: ADDOP(c, ROT_TWO); break;
3261 case 1: ADDOP(c, ROT_THREE); break;
3262 case 2: ADDOP(c, ROT_FOUR); break;
3263 }
3264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265
3266 switch (ctx) {
3267 case AugLoad: /* fall through to Load */
3268 case Load: op = SLICE; break;
3269 case AugStore:/* fall through to Store */
3270 case Store: op = STORE_SLICE; break;
3271 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003272 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003273 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003274 PyErr_SetString(PyExc_SystemError,
3275 "param invalid in simple slice");
3276 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 }
3278
3279 ADDOP(c, op + slice_offset);
3280 return 1;
3281}
3282
3283static int
3284compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3285 expr_context_ty ctx)
3286{
3287 switch (s->kind) {
3288 case Ellipsis_kind:
3289 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3290 break;
3291 case Slice_kind:
3292 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293 case Index_kind:
3294 VISIT(c, expr, s->v.Index.value);
3295 break;
3296 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003297 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003298 PyErr_SetString(PyExc_SystemError,
3299 "extended slice invalid in nested slice");
3300 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 }
3302 return 1;
3303}
3304
3305
3306static int
3307compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3308{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003309 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003311 case Index_kind:
3312 kindname = "index";
3313 if (ctx != AugStore) {
3314 VISIT(c, expr, s->v.Index.value);
3315 }
3316 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003318 kindname = "ellipsis";
3319 if (ctx != AugStore) {
3320 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3321 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 break;
3323 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003324 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 if (!s->v.Slice.step)
3326 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003327 if (ctx != AugStore) {
3328 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329 return 0;
3330 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003331 break;
3332 case ExtSlice_kind:
3333 kindname = "extended slice";
3334 if (ctx != AugStore) {
3335 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3336 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003337 slice_ty sub = (slice_ty)asdl_seq_GET(
3338 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003339 if (!compiler_visit_nested_slice(c, sub, ctx))
3340 return 0;
3341 }
3342 ADDOP_I(c, BUILD_TUPLE, n);
3343 }
3344 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003345 default:
3346 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003347 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003348 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003350 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003351}
3352
3353/* do depth-first search of basic block graph, starting with block.
3354 post records the block indices in post-order.
3355
3356 XXX must handle implicit jumps from one block to next
3357*/
3358
3359static void
3360dfs(struct compiler *c, basicblock *b, struct assembler *a)
3361{
3362 int i;
3363 struct instr *instr = NULL;
3364
3365 if (b->b_seen)
3366 return;
3367 b->b_seen = 1;
3368 if (b->b_next != NULL)
3369 dfs(c, b->b_next, a);
3370 for (i = 0; i < b->b_iused; i++) {
3371 instr = &b->b_instr[i];
3372 if (instr->i_jrel || instr->i_jabs)
3373 dfs(c, instr->i_target, a);
3374 }
3375 a->a_postorder[a->a_nblocks++] = b;
3376}
3377
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003378static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003379stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3380{
3381 int i;
3382 struct instr *instr;
3383 if (b->b_seen || b->b_startdepth >= depth)
3384 return maxdepth;
3385 b->b_seen = 1;
3386 b->b_startdepth = depth;
3387 for (i = 0; i < b->b_iused; i++) {
3388 instr = &b->b_instr[i];
3389 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3390 if (depth > maxdepth)
3391 maxdepth = depth;
3392 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3393 if (instr->i_jrel || instr->i_jabs) {
3394 maxdepth = stackdepth_walk(c, instr->i_target,
3395 depth, maxdepth);
3396 if (instr->i_opcode == JUMP_ABSOLUTE ||
3397 instr->i_opcode == JUMP_FORWARD) {
3398 goto out; /* remaining code is dead */
3399 }
3400 }
3401 }
3402 if (b->b_next)
3403 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3404out:
3405 b->b_seen = 0;
3406 return maxdepth;
3407}
3408
3409/* Find the flow path that needs the largest stack. We assume that
3410 * cycles in the flow graph have no net effect on the stack depth.
3411 */
3412static int
3413stackdepth(struct compiler *c)
3414{
3415 basicblock *b, *entryblock;
3416 entryblock = NULL;
3417 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3418 b->b_seen = 0;
3419 b->b_startdepth = INT_MIN;
3420 entryblock = b;
3421 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003422 if (!entryblock)
3423 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424 return stackdepth_walk(c, entryblock, 0, 0);
3425}
3426
3427static int
3428assemble_init(struct assembler *a, int nblocks, int firstlineno)
3429{
3430 memset(a, 0, sizeof(struct assembler));
3431 a->a_lineno = firstlineno;
3432 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3433 if (!a->a_bytecode)
3434 return 0;
3435 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3436 if (!a->a_lnotab)
3437 return 0;
3438 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003439 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003440 if (!a->a_postorder) {
3441 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003443 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444 return 1;
3445}
3446
3447static void
3448assemble_free(struct assembler *a)
3449{
3450 Py_XDECREF(a->a_bytecode);
3451 Py_XDECREF(a->a_lnotab);
3452 if (a->a_postorder)
3453 PyObject_Free(a->a_postorder);
3454}
3455
3456/* Return the size of a basic block in bytes. */
3457
3458static int
3459instrsize(struct instr *instr)
3460{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003461 if (!instr->i_hasarg)
3462 return 1;
3463 if (instr->i_oparg > 0xffff)
3464 return 6;
3465 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466}
3467
3468static int
3469blocksize(basicblock *b)
3470{
3471 int i;
3472 int size = 0;
3473
3474 for (i = 0; i < b->b_iused; i++)
3475 size += instrsize(&b->b_instr[i]);
3476 return size;
3477}
3478
3479/* All about a_lnotab.
3480
3481c_lnotab is an array of unsigned bytes disguised as a Python string.
3482It is used to map bytecode offsets to source code line #s (when needed
3483for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003484
Tim Peters2a7f3842001-06-09 09:26:21 +00003485The array is conceptually a list of
3486 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003487pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003488
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003489 byte code offset source code line number
3490 0 1
3491 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003492 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 350 307
3494 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003495
3496The first trick is that these numbers aren't stored, only the increments
3497from one row to the next (this doesn't really work, but it's a start):
3498
3499 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3500
3501The second trick is that an unsigned byte can't hold negative values, or
3502values larger than 255, so (a) there's a deep assumption that byte code
3503offsets and their corresponding line #s both increase monotonically, and (b)
3504if at least one column jumps by more than 255 from one row to the next, more
3505than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003507part. A user of c_lnotab desiring to find the source line number
3508corresponding to a bytecode address A should do something like this
3509
3510 lineno = addr = 0
3511 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003512 addr += addr_incr
3513 if addr > A:
3514 return lineno
3515 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003516
3517In order for this to work, when the addr field increments by more than 255,
3518the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003519increment is < 256. So, in the example above, assemble_lnotab (it used
3520to be called com_set_lineno) should not (as was actually done until 2.2)
3521expand 300, 300 to 255, 255, 45, 45,
3522 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003523*/
3524
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003525static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003527{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 int d_bytecode, d_lineno;
3529 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003530 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531
3532 d_bytecode = a->a_offset - a->a_lineno_off;
3533 d_lineno = i->i_lineno - a->a_lineno;
3534
3535 assert(d_bytecode >= 0);
3536 assert(d_lineno >= 0);
3537
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003538 /* XXX(nnorwitz): is there a better way to handle this?
3539 for loops are special, we want to be able to trace them
3540 each time around, so we need to set an extra line number. */
3541 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003542 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003543
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003545 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 nbytes = a->a_lnotab_off + 2 * ncodes;
3547 len = PyString_GET_SIZE(a->a_lnotab);
3548 if (nbytes >= len) {
3549 if (len * 2 < nbytes)
3550 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003551 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 len *= 2;
3553 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3554 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003555 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003556 lnotab = (unsigned char *)
3557 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003558 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559 *lnotab++ = 255;
3560 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 d_bytecode -= ncodes * 255;
3563 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003564 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 assert(d_bytecode <= 255);
3566 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003567 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 nbytes = a->a_lnotab_off + 2 * ncodes;
3569 len = PyString_GET_SIZE(a->a_lnotab);
3570 if (nbytes >= len) {
3571 if (len * 2 < nbytes)
3572 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003573 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 len *= 2;
3575 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3576 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003577 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003578 lnotab = (unsigned char *)
3579 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003581 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003583 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003585 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003586 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587 d_lineno -= ncodes * 255;
3588 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003589 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003590
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591 len = PyString_GET_SIZE(a->a_lnotab);
3592 if (a->a_lnotab_off + 2 >= len) {
3593 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003594 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003595 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003596 lnotab = (unsigned char *)
3597 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003598
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599 a->a_lnotab_off += 2;
3600 if (d_bytecode) {
3601 *lnotab++ = d_bytecode;
3602 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003603 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003604 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 *lnotab++ = 0;
3606 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003607 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608 a->a_lineno = i->i_lineno;
3609 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003610 return 1;
3611}
3612
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613/* assemble_emit()
3614 Extend the bytecode with a new instruction.
3615 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003616*/
3617
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003618static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003620{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003621 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003622 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 char *code;
3624
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003625 size = instrsize(i);
3626 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003628 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003629 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003631 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 if (a->a_offset + size >= len) {
3633 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003634 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3637 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003638 if (size == 6) {
3639 assert(i->i_hasarg);
3640 *code++ = (char)EXTENDED_ARG;
3641 *code++ = ext & 0xff;
3642 *code++ = ext >> 8;
3643 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003644 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003646 if (i->i_hasarg) {
3647 assert(size == 3 || size == 6);
3648 *code++ = arg & 0xff;
3649 *code++ = arg >> 8;
3650 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003652}
3653
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003654static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003656{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003658 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003659 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003660
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661 /* Compute the size of each block and fixup jump args.
3662 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003663start:
3664 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003665 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003666 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667 bsize = blocksize(b);
3668 b->b_offset = totsize;
3669 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003670 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003671 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3673 bsize = b->b_offset;
3674 for (i = 0; i < b->b_iused; i++) {
3675 struct instr *instr = &b->b_instr[i];
3676 /* Relative jumps are computed relative to
3677 the instruction pointer after fetching
3678 the jump instruction.
3679 */
3680 bsize += instrsize(instr);
3681 if (instr->i_jabs)
3682 instr->i_oparg = instr->i_target->b_offset;
3683 else if (instr->i_jrel) {
3684 int delta = instr->i_target->b_offset - bsize;
3685 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003686 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003687 else
3688 continue;
3689 if (instr->i_oparg > 0xffff)
3690 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003691 }
3692 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003693
3694 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003695 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003696 with a better solution.
3697
3698 In the meantime, should the goto be dropped in favor
3699 of a loop?
3700
3701 The issue is that in the first loop blocksize() is called
3702 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003703 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003704 i_oparg is calculated in the second loop above.
3705
3706 So we loop until we stop seeing new EXTENDED_ARGs.
3707 The only EXTENDED_ARGs that could be popping up are
3708 ones in jump instructions. So this should converge
3709 fairly quickly.
3710 */
3711 if (last_extended_arg_count != extended_arg_count) {
3712 last_extended_arg_count = extended_arg_count;
3713 goto start;
3714 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003715}
3716
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003717static PyObject *
3718dict_keys_inorder(PyObject *dict, int offset)
3719{
3720 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003721 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003722
3723 tuple = PyTuple_New(size);
3724 if (tuple == NULL)
3725 return NULL;
3726 while (PyDict_Next(dict, &pos, &k, &v)) {
3727 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003728 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003729 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003730 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003731 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003732 PyTuple_SET_ITEM(tuple, i - offset, k);
3733 }
3734 return tuple;
3735}
3736
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003737static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003739{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740 PySTEntryObject *ste = c->u->u_ste;
3741 int flags = 0, n;
3742 if (ste->ste_type != ModuleBlock)
3743 flags |= CO_NEWLOCALS;
3744 if (ste->ste_type == FunctionBlock) {
3745 if (!ste->ste_unoptimized)
3746 flags |= CO_OPTIMIZED;
3747 if (ste->ste_nested)
3748 flags |= CO_NESTED;
3749 if (ste->ste_generator)
3750 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003751 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003752 if (ste->ste_varargs)
3753 flags |= CO_VARARGS;
3754 if (ste->ste_varkeywords)
3755 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003756 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003758
3759 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003760 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003761
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 n = PyDict_Size(c->u->u_freevars);
3763 if (n < 0)
3764 return -1;
3765 if (n == 0) {
3766 n = PyDict_Size(c->u->u_cellvars);
3767 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003768 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769 if (n == 0) {
3770 flags |= CO_NOFREE;
3771 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003772 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003773
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003774 return flags;
3775}
3776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777static PyCodeObject *
3778makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003779{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 PyObject *tmp;
3781 PyCodeObject *co = NULL;
3782 PyObject *consts = NULL;
3783 PyObject *names = NULL;
3784 PyObject *varnames = NULL;
3785 PyObject *filename = NULL;
3786 PyObject *name = NULL;
3787 PyObject *freevars = NULL;
3788 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003789 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003791
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792 tmp = dict_keys_inorder(c->u->u_consts, 0);
3793 if (!tmp)
3794 goto error;
3795 consts = PySequence_List(tmp); /* optimize_code requires a list */
3796 Py_DECREF(tmp);
3797
3798 names = dict_keys_inorder(c->u->u_names, 0);
3799 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3800 if (!consts || !names || !varnames)
3801 goto error;
3802
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003803 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3804 if (!cellvars)
3805 goto error;
3806 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3807 if (!freevars)
3808 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809 filename = PyString_FromString(c->c_filename);
3810 if (!filename)
3811 goto error;
3812
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003813 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 flags = compute_code_flags(c);
3815 if (flags < 0)
3816 goto error;
3817
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003818 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819 if (!bytecode)
3820 goto error;
3821
3822 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3823 if (!tmp)
3824 goto error;
3825 Py_DECREF(consts);
3826 consts = tmp;
3827
3828 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3829 bytecode, consts, names, varnames,
3830 freevars, cellvars,
3831 filename, c->u->u_name,
3832 c->u->u_firstlineno,
3833 a->a_lnotab);
3834 error:
3835 Py_XDECREF(consts);
3836 Py_XDECREF(names);
3837 Py_XDECREF(varnames);
3838 Py_XDECREF(filename);
3839 Py_XDECREF(name);
3840 Py_XDECREF(freevars);
3841 Py_XDECREF(cellvars);
3842 Py_XDECREF(bytecode);
3843 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003844}
3845
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003846
3847/* For debugging purposes only */
3848#if 0
3849static void
3850dump_instr(const struct instr *i)
3851{
3852 const char *jrel = i->i_jrel ? "jrel " : "";
3853 const char *jabs = i->i_jabs ? "jabs " : "";
3854 char arg[128];
3855
3856 *arg = '\0';
3857 if (i->i_hasarg)
3858 sprintf(arg, "arg: %d ", i->i_oparg);
3859
3860 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3861 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3862}
3863
3864static void
3865dump_basicblock(const basicblock *b)
3866{
3867 const char *seen = b->b_seen ? "seen " : "";
3868 const char *b_return = b->b_return ? "return " : "";
3869 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3870 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3871 if (b->b_instr) {
3872 int i;
3873 for (i = 0; i < b->b_iused; i++) {
3874 fprintf(stderr, " [%02d] ", i);
3875 dump_instr(b->b_instr + i);
3876 }
3877 }
3878}
3879#endif
3880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881static PyCodeObject *
3882assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003883{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 basicblock *b, *entryblock;
3885 struct assembler a;
3886 int i, j, nblocks;
3887 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003888
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889 /* Make sure every block that falls off the end returns None.
3890 XXX NEXT_BLOCK() isn't quite right, because if the last
3891 block ends with a jump or return b_next shouldn't set.
3892 */
3893 if (!c->u->u_curblock->b_return) {
3894 NEXT_BLOCK(c);
3895 if (addNone)
3896 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3897 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003898 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003899
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 nblocks = 0;
3901 entryblock = NULL;
3902 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3903 nblocks++;
3904 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003905 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003906
Neal Norwitzed657552006-07-10 00:04:44 +00003907 /* Set firstlineno if it wasn't explicitly set. */
3908 if (!c->u->u_firstlineno) {
3909 if (entryblock && entryblock->b_instr)
3910 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3911 else
3912 c->u->u_firstlineno = 1;
3913 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3915 goto error;
3916 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003919 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003920
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921 /* Emit code in reverse postorder from dfs. */
3922 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003923 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003924 for (j = 0; j < b->b_iused; j++)
3925 if (!assemble_emit(&a, &b->b_instr[j]))
3926 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003927 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003929 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3930 goto error;
3931 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3932 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934 co = makecode(c, &a);
3935 error:
3936 assemble_free(&a);
3937 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003938}