blob: 5aaf809cd48799f4d7e548be12a0c3daf8cb9cd5 [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);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000571 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000572 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000574 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575 compiler_unit_check(c->u);
576 }
577 else
578 c->u = NULL;
579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580}
581
Guido van Rossumc2e20742006-02-27 22:32:47 +0000582/* Allocate a new "anonymous" local variable.
583 Used by list comprehensions and with statements.
584*/
585
586static PyObject *
587compiler_new_tmpname(struct compiler *c)
588{
589 char tmpname[256];
590 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
591 return PyString_FromString(tmpname);
592}
593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594/* Allocate a new block and return a pointer to it.
595 Returns NULL on error.
596*/
597
598static basicblock *
599compiler_new_block(struct compiler *c)
600{
601 basicblock *b;
602 struct compiler_unit *u;
603
604 u = c->u;
605 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000606 if (b == NULL) {
607 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +0000611 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612 b->b_list = u->u_blocks;
613 u->u_blocks = b;
614 return b;
615}
616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617static basicblock *
618compiler_use_new_block(struct compiler *c)
619{
620 basicblock *block = compiler_new_block(c);
621 if (block == NULL)
622 return NULL;
623 c->u->u_curblock = block;
624 return block;
625}
626
627static basicblock *
628compiler_next_block(struct compiler *c)
629{
630 basicblock *block = compiler_new_block(c);
631 if (block == NULL)
632 return NULL;
633 c->u->u_curblock->b_next = block;
634 c->u->u_curblock = block;
635 return block;
636}
637
638static basicblock *
639compiler_use_next_block(struct compiler *c, basicblock *block)
640{
641 assert(block != NULL);
642 c->u->u_curblock->b_next = block;
643 c->u->u_curblock = block;
644 return block;
645}
646
647/* Returns the offset of the next instruction in the current block's
648 b_instr array. Resizes the b_instr as necessary.
649 Returns -1 on failure.
650 */
651
652static int
653compiler_next_instr(struct compiler *c, basicblock *b)
654{
655 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000657 b->b_instr = (struct instr *)PyObject_Malloc(
658 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659 if (b->b_instr == NULL) {
660 PyErr_NoMemory();
661 return -1;
662 }
663 b->b_ialloc = DEFAULT_BLOCK_SIZE;
664 memset((char *)b->b_instr, 0,
665 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000668 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669 size_t oldsize, newsize;
670 oldsize = b->b_ialloc * sizeof(struct instr);
671 newsize = oldsize << 1;
672 if (newsize == 0) {
673 PyErr_NoMemory();
674 return -1;
675 }
676 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000677 tmp = (struct instr *)PyObject_Realloc(
Anthony Baxter7b782b62006-04-11 12:01:56 +0000678 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000679 if (tmp == NULL) {
680 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000681 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000682 }
683 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
685 }
686 return b->b_iused++;
687}
688
Jeremy Hylton12603c42006-04-01 16:18:02 +0000689/* Set the i_lineno member of the instruction at offse off if the
690 line number for the current expression/statement (?) has not
691 already been set. If it has been set, the call has no effect.
692
693 Every time a new node is b
694 */
695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696static void
697compiler_set_lineno(struct compiler *c, int off)
698{
699 basicblock *b;
700 if (c->u->u_lineno_set)
701 return;
702 c->u->u_lineno_set = true;
703 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000704 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705}
706
707static int
708opcode_stack_effect(int opcode, int oparg)
709{
710 switch (opcode) {
711 case POP_TOP:
712 return -1;
713 case ROT_TWO:
714 case ROT_THREE:
715 return 0;
716 case DUP_TOP:
717 return 1;
718 case ROT_FOUR:
719 return 0;
720
721 case UNARY_POSITIVE:
722 case UNARY_NEGATIVE:
723 case UNARY_NOT:
724 case UNARY_CONVERT:
725 case UNARY_INVERT:
726 return 0;
727
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000728 case LIST_APPEND:
729 return -2;
730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000731 case BINARY_POWER:
732 case BINARY_MULTIPLY:
733 case BINARY_DIVIDE:
734 case BINARY_MODULO:
735 case BINARY_ADD:
736 case BINARY_SUBTRACT:
737 case BINARY_SUBSCR:
738 case BINARY_FLOOR_DIVIDE:
739 case BINARY_TRUE_DIVIDE:
740 return -1;
741 case INPLACE_FLOOR_DIVIDE:
742 case INPLACE_TRUE_DIVIDE:
743 return -1;
744
745 case SLICE+0:
746 return 1;
747 case SLICE+1:
748 return 0;
749 case SLICE+2:
750 return 0;
751 case SLICE+3:
752 return -1;
753
754 case STORE_SLICE+0:
755 return -2;
756 case STORE_SLICE+1:
757 return -3;
758 case STORE_SLICE+2:
759 return -3;
760 case STORE_SLICE+3:
761 return -4;
762
763 case DELETE_SLICE+0:
764 return -1;
765 case DELETE_SLICE+1:
766 return -2;
767 case DELETE_SLICE+2:
768 return -2;
769 case DELETE_SLICE+3:
770 return -3;
771
772 case INPLACE_ADD:
773 case INPLACE_SUBTRACT:
774 case INPLACE_MULTIPLY:
775 case INPLACE_DIVIDE:
776 case INPLACE_MODULO:
777 return -1;
778 case STORE_SUBSCR:
779 return -3;
780 case DELETE_SUBSCR:
781 return -2;
782
783 case BINARY_LSHIFT:
784 case BINARY_RSHIFT:
785 case BINARY_AND:
786 case BINARY_XOR:
787 case BINARY_OR:
788 return -1;
789 case INPLACE_POWER:
790 return -1;
791 case GET_ITER:
792 return 0;
793
794 case PRINT_EXPR:
795 return -1;
796 case PRINT_ITEM:
797 return -1;
798 case PRINT_NEWLINE:
799 return 0;
800 case PRINT_ITEM_TO:
801 return -2;
802 case PRINT_NEWLINE_TO:
803 return -1;
804 case INPLACE_LSHIFT:
805 case INPLACE_RSHIFT:
806 case INPLACE_AND:
807 case INPLACE_XOR:
808 case INPLACE_OR:
809 return -1;
810 case BREAK_LOOP:
811 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000812 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000813 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000814 case LOAD_LOCALS:
815 return 1;
816 case RETURN_VALUE:
817 return -1;
818 case IMPORT_STAR:
819 return -1;
820 case EXEC_STMT:
821 return -3;
822 case YIELD_VALUE:
823 return 0;
824
825 case POP_BLOCK:
826 return 0;
827 case END_FINALLY:
828 return -1; /* or -2 or -3 if exception occurred */
829 case BUILD_CLASS:
830 return -2;
831
832 case STORE_NAME:
833 return -1;
834 case DELETE_NAME:
835 return 0;
836 case UNPACK_SEQUENCE:
837 return oparg-1;
838 case FOR_ITER:
839 return 1;
840
841 case STORE_ATTR:
842 return -2;
843 case DELETE_ATTR:
844 return -1;
845 case STORE_GLOBAL:
846 return -1;
847 case DELETE_GLOBAL:
848 return 0;
849 case DUP_TOPX:
850 return oparg;
851 case LOAD_CONST:
852 return 1;
853 case LOAD_NAME:
854 return 1;
855 case BUILD_TUPLE:
856 case BUILD_LIST:
857 return 1-oparg;
858 case BUILD_MAP:
859 return 1;
860 case LOAD_ATTR:
861 return 0;
862 case COMPARE_OP:
863 return -1;
864 case IMPORT_NAME:
865 return 0;
866 case IMPORT_FROM:
867 return 1;
868
869 case JUMP_FORWARD:
870 case JUMP_IF_FALSE:
871 case JUMP_IF_TRUE:
872 case JUMP_ABSOLUTE:
873 return 0;
874
875 case LOAD_GLOBAL:
876 return 1;
877
878 case CONTINUE_LOOP:
879 return 0;
880 case SETUP_LOOP:
881 return 0;
882 case SETUP_EXCEPT:
883 case SETUP_FINALLY:
884 return 3; /* actually pushed by an exception */
885
886 case LOAD_FAST:
887 return 1;
888 case STORE_FAST:
889 return -1;
890 case DELETE_FAST:
891 return 0;
892
893 case RAISE_VARARGS:
894 return -oparg;
895#define NARGS(o) (((o) % 256) + 2*((o) / 256))
896 case CALL_FUNCTION:
897 return -NARGS(oparg);
898 case CALL_FUNCTION_VAR:
899 case CALL_FUNCTION_KW:
900 return -NARGS(oparg)-1;
901 case CALL_FUNCTION_VAR_KW:
902 return -NARGS(oparg)-2;
903#undef NARGS
904 case MAKE_FUNCTION:
905 return -oparg;
906 case BUILD_SLICE:
907 if (oparg == 3)
908 return -2;
909 else
910 return -1;
911
912 case MAKE_CLOSURE:
913 return -oparg;
914 case LOAD_CLOSURE:
915 return 1;
916 case LOAD_DEREF:
917 return 1;
918 case STORE_DEREF:
919 return -1;
920 default:
921 fprintf(stderr, "opcode = %d\n", opcode);
922 Py_FatalError("opcode_stack_effect()");
923
924 }
925 return 0; /* not reachable */
926}
927
928/* Add an opcode with no argument.
929 Returns 0 on failure, 1 on success.
930*/
931
932static int
933compiler_addop(struct compiler *c, int opcode)
934{
935 basicblock *b;
936 struct instr *i;
937 int off;
938 off = compiler_next_instr(c, c->u->u_curblock);
939 if (off < 0)
940 return 0;
941 b = c->u->u_curblock;
942 i = &b->b_instr[off];
943 i->i_opcode = opcode;
944 i->i_hasarg = 0;
945 if (opcode == RETURN_VALUE)
946 b->b_return = 1;
947 compiler_set_lineno(c, off);
948 return 1;
949}
950
951static int
952compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
953{
954 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000955 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000957 /* necessary to make sure types aren't coerced (e.g., int and long) */
958 t = PyTuple_Pack(2, o, o->ob_type);
959 if (t == NULL)
960 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961
962 v = PyDict_GetItem(dict, t);
963 if (!v) {
964 arg = PyDict_Size(dict);
965 v = PyInt_FromLong(arg);
966 if (!v) {
967 Py_DECREF(t);
968 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000969 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970 if (PyDict_SetItem(dict, t, v) < 0) {
971 Py_DECREF(t);
972 Py_DECREF(v);
973 return -1;
974 }
975 Py_DECREF(v);
976 }
977 else
978 arg = PyInt_AsLong(v);
979 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981}
982
983static int
984compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
985 PyObject *o)
986{
987 int arg = compiler_add_o(c, dict, o);
988 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000989 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990 return compiler_addop_i(c, opcode, arg);
991}
992
993static int
994compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000995 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000996{
997 int arg;
998 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
999 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001 arg = compiler_add_o(c, dict, mangled);
1002 Py_DECREF(mangled);
1003 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005 return compiler_addop_i(c, opcode, arg);
1006}
1007
1008/* Add an opcode with an integer argument.
1009 Returns 0 on failure, 1 on success.
1010*/
1011
1012static int
1013compiler_addop_i(struct compiler *c, int opcode, int oparg)
1014{
1015 struct instr *i;
1016 int off;
1017 off = compiler_next_instr(c, c->u->u_curblock);
1018 if (off < 0)
1019 return 0;
1020 i = &c->u->u_curblock->b_instr[off];
1021 i->i_opcode = opcode;
1022 i->i_oparg = oparg;
1023 i->i_hasarg = 1;
1024 compiler_set_lineno(c, off);
1025 return 1;
1026}
1027
1028static int
1029compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1030{
1031 struct instr *i;
1032 int off;
1033
1034 assert(b != NULL);
1035 off = compiler_next_instr(c, c->u->u_curblock);
1036 if (off < 0)
1037 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038 i = &c->u->u_curblock->b_instr[off];
1039 i->i_opcode = opcode;
1040 i->i_target = b;
1041 i->i_hasarg = 1;
1042 if (absolute)
1043 i->i_jabs = 1;
1044 else
1045 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001046 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047 return 1;
1048}
1049
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001050/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1051 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052 it as the current block. NEXT_BLOCK() also creates an implicit jump
1053 from the current block to the new block.
1054*/
1055
1056/* XXX The returns inside these macros make it impossible to decref
1057 objects created in the local function.
1058*/
1059
1060
1061#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001062 if (compiler_use_new_block((C)) == NULL) \
1063 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064}
1065
1066#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001067 if (compiler_next_block((C)) == NULL) \
1068 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069}
1070
1071#define ADDOP(C, OP) { \
1072 if (!compiler_addop((C), (OP))) \
1073 return 0; \
1074}
1075
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001076#define ADDOP_IN_SCOPE(C, OP) { \
1077 if (!compiler_addop((C), (OP))) { \
1078 compiler_exit_scope(c); \
1079 return 0; \
1080 } \
1081}
1082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083#define ADDOP_O(C, OP, O, TYPE) { \
1084 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1085 return 0; \
1086}
1087
1088#define ADDOP_NAME(C, OP, O, TYPE) { \
1089 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1090 return 0; \
1091}
1092
1093#define ADDOP_I(C, OP, O) { \
1094 if (!compiler_addop_i((C), (OP), (O))) \
1095 return 0; \
1096}
1097
1098#define ADDOP_JABS(C, OP, O) { \
1099 if (!compiler_addop_j((C), (OP), (O), 1)) \
1100 return 0; \
1101}
1102
1103#define ADDOP_JREL(C, OP, O) { \
1104 if (!compiler_addop_j((C), (OP), (O), 0)) \
1105 return 0; \
1106}
1107
1108/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1109 the ASDL name to synthesize the name of the C type and the visit function.
1110*/
1111
1112#define VISIT(C, TYPE, V) {\
1113 if (!compiler_visit_ ## TYPE((C), (V))) \
1114 return 0; \
1115}
1116
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001117#define VISIT_IN_SCOPE(C, TYPE, V) {\
1118 if (!compiler_visit_ ## TYPE((C), (V))) { \
1119 compiler_exit_scope(c); \
1120 return 0; \
1121 } \
1122}
1123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124#define VISIT_SLICE(C, V, CTX) {\
1125 if (!compiler_visit_slice((C), (V), (CTX))) \
1126 return 0; \
1127}
1128
1129#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001133 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001134 if (!compiler_visit_ ## TYPE((C), elt)) \
1135 return 0; \
1136 } \
1137}
1138
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001141 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001143 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001144 if (!compiler_visit_ ## TYPE((C), elt)) { \
1145 compiler_exit_scope(c); \
1146 return 0; \
1147 } \
1148 } \
1149}
1150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151static int
1152compiler_isdocstring(stmt_ty s)
1153{
1154 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return s->v.Expr.value->kind == Str_kind;
1157}
1158
1159/* Compile a sequence of statements, checking for a docstring. */
1160
1161static int
1162compiler_body(struct compiler *c, asdl_seq *stmts)
1163{
1164 int i = 0;
1165 stmt_ty st;
1166
1167 if (!asdl_seq_LEN(stmts))
1168 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001169 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 if (compiler_isdocstring(st)) {
1171 i = 1;
1172 VISIT(c, expr, st->v.Expr.value);
1173 if (!compiler_nameop(c, __doc__, Store))
1174 return 0;
1175 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001176 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001177 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 return 1;
1179}
1180
1181static PyCodeObject *
1182compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001183{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001184 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001185 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 static PyObject *module;
1187 if (!module) {
1188 module = PyString_FromString("<module>");
1189 if (!module)
1190 return NULL;
1191 }
Neal Norwitzed657552006-07-10 00:04:44 +00001192 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1193 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001194 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 switch (mod->kind) {
1196 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001197 if (!compiler_body(c, mod->v.Module.body)) {
1198 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 break;
1202 case Interactive_kind:
1203 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001204 VISIT_SEQ_IN_SCOPE(c, stmt,
1205 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 break;
1207 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001208 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 break;
1211 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001212 PyErr_SetString(PyExc_SystemError,
1213 "suite should not be possible");
1214 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001215 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001216 PyErr_Format(PyExc_SystemError,
1217 "module kind %d should not be possible",
1218 mod->kind);
1219 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 co = assemble(c, addNone);
1222 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001223 return co;
1224}
1225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226/* The test for LOCAL must come before the test for FREE in order to
1227 handle classes where name is both local and free. The local var is
1228 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001229*/
1230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231static int
1232get_ref_type(struct compiler *c, PyObject *name)
1233{
1234 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001235 if (scope == 0) {
1236 char buf[350];
1237 PyOS_snprintf(buf, sizeof(buf),
1238 "unknown scope for %.100s in %.100s(%s) in %s\n"
1239 "symbols: %s\nlocals: %s\nglobals: %s\n",
1240 PyString_AS_STRING(name),
1241 PyString_AS_STRING(c->u->u_name),
1242 PyObject_REPR(c->u->u_ste->ste_id),
1243 c->c_filename,
1244 PyObject_REPR(c->u->u_ste->ste_symbols),
1245 PyObject_REPR(c->u->u_varnames),
1246 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001248 Py_FatalError(buf);
1249 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254static int
1255compiler_lookup_arg(PyObject *dict, PyObject *name)
1256{
1257 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001258 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001260 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001262 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001264 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 return PyInt_AS_LONG(v);
1266}
1267
1268static int
1269compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1270{
1271 int i, free = PyCode_GetNumFree(co);
1272 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001273 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1274 ADDOP_I(c, MAKE_FUNCTION, args);
1275 return 1;
1276 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 for (i = 0; i < free; ++i) {
1278 /* Bypass com_addop_varname because it will generate
1279 LOAD_DEREF but LOAD_CLOSURE is needed.
1280 */
1281 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1282 int arg, reftype;
1283
1284 /* Special case: If a class contains a method with a
1285 free variable that has the same name as a method,
1286 the name will be considered free *and* local in the
1287 class. It should be handled by the closure, as
1288 well as by the normal name loookup logic.
1289 */
1290 reftype = get_ref_type(c, name);
1291 if (reftype == CELL)
1292 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1293 else /* (reftype == FREE) */
1294 arg = compiler_lookup_arg(c->u->u_freevars, name);
1295 if (arg == -1) {
1296 printf("lookup %s in %s %d %d\n"
1297 "freevars of %s: %s\n",
1298 PyObject_REPR(name),
1299 PyString_AS_STRING(c->u->u_name),
1300 reftype, arg,
1301 PyString_AS_STRING(co->co_name),
1302 PyObject_REPR(co->co_freevars));
1303 Py_FatalError("compiler_make_closure()");
1304 }
1305 ADDOP_I(c, LOAD_CLOSURE, arg);
1306 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001309 ADDOP_I(c, MAKE_CLOSURE, args);
1310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
1314compiler_decorators(struct compiler *c, asdl_seq* decos)
1315{
1316 int i;
1317
1318 if (!decos)
1319 return 1;
1320
1321 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001322 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 }
1324 return 1;
1325}
1326
1327static int
1328compiler_arguments(struct compiler *c, arguments_ty args)
1329{
1330 int i;
1331 int n = asdl_seq_LEN(args->args);
1332 /* Correctly handle nested argument lists */
1333 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001334 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 if (arg->kind == Tuple_kind) {
1336 PyObject *id = PyString_FromFormat(".%d", i);
1337 if (id == NULL) {
1338 return 0;
1339 }
1340 if (!compiler_nameop(c, id, Load)) {
1341 Py_DECREF(id);
1342 return 0;
1343 }
1344 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001345 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 }
1347 }
1348 return 1;
1349}
1350
1351static int
1352compiler_function(struct compiler *c, stmt_ty s)
1353{
1354 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001355 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 arguments_ty args = s->v.FunctionDef.args;
1357 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001358 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 int i, n, docstring;
1360
1361 assert(s->kind == FunctionDef_kind);
1362
1363 if (!compiler_decorators(c, decos))
1364 return 0;
1365 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001366 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1368 s->lineno))
1369 return 0;
1370
Anthony Baxter7b782b62006-04-11 12:01:56 +00001371 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001372 docstring = compiler_isdocstring(st);
1373 if (docstring)
1374 first_const = st->v.Expr.value->v.Str.s;
1375 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001376 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001377 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001378 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001380 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381 compiler_arguments(c, args);
1382
1383 c->u->u_argcount = asdl_seq_LEN(args->args);
1384 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001385 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001387 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1388 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389 }
1390 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001391 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392 if (co == NULL)
1393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001395 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001396 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397
1398 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1399 ADDOP_I(c, CALL_FUNCTION, 1);
1400 }
1401
1402 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1403}
1404
1405static int
1406compiler_class(struct compiler *c, stmt_ty s)
1407{
1408 int n;
1409 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001410 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411 /* push class name on stack, needed by BUILD_CLASS */
1412 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1413 /* push the tuple of base classes on the stack */
1414 n = asdl_seq_LEN(s->v.ClassDef.bases);
1415 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001416 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417 ADDOP_I(c, BUILD_TUPLE, n);
1418 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1419 s->lineno))
1420 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001421 c->u->u_private = s->v.ClassDef.name;
1422 Py_INCREF(c->u->u_private);
1423 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001424 if (!str || !compiler_nameop(c, str, Load)) {
1425 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001426 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001428 }
1429
1430 Py_DECREF(str);
1431 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432 if (!str || !compiler_nameop(c, str, Store)) {
1433 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001434 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001436 }
1437 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001439 if (!compiler_body(c, s->v.ClassDef.body)) {
1440 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001442 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001444 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1445 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001447 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448 if (co == NULL)
1449 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001451 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001452 Py_DECREF(co);
1453
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 ADDOP_I(c, CALL_FUNCTION, 0);
1455 ADDOP(c, BUILD_CLASS);
1456 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1457 return 0;
1458 return 1;
1459}
1460
1461static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001462compiler_ifexp(struct compiler *c, expr_ty e)
1463{
1464 basicblock *end, *next;
1465
1466 assert(e->kind == IfExp_kind);
1467 end = compiler_new_block(c);
1468 if (end == NULL)
1469 return 0;
1470 next = compiler_new_block(c);
1471 if (next == NULL)
1472 return 0;
1473 VISIT(c, expr, e->v.IfExp.test);
1474 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1475 ADDOP(c, POP_TOP);
1476 VISIT(c, expr, e->v.IfExp.body);
1477 ADDOP_JREL(c, JUMP_FORWARD, end);
1478 compiler_use_next_block(c, next);
1479 ADDOP(c, POP_TOP);
1480 VISIT(c, expr, e->v.IfExp.orelse);
1481 compiler_use_next_block(c, end);
1482 return 1;
1483}
1484
1485static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486compiler_lambda(struct compiler *c, expr_ty e)
1487{
1488 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001489 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490 arguments_ty args = e->v.Lambda.args;
1491 assert(e->kind == Lambda_kind);
1492
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001493 if (!name) {
1494 name = PyString_InternFromString("<lambda>");
1495 if (!name)
1496 return 0;
1497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498
1499 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001500 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1502 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001503
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001504 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505 compiler_arguments(c, args);
1506
1507 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001508 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1509 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001511 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512 if (co == NULL)
1513 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001515 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001516 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517
1518 return 1;
1519}
1520
1521static int
1522compiler_print(struct compiler *c, stmt_ty s)
1523{
1524 int i, n;
1525 bool dest;
1526
1527 assert(s->kind == Print_kind);
1528 n = asdl_seq_LEN(s->v.Print.values);
1529 dest = false;
1530 if (s->v.Print.dest) {
1531 VISIT(c, expr, s->v.Print.dest);
1532 dest = true;
1533 }
1534 for (i = 0; i < n; i++) {
1535 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1536 if (dest) {
1537 ADDOP(c, DUP_TOP);
1538 VISIT(c, expr, e);
1539 ADDOP(c, ROT_TWO);
1540 ADDOP(c, PRINT_ITEM_TO);
1541 }
1542 else {
1543 VISIT(c, expr, e);
1544 ADDOP(c, PRINT_ITEM);
1545 }
1546 }
1547 if (s->v.Print.nl) {
1548 if (dest)
1549 ADDOP(c, PRINT_NEWLINE_TO)
1550 else
1551 ADDOP(c, PRINT_NEWLINE)
1552 }
1553 else if (dest)
1554 ADDOP(c, POP_TOP);
1555 return 1;
1556}
1557
1558static int
1559compiler_if(struct compiler *c, stmt_ty s)
1560{
1561 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001562 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001563 assert(s->kind == If_kind);
1564 end = compiler_new_block(c);
1565 if (end == NULL)
1566 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001567 next = compiler_new_block(c);
1568 if (next == NULL)
1569 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001570
1571 constant = expr_constant(s->v.If.test);
1572 /* constant = 0: "if 0"
1573 * constant = 1: "if 1", "if 2", ...
1574 * constant = -1: rest */
1575 if (constant == 0) {
1576 if (s->v.If.orelse)
1577 VISIT_SEQ(c, stmt, s->v.If.orelse);
1578 } else if (constant == 1) {
1579 VISIT_SEQ(c, stmt, s->v.If.body);
1580 } else {
1581 VISIT(c, expr, s->v.If.test);
1582 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1583 ADDOP(c, POP_TOP);
1584 VISIT_SEQ(c, stmt, s->v.If.body);
1585 ADDOP_JREL(c, JUMP_FORWARD, end);
1586 compiler_use_next_block(c, next);
1587 ADDOP(c, POP_TOP);
1588 if (s->v.If.orelse)
1589 VISIT_SEQ(c, stmt, s->v.If.orelse);
1590 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591 compiler_use_next_block(c, end);
1592 return 1;
1593}
1594
1595static int
1596compiler_for(struct compiler *c, stmt_ty s)
1597{
1598 basicblock *start, *cleanup, *end;
1599
1600 start = compiler_new_block(c);
1601 cleanup = compiler_new_block(c);
1602 end = compiler_new_block(c);
1603 if (start == NULL || end == NULL || cleanup == NULL)
1604 return 0;
1605 ADDOP_JREL(c, SETUP_LOOP, end);
1606 if (!compiler_push_fblock(c, LOOP, start))
1607 return 0;
1608 VISIT(c, expr, s->v.For.iter);
1609 ADDOP(c, GET_ITER);
1610 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001611 /* XXX(nnorwitz): is there a better way to handle this?
1612 for loops are special, we want to be able to trace them
1613 each time around, so we need to set an extra line number. */
1614 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615 ADDOP_JREL(c, FOR_ITER, cleanup);
1616 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001617 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1619 compiler_use_next_block(c, cleanup);
1620 ADDOP(c, POP_BLOCK);
1621 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001622 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001623 compiler_use_next_block(c, end);
1624 return 1;
1625}
1626
1627static int
1628compiler_while(struct compiler *c, stmt_ty s)
1629{
1630 basicblock *loop, *orelse, *end, *anchor = NULL;
1631 int constant = expr_constant(s->v.While.test);
1632
1633 if (constant == 0)
1634 return 1;
1635 loop = compiler_new_block(c);
1636 end = compiler_new_block(c);
1637 if (constant == -1) {
1638 anchor = compiler_new_block(c);
1639 if (anchor == NULL)
1640 return 0;
1641 }
1642 if (loop == NULL || end == NULL)
1643 return 0;
1644 if (s->v.While.orelse) {
1645 orelse = compiler_new_block(c);
1646 if (orelse == NULL)
1647 return 0;
1648 }
1649 else
1650 orelse = NULL;
1651
1652 ADDOP_JREL(c, SETUP_LOOP, end);
1653 compiler_use_next_block(c, loop);
1654 if (!compiler_push_fblock(c, LOOP, loop))
1655 return 0;
1656 if (constant == -1) {
1657 VISIT(c, expr, s->v.While.test);
1658 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1659 ADDOP(c, POP_TOP);
1660 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001661 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1663
1664 /* XXX should the two POP instructions be in a separate block
1665 if there is no else clause ?
1666 */
1667
1668 if (constant == -1) {
1669 compiler_use_next_block(c, anchor);
1670 ADDOP(c, POP_TOP);
1671 ADDOP(c, POP_BLOCK);
1672 }
1673 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001674 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001675 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676 compiler_use_next_block(c, end);
1677
1678 return 1;
1679}
1680
1681static int
1682compiler_continue(struct compiler *c)
1683{
1684 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1685 int i;
1686
1687 if (!c->u->u_nfblocks)
1688 return compiler_error(c, LOOP_ERROR_MSG);
1689 i = c->u->u_nfblocks - 1;
1690 switch (c->u->u_fblock[i].fb_type) {
1691 case LOOP:
1692 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1693 break;
1694 case EXCEPT:
1695 case FINALLY_TRY:
1696 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1697 ;
1698 if (i == -1)
1699 return compiler_error(c, LOOP_ERROR_MSG);
1700 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1701 break;
1702 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001703 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 "'continue' not supported inside 'finally' clause");
1705 }
1706
1707 return 1;
1708}
1709
1710/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1711
1712 SETUP_FINALLY L
1713 <code for body>
1714 POP_BLOCK
1715 LOAD_CONST <None>
1716 L: <code for finalbody>
1717 END_FINALLY
1718
1719 The special instructions use the block stack. Each block
1720 stack entry contains the instruction that created it (here
1721 SETUP_FINALLY), the level of the value stack at the time the
1722 block stack entry was created, and a label (here L).
1723
1724 SETUP_FINALLY:
1725 Pushes the current value stack level and the label
1726 onto the block stack.
1727 POP_BLOCK:
1728 Pops en entry from the block stack, and pops the value
1729 stack until its level is the same as indicated on the
1730 block stack. (The label is ignored.)
1731 END_FINALLY:
1732 Pops a variable number of entries from the *value* stack
1733 and re-raises the exception they specify. The number of
1734 entries popped depends on the (pseudo) exception type.
1735
1736 The block stack is unwound when an exception is raised:
1737 when a SETUP_FINALLY entry is found, the exception is pushed
1738 onto the value stack (and the exception condition is cleared),
1739 and the interpreter jumps to the label gotten from the block
1740 stack.
1741*/
1742
1743static int
1744compiler_try_finally(struct compiler *c, stmt_ty s)
1745{
1746 basicblock *body, *end;
1747 body = compiler_new_block(c);
1748 end = compiler_new_block(c);
1749 if (body == NULL || end == NULL)
1750 return 0;
1751
1752 ADDOP_JREL(c, SETUP_FINALLY, end);
1753 compiler_use_next_block(c, body);
1754 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1755 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001756 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757 ADDOP(c, POP_BLOCK);
1758 compiler_pop_fblock(c, FINALLY_TRY, body);
1759
1760 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1761 compiler_use_next_block(c, end);
1762 if (!compiler_push_fblock(c, FINALLY_END, end))
1763 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001764 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765 ADDOP(c, END_FINALLY);
1766 compiler_pop_fblock(c, FINALLY_END, end);
1767
1768 return 1;
1769}
1770
1771/*
1772 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1773 (The contents of the value stack is shown in [], with the top
1774 at the right; 'tb' is trace-back info, 'val' the exception's
1775 associated value, and 'exc' the exception.)
1776
1777 Value stack Label Instruction Argument
1778 [] SETUP_EXCEPT L1
1779 [] <code for S>
1780 [] POP_BLOCK
1781 [] JUMP_FORWARD L0
1782
1783 [tb, val, exc] L1: DUP )
1784 [tb, val, exc, exc] <evaluate E1> )
1785 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1786 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1787 [tb, val, exc, 1] POP )
1788 [tb, val, exc] POP
1789 [tb, val] <assign to V1> (or POP if no V1)
1790 [tb] POP
1791 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001792 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793
1794 [tb, val, exc, 0] L2: POP
1795 [tb, val, exc] DUP
1796 .............................etc.......................
1797
1798 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001799 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
1801 [] L0: <next statement>
1802
1803 Of course, parts are not generated if Vi or Ei is not present.
1804*/
1805static int
1806compiler_try_except(struct compiler *c, stmt_ty s)
1807{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001808 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 int i, n;
1810
1811 body = compiler_new_block(c);
1812 except = compiler_new_block(c);
1813 orelse = compiler_new_block(c);
1814 end = compiler_new_block(c);
1815 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1816 return 0;
1817 ADDOP_JREL(c, SETUP_EXCEPT, except);
1818 compiler_use_next_block(c, body);
1819 if (!compiler_push_fblock(c, EXCEPT, body))
1820 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001821 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822 ADDOP(c, POP_BLOCK);
1823 compiler_pop_fblock(c, EXCEPT, body);
1824 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1825 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1826 compiler_use_next_block(c, except);
1827 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001828 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 s->v.TryExcept.handlers, i);
1830 if (!handler->type && i < n-1)
1831 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00001832 c->u->u_lineno_set = false;
1833 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 except = compiler_new_block(c);
1835 if (except == NULL)
1836 return 0;
1837 if (handler->type) {
1838 ADDOP(c, DUP_TOP);
1839 VISIT(c, expr, handler->type);
1840 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1841 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1842 ADDOP(c, POP_TOP);
1843 }
1844 ADDOP(c, POP_TOP);
1845 if (handler->name) {
1846 VISIT(c, expr, handler->name);
1847 }
1848 else {
1849 ADDOP(c, POP_TOP);
1850 }
1851 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001852 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 ADDOP_JREL(c, JUMP_FORWARD, end);
1854 compiler_use_next_block(c, except);
1855 if (handler->type)
1856 ADDOP(c, POP_TOP);
1857 }
1858 ADDOP(c, END_FINALLY);
1859 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001860 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 compiler_use_next_block(c, end);
1862 return 1;
1863}
1864
1865static int
1866compiler_import_as(struct compiler *c, identifier name, identifier asname)
1867{
1868 /* The IMPORT_NAME opcode was already generated. This function
1869 merely needs to bind the result to a name.
1870
1871 If there is a dot in name, we need to split it and emit a
1872 LOAD_ATTR for each name.
1873 */
1874 const char *src = PyString_AS_STRING(name);
1875 const char *dot = strchr(src, '.');
1876 if (dot) {
1877 /* Consume the base module name to get the first attribute */
1878 src = dot + 1;
1879 while (dot) {
1880 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001881 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001883 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001885 if (!attr)
1886 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001888 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889 src = dot + 1;
1890 }
1891 }
1892 return compiler_nameop(c, asname, Store);
1893}
1894
1895static int
1896compiler_import(struct compiler *c, stmt_ty s)
1897{
1898 /* The Import node stores a module name like a.b.c as a single
1899 string. This is convenient for all cases except
1900 import a.b.c as d
1901 where we need to parse that string to extract the individual
1902 module names.
1903 XXX Perhaps change the representation to make this case simpler?
1904 */
1905 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001906
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001908 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001910 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911
Neal Norwitzcbce2802006-04-03 06:26:32 +00001912 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001913 level = PyInt_FromLong(0);
1914 else
1915 level = PyInt_FromLong(-1);
1916
1917 if (level == NULL)
1918 return 0;
1919
1920 ADDOP_O(c, LOAD_CONST, level, consts);
1921 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1923 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1924
1925 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001926 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001927 if (!r)
1928 return r;
1929 }
1930 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 identifier tmp = alias->name;
1932 const char *base = PyString_AS_STRING(alias->name);
1933 char *dot = strchr(base, '.');
1934 if (dot)
1935 tmp = PyString_FromStringAndSize(base,
1936 dot - base);
1937 r = compiler_nameop(c, tmp, Store);
1938 if (dot) {
1939 Py_DECREF(tmp);
1940 }
1941 if (!r)
1942 return r;
1943 }
1944 }
1945 return 1;
1946}
1947
1948static int
1949compiler_from_import(struct compiler *c, stmt_ty s)
1950{
1951 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952
1953 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001954 PyObject *level;
1955
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 if (!names)
1957 return 0;
1958
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001959 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001960 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001961 level = PyInt_FromLong(-1);
1962 else
1963 level = PyInt_FromLong(s->v.ImportFrom.level);
1964
1965 if (!level) {
1966 Py_DECREF(names);
1967 return 0;
1968 }
1969
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970 /* build up the names */
1971 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001972 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973 Py_INCREF(alias->name);
1974 PyTuple_SET_ITEM(names, i, alias->name);
1975 }
1976
1977 if (s->lineno > c->c_future->ff_lineno) {
1978 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1979 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001980 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981 Py_DECREF(names);
1982 return compiler_error(c,
1983 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001984 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985
1986 }
1987 }
1988
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001989 ADDOP_O(c, LOAD_CONST, level, consts);
1990 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001992 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1994 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001995 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996 identifier store_name;
1997
1998 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1999 assert(n == 1);
2000 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002001 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 }
2003
2004 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2005 store_name = alias->name;
2006 if (alias->asname)
2007 store_name = alias->asname;
2008
2009 if (!compiler_nameop(c, store_name, Store)) {
2010 Py_DECREF(names);
2011 return 0;
2012 }
2013 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002014 /* remove imported module */
2015 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016 return 1;
2017}
2018
2019static int
2020compiler_assert(struct compiler *c, stmt_ty s)
2021{
2022 static PyObject *assertion_error = NULL;
2023 basicblock *end;
2024
2025 if (Py_OptimizeFlag)
2026 return 1;
2027 if (assertion_error == NULL) {
2028 assertion_error = PyString_FromString("AssertionError");
2029 if (assertion_error == NULL)
2030 return 0;
2031 }
2032 VISIT(c, expr, s->v.Assert.test);
2033 end = compiler_new_block(c);
2034 if (end == NULL)
2035 return 0;
2036 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2037 ADDOP(c, POP_TOP);
2038 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2039 if (s->v.Assert.msg) {
2040 VISIT(c, expr, s->v.Assert.msg);
2041 ADDOP_I(c, RAISE_VARARGS, 2);
2042 }
2043 else {
2044 ADDOP_I(c, RAISE_VARARGS, 1);
2045 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002046 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 ADDOP(c, POP_TOP);
2048 return 1;
2049}
2050
2051static int
2052compiler_visit_stmt(struct compiler *c, stmt_ty s)
2053{
2054 int i, n;
2055
Jeremy Hylton12603c42006-04-01 16:18:02 +00002056 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 c->u->u_lineno = s->lineno;
2058 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002061 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002063 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002065 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 if (c->u->u_ste->ste_type != FunctionBlock)
2067 return compiler_error(c, "'return' outside function");
2068 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069 VISIT(c, expr, s->v.Return.value);
2070 }
2071 else
2072 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2073 ADDOP(c, RETURN_VALUE);
2074 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002075 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002076 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002078 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 n = asdl_seq_LEN(s->v.Assign.targets);
2080 VISIT(c, expr, s->v.Assign.value);
2081 for (i = 0; i < n; i++) {
2082 if (i < n - 1)
2083 ADDOP(c, DUP_TOP);
2084 VISIT(c, expr,
2085 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2086 }
2087 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002088 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002090 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002092 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002094 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002096 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002098 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 n = 0;
2100 if (s->v.Raise.type) {
2101 VISIT(c, expr, s->v.Raise.type);
2102 n++;
2103 if (s->v.Raise.inst) {
2104 VISIT(c, expr, s->v.Raise.inst);
2105 n++;
2106 if (s->v.Raise.tback) {
2107 VISIT(c, expr, s->v.Raise.tback);
2108 n++;
2109 }
2110 }
2111 }
2112 ADDOP_I(c, RAISE_VARARGS, n);
2113 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002114 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002116 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002118 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002120 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002122 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002124 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125 VISIT(c, expr, s->v.Exec.body);
2126 if (s->v.Exec.globals) {
2127 VISIT(c, expr, s->v.Exec.globals);
2128 if (s->v.Exec.locals) {
2129 VISIT(c, expr, s->v.Exec.locals);
2130 } else {
2131 ADDOP(c, DUP_TOP);
2132 }
2133 } else {
2134 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2135 ADDOP(c, DUP_TOP);
2136 }
2137 ADDOP(c, EXEC_STMT);
2138 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002139 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002141 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002142 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002143 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 ADDOP(c, PRINT_EXPR);
2145 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002146 else if (s->v.Expr.value->kind != Str_kind &&
2147 s->v.Expr.value->kind != Num_kind) {
2148 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 ADDOP(c, POP_TOP);
2150 }
2151 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002152 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002154 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 if (!c->u->u_nfblocks)
2156 return compiler_error(c, "'break' outside loop");
2157 ADDOP(c, BREAK_LOOP);
2158 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002159 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002161 case With_kind:
2162 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 }
2164 return 1;
2165}
2166
2167static int
2168unaryop(unaryop_ty op)
2169{
2170 switch (op) {
2171 case Invert:
2172 return UNARY_INVERT;
2173 case Not:
2174 return UNARY_NOT;
2175 case UAdd:
2176 return UNARY_POSITIVE;
2177 case USub:
2178 return UNARY_NEGATIVE;
2179 }
2180 return 0;
2181}
2182
2183static int
2184binop(struct compiler *c, operator_ty op)
2185{
2186 switch (op) {
2187 case Add:
2188 return BINARY_ADD;
2189 case Sub:
2190 return BINARY_SUBTRACT;
2191 case Mult:
2192 return BINARY_MULTIPLY;
2193 case Div:
2194 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2195 return BINARY_TRUE_DIVIDE;
2196 else
2197 return BINARY_DIVIDE;
2198 case Mod:
2199 return BINARY_MODULO;
2200 case Pow:
2201 return BINARY_POWER;
2202 case LShift:
2203 return BINARY_LSHIFT;
2204 case RShift:
2205 return BINARY_RSHIFT;
2206 case BitOr:
2207 return BINARY_OR;
2208 case BitXor:
2209 return BINARY_XOR;
2210 case BitAnd:
2211 return BINARY_AND;
2212 case FloorDiv:
2213 return BINARY_FLOOR_DIVIDE;
2214 }
2215 return 0;
2216}
2217
2218static int
2219cmpop(cmpop_ty op)
2220{
2221 switch (op) {
2222 case Eq:
2223 return PyCmp_EQ;
2224 case NotEq:
2225 return PyCmp_NE;
2226 case Lt:
2227 return PyCmp_LT;
2228 case LtE:
2229 return PyCmp_LE;
2230 case Gt:
2231 return PyCmp_GT;
2232 case GtE:
2233 return PyCmp_GE;
2234 case Is:
2235 return PyCmp_IS;
2236 case IsNot:
2237 return PyCmp_IS_NOT;
2238 case In:
2239 return PyCmp_IN;
2240 case NotIn:
2241 return PyCmp_NOT_IN;
2242 }
2243 return PyCmp_BAD;
2244}
2245
2246static int
2247inplace_binop(struct compiler *c, operator_ty op)
2248{
2249 switch (op) {
2250 case Add:
2251 return INPLACE_ADD;
2252 case Sub:
2253 return INPLACE_SUBTRACT;
2254 case Mult:
2255 return INPLACE_MULTIPLY;
2256 case Div:
2257 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2258 return INPLACE_TRUE_DIVIDE;
2259 else
2260 return INPLACE_DIVIDE;
2261 case Mod:
2262 return INPLACE_MODULO;
2263 case Pow:
2264 return INPLACE_POWER;
2265 case LShift:
2266 return INPLACE_LSHIFT;
2267 case RShift:
2268 return INPLACE_RSHIFT;
2269 case BitOr:
2270 return INPLACE_OR;
2271 case BitXor:
2272 return INPLACE_XOR;
2273 case BitAnd:
2274 return INPLACE_AND;
2275 case FloorDiv:
2276 return INPLACE_FLOOR_DIVIDE;
2277 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002278 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002279 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 return 0;
2281}
2282
2283static int
2284compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2285{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002286 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2288
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002289 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002290 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 /* XXX AugStore isn't used anywhere! */
2292
2293 /* First check for assignment to __debug__. Param? */
2294 if ((ctx == Store || ctx == AugStore || ctx == Del)
2295 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2296 return compiler_error(c, "can not assign to __debug__");
2297 }
2298
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002299 mangled = _Py_Mangle(c->u->u_private, name);
2300 if (!mangled)
2301 return 0;
2302
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303 op = 0;
2304 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002305 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 switch (scope) {
2307 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002308 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 optype = OP_DEREF;
2310 break;
2311 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002312 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 optype = OP_DEREF;
2314 break;
2315 case LOCAL:
2316 if (c->u->u_ste->ste_type == FunctionBlock)
2317 optype = OP_FAST;
2318 break;
2319 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002320 if (c->u->u_ste->ste_type == FunctionBlock &&
2321 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322 optype = OP_GLOBAL;
2323 break;
2324 case GLOBAL_EXPLICIT:
2325 optype = OP_GLOBAL;
2326 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002327 default:
2328 /* scope can be 0 */
2329 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 }
2331
2332 /* XXX Leave assert here, but handle __doc__ and the like better */
2333 assert(scope || PyString_AS_STRING(name)[0] == '_');
2334
2335 switch (optype) {
2336 case OP_DEREF:
2337 switch (ctx) {
2338 case Load: op = LOAD_DEREF; break;
2339 case Store: op = STORE_DEREF; break;
2340 case AugLoad:
2341 case AugStore:
2342 break;
2343 case Del:
2344 PyErr_Format(PyExc_SyntaxError,
2345 "can not delete variable '%s' referenced "
2346 "in nested scope",
2347 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002348 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002351 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002352 PyErr_SetString(PyExc_SystemError,
2353 "param invalid for deref variable");
2354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 }
2356 break;
2357 case OP_FAST:
2358 switch (ctx) {
2359 case Load: op = LOAD_FAST; break;
2360 case Store: op = STORE_FAST; break;
2361 case Del: op = DELETE_FAST; break;
2362 case AugLoad:
2363 case AugStore:
2364 break;
2365 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002366 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002367 PyErr_SetString(PyExc_SystemError,
2368 "param invalid for local variable");
2369 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002371 ADDOP_O(c, op, mangled, varnames);
2372 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002373 return 1;
2374 case OP_GLOBAL:
2375 switch (ctx) {
2376 case Load: op = LOAD_GLOBAL; break;
2377 case Store: op = STORE_GLOBAL; break;
2378 case Del: op = DELETE_GLOBAL; break;
2379 case AugLoad:
2380 case AugStore:
2381 break;
2382 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002383 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002384 PyErr_SetString(PyExc_SystemError,
2385 "param invalid for global variable");
2386 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387 }
2388 break;
2389 case OP_NAME:
2390 switch (ctx) {
2391 case Load: op = LOAD_NAME; break;
2392 case Store: op = STORE_NAME; break;
2393 case Del: op = DELETE_NAME; break;
2394 case AugLoad:
2395 case AugStore:
2396 break;
2397 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002398 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002399 PyErr_SetString(PyExc_SystemError,
2400 "param invalid for name variable");
2401 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002402 }
2403 break;
2404 }
2405
2406 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002407 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002408 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002409 if (arg < 0)
2410 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002411 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412}
2413
2414static int
2415compiler_boolop(struct compiler *c, expr_ty e)
2416{
2417 basicblock *end;
2418 int jumpi, i, n;
2419 asdl_seq *s;
2420
2421 assert(e->kind == BoolOp_kind);
2422 if (e->v.BoolOp.op == And)
2423 jumpi = JUMP_IF_FALSE;
2424 else
2425 jumpi = JUMP_IF_TRUE;
2426 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002427 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 return 0;
2429 s = e->v.BoolOp.values;
2430 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002431 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002433 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002434 ADDOP_JREL(c, jumpi, end);
2435 ADDOP(c, POP_TOP)
2436 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002437 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438 compiler_use_next_block(c, end);
2439 return 1;
2440}
2441
2442static int
2443compiler_list(struct compiler *c, expr_ty e)
2444{
2445 int n = asdl_seq_LEN(e->v.List.elts);
2446 if (e->v.List.ctx == Store) {
2447 ADDOP_I(c, UNPACK_SEQUENCE, n);
2448 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002449 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 if (e->v.List.ctx == Load) {
2451 ADDOP_I(c, BUILD_LIST, n);
2452 }
2453 return 1;
2454}
2455
2456static int
2457compiler_tuple(struct compiler *c, expr_ty e)
2458{
2459 int n = asdl_seq_LEN(e->v.Tuple.elts);
2460 if (e->v.Tuple.ctx == Store) {
2461 ADDOP_I(c, UNPACK_SEQUENCE, n);
2462 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002463 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 if (e->v.Tuple.ctx == Load) {
2465 ADDOP_I(c, BUILD_TUPLE, n);
2466 }
2467 return 1;
2468}
2469
2470static int
2471compiler_compare(struct compiler *c, expr_ty e)
2472{
2473 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002474 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475
2476 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2477 VISIT(c, expr, e->v.Compare.left);
2478 n = asdl_seq_LEN(e->v.Compare.ops);
2479 assert(n > 0);
2480 if (n > 1) {
2481 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002482 if (cleanup == NULL)
2483 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002484 VISIT(c, expr,
2485 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 }
2487 for (i = 1; i < n; i++) {
2488 ADDOP(c, DUP_TOP);
2489 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002491 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00002492 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2494 NEXT_BLOCK(c);
2495 ADDOP(c, POP_TOP);
2496 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002497 VISIT(c, expr,
2498 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002500 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002502 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503 if (n > 1) {
2504 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002505 if (end == NULL)
2506 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 ADDOP_JREL(c, JUMP_FORWARD, end);
2508 compiler_use_next_block(c, cleanup);
2509 ADDOP(c, ROT_TWO);
2510 ADDOP(c, POP_TOP);
2511 compiler_use_next_block(c, end);
2512 }
2513 return 1;
2514}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00002515#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516
2517static int
2518compiler_call(struct compiler *c, expr_ty e)
2519{
2520 int n, code = 0;
2521
2522 VISIT(c, expr, e->v.Call.func);
2523 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002524 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002526 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2528 }
2529 if (e->v.Call.starargs) {
2530 VISIT(c, expr, e->v.Call.starargs);
2531 code |= 1;
2532 }
2533 if (e->v.Call.kwargs) {
2534 VISIT(c, expr, e->v.Call.kwargs);
2535 code |= 2;
2536 }
2537 switch (code) {
2538 case 0:
2539 ADDOP_I(c, CALL_FUNCTION, n);
2540 break;
2541 case 1:
2542 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2543 break;
2544 case 2:
2545 ADDOP_I(c, CALL_FUNCTION_KW, n);
2546 break;
2547 case 3:
2548 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2549 break;
2550 }
2551 return 1;
2552}
2553
2554static int
2555compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002556 asdl_seq *generators, int gen_index,
2557 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558{
2559 /* generate code for the iterator, then each of the ifs,
2560 and then write to the element */
2561
2562 comprehension_ty l;
2563 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002564 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565
2566 start = compiler_new_block(c);
2567 skip = compiler_new_block(c);
2568 if_cleanup = compiler_new_block(c);
2569 anchor = compiler_new_block(c);
2570
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002571 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2572 anchor == NULL)
2573 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574
Anthony Baxter7b782b62006-04-11 12:01:56 +00002575 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576 VISIT(c, expr, l->iter);
2577 ADDOP(c, GET_ITER);
2578 compiler_use_next_block(c, start);
2579 ADDOP_JREL(c, FOR_ITER, anchor);
2580 NEXT_BLOCK(c);
2581 VISIT(c, expr, l->target);
2582
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584 n = asdl_seq_LEN(l->ifs);
2585 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002586 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587 VISIT(c, expr, e);
2588 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2589 NEXT_BLOCK(c);
2590 ADDOP(c, POP_TOP);
2591 }
2592
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002593 if (++gen_index < asdl_seq_LEN(generators))
2594 if (!compiler_listcomp_generator(c, tmpname,
2595 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002598 /* only append after the last for generator */
2599 if (gen_index >= asdl_seq_LEN(generators)) {
2600 if (!compiler_nameop(c, tmpname, Load))
2601 return 0;
2602 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002603 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002604
2605 compiler_use_next_block(c, skip);
2606 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607 for (i = 0; i < n; i++) {
2608 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002609 if (i == 0)
2610 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 ADDOP(c, POP_TOP);
2612 }
2613 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2614 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002615 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002617 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 return 0;
2619
2620 return 1;
2621}
2622
2623static int
2624compiler_listcomp(struct compiler *c, expr_ty e)
2625{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002627 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628 static identifier append;
2629 asdl_seq *generators = e->v.ListComp.generators;
2630
2631 assert(e->kind == ListComp_kind);
2632 if (!append) {
2633 append = PyString_InternFromString("append");
2634 if (!append)
2635 return 0;
2636 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002637 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 if (!tmp)
2639 return 0;
2640 ADDOP_I(c, BUILD_LIST, 0);
2641 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002643 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2644 e->v.ListComp.elt);
2645 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 return rc;
2647}
2648
2649static int
2650compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 asdl_seq *generators, int gen_index,
2652 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653{
2654 /* generate code for the iterator, then each of the ifs,
2655 and then write to the element */
2656
2657 comprehension_ty ge;
2658 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660
2661 start = compiler_new_block(c);
2662 skip = compiler_new_block(c);
2663 if_cleanup = compiler_new_block(c);
2664 anchor = compiler_new_block(c);
2665 end = compiler_new_block(c);
2666
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 anchor == NULL || end == NULL)
2669 return 0;
2670
Anthony Baxter7b782b62006-04-11 12:01:56 +00002671 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 ADDOP_JREL(c, SETUP_LOOP, end);
2673 if (!compiler_push_fblock(c, LOOP, start))
2674 return 0;
2675
2676 if (gen_index == 0) {
2677 /* Receive outermost iter as an implicit argument */
2678 c->u->u_argcount = 1;
2679 ADDOP_I(c, LOAD_FAST, 0);
2680 }
2681 else {
2682 /* Sub-iter - calculate on the fly */
2683 VISIT(c, expr, ge->iter);
2684 ADDOP(c, GET_ITER);
2685 }
2686 compiler_use_next_block(c, start);
2687 ADDOP_JREL(c, FOR_ITER, anchor);
2688 NEXT_BLOCK(c);
2689 VISIT(c, expr, ge->target);
2690
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002691 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 n = asdl_seq_LEN(ge->ifs);
2693 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002694 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695 VISIT(c, expr, e);
2696 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2697 NEXT_BLOCK(c);
2698 ADDOP(c, POP_TOP);
2699 }
2700
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002701 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2703 return 0;
2704
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002705 /* only append after the last 'for' generator */
2706 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 VISIT(c, expr, elt);
2708 ADDOP(c, YIELD_VALUE);
2709 ADDOP(c, POP_TOP);
2710
2711 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713 for (i = 0; i < n; i++) {
2714 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002715 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 compiler_use_next_block(c, if_cleanup);
2717
2718 ADDOP(c, POP_TOP);
2719 }
2720 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2721 compiler_use_next_block(c, anchor);
2722 ADDOP(c, POP_BLOCK);
2723 compiler_pop_fblock(c, LOOP, start);
2724 compiler_use_next_block(c, end);
2725
2726 return 1;
2727}
2728
2729static int
2730compiler_genexp(struct compiler *c, expr_ty e)
2731{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002732 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 PyCodeObject *co;
2734 expr_ty outermost_iter = ((comprehension_ty)
2735 (asdl_seq_GET(e->v.GeneratorExp.generators,
2736 0)))->iter;
2737
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002738 if (!name) {
2739 name = PyString_FromString("<genexpr>");
2740 if (!name)
2741 return 0;
2742 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743
2744 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2745 return 0;
2746 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2747 e->v.GeneratorExp.elt);
2748 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002749 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750 if (co == NULL)
2751 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002753 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002754 Py_DECREF(co);
2755
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756 VISIT(c, expr, outermost_iter);
2757 ADDOP(c, GET_ITER);
2758 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759
2760 return 1;
2761}
2762
2763static int
2764compiler_visit_keyword(struct compiler *c, keyword_ty k)
2765{
2766 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2767 VISIT(c, expr, k->value);
2768 return 1;
2769}
2770
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002771/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772 whether they are true or false.
2773
2774 Return values: 1 for true, 0 for false, -1 for non-constant.
2775 */
2776
2777static int
2778expr_constant(expr_ty e)
2779{
2780 switch (e->kind) {
2781 case Num_kind:
2782 return PyObject_IsTrue(e->v.Num.n);
2783 case Str_kind:
2784 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002785 case Name_kind:
2786 /* __debug__ is not assignable, so we can optimize
2787 * it away in if and while statements */
2788 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2789 "__debug__") == 0)
2790 return ! Py_OptimizeFlag;
2791 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792 default:
2793 return -1;
2794 }
2795}
2796
Guido van Rossumc2e20742006-02-27 22:32:47 +00002797/*
2798 Implements the with statement from PEP 343.
2799
2800 The semantics outlined in that PEP are as follows:
2801
2802 with EXPR as VAR:
2803 BLOCK
2804
2805 It is implemented roughly as:
2806
Guido van Rossumda5b7012006-05-02 19:47:52 +00002807 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002808 exit = context.__exit__ # not calling it
2809 value = context.__enter__()
2810 try:
2811 VAR = value # if VAR present in the syntax
2812 BLOCK
2813 finally:
2814 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002816 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002817 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002818 exit(*exc)
2819 */
2820static int
2821compiler_with(struct compiler *c, stmt_ty s)
2822{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002823 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002824 basicblock *block, *finally;
2825 identifier tmpexit, tmpvalue = NULL;
2826
2827 assert(s->kind == With_kind);
2828
Guido van Rossumc2e20742006-02-27 22:32:47 +00002829 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002830 enter_attr = PyString_InternFromString("__enter__");
2831 if (!enter_attr)
2832 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002833 }
2834 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002835 exit_attr = PyString_InternFromString("__exit__");
2836 if (!exit_attr)
2837 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002838 }
2839
2840 block = compiler_new_block(c);
2841 finally = compiler_new_block(c);
2842 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002843 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002844
2845 /* Create a temporary variable to hold context.__exit__ */
2846 tmpexit = compiler_new_tmpname(c);
2847 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002848 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002849 PyArena_AddPyObject(c->c_arena, tmpexit);
2850
2851 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002852 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002853 We need to do this rather than preserving it on the stack
2854 because SETUP_FINALLY remembers the stack level.
2855 We need to do the assignment *inside* the try/finally
2856 so that context.__exit__() is called when the assignment
2857 fails. But we need to call context.__enter__() *before*
2858 the try/finally so that if it fails we won't call
2859 context.__exit__().
2860 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002861 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002862 if (tmpvalue == NULL)
2863 return 0;
2864 PyArena_AddPyObject(c->c_arena, tmpvalue);
2865 }
2866
Guido van Rossumda5b7012006-05-02 19:47:52 +00002867 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002868 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869
2870 /* Squirrel away context.__exit__ */
2871 ADDOP(c, DUP_TOP);
2872 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2873 if (!compiler_nameop(c, tmpexit, Store))
2874 return 0;
2875
2876 /* Call context.__enter__() */
2877 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2878 ADDOP_I(c, CALL_FUNCTION, 0);
2879
2880 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002881 /* Store it in tmpvalue */
2882 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002883 return 0;
2884 }
2885 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002886 /* Discard result from context.__enter__() */
2887 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002888 }
2889
2890 /* Start the try block */
2891 ADDOP_JREL(c, SETUP_FINALLY, finally);
2892
2893 compiler_use_next_block(c, block);
2894 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002895 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002896 }
2897
2898 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002899 /* Bind saved result of context.__enter__() to VAR */
2900 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002901 !compiler_nameop(c, tmpvalue, Del))
2902 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002903 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002904 }
2905
2906 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002907 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908
2909 /* End of try block; start the finally block */
2910 ADDOP(c, POP_BLOCK);
2911 compiler_pop_fblock(c, FINALLY_TRY, block);
2912
2913 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2914 compiler_use_next_block(c, finally);
2915 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002916 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002917
2918 /* Finally block starts; push tmpexit and issue our magic opcode. */
2919 if (!compiler_nameop(c, tmpexit, Load) ||
2920 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002921 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002922 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002923
2924 /* Finally block ends. */
2925 ADDOP(c, END_FINALLY);
2926 compiler_pop_fblock(c, FINALLY_END, finally);
2927 return 1;
2928}
2929
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930static int
2931compiler_visit_expr(struct compiler *c, expr_ty e)
2932{
2933 int i, n;
2934
Jeremy Hylton12603c42006-04-01 16:18:02 +00002935 /* If expr e has a different line number than the last expr/stmt,
2936 set a new line number for the next instruction.
2937 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 if (e->lineno > c->u->u_lineno) {
2939 c->u->u_lineno = e->lineno;
2940 c->u->u_lineno_set = false;
2941 }
2942 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002943 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002945 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946 VISIT(c, expr, e->v.BinOp.left);
2947 VISIT(c, expr, e->v.BinOp.right);
2948 ADDOP(c, binop(c, e->v.BinOp.op));
2949 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002950 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 VISIT(c, expr, e->v.UnaryOp.operand);
2952 ADDOP(c, unaryop(e->v.UnaryOp.op));
2953 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002954 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002956 case IfExp_kind:
2957 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002958 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959 /* XXX get rid of arg? */
2960 ADDOP_I(c, BUILD_MAP, 0);
2961 n = asdl_seq_LEN(e->v.Dict.values);
2962 /* We must arrange things just right for STORE_SUBSCR.
2963 It wants the stack to look like (value) (dict) (key) */
2964 for (i = 0; i < n; i++) {
2965 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002966 VISIT(c, expr,
2967 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002969 VISIT(c, expr,
2970 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 ADDOP(c, STORE_SUBSCR);
2972 }
2973 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002974 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002976 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977 return compiler_genexp(c, e);
2978 case Yield_kind:
2979 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002980 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002981 /*
2982 for (i = 0; i < c->u->u_nfblocks; i++) {
2983 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2984 return compiler_error(
2985 c, "'yield' not allowed in a 'try' "
2986 "block with a 'finally' clause");
2987 }
2988 */
2989 if (e->v.Yield.value) {
2990 VISIT(c, expr, e->v.Yield.value);
2991 }
2992 else {
2993 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2994 }
2995 ADDOP(c, YIELD_VALUE);
2996 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002997 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002999 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003000 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003001 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003002 VISIT(c, expr, e->v.Repr.value);
3003 ADDOP(c, UNARY_CONVERT);
3004 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003005 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3007 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003008 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3010 break;
3011 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003012 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013 if (e->v.Attribute.ctx != AugStore)
3014 VISIT(c, expr, e->v.Attribute.value);
3015 switch (e->v.Attribute.ctx) {
3016 case AugLoad:
3017 ADDOP(c, DUP_TOP);
3018 /* Fall through to load */
3019 case Load:
3020 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3021 break;
3022 case AugStore:
3023 ADDOP(c, ROT_TWO);
3024 /* Fall through to save */
3025 case Store:
3026 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3027 break;
3028 case Del:
3029 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3030 break;
3031 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003032 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003033 PyErr_SetString(PyExc_SystemError,
3034 "param invalid in attribute expression");
3035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036 }
3037 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003038 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039 switch (e->v.Subscript.ctx) {
3040 case AugLoad:
3041 VISIT(c, expr, e->v.Subscript.value);
3042 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3043 break;
3044 case Load:
3045 VISIT(c, expr, e->v.Subscript.value);
3046 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3047 break;
3048 case AugStore:
3049 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3050 break;
3051 case Store:
3052 VISIT(c, expr, e->v.Subscript.value);
3053 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3054 break;
3055 case Del:
3056 VISIT(c, expr, e->v.Subscript.value);
3057 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3058 break;
3059 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003060 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003061 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003062 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003063 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064 }
3065 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003066 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3068 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003069 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003070 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003071 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072 return compiler_tuple(c, e);
3073 }
3074 return 1;
3075}
3076
3077static int
3078compiler_augassign(struct compiler *c, stmt_ty s)
3079{
3080 expr_ty e = s->v.AugAssign.target;
3081 expr_ty auge;
3082
3083 assert(s->kind == AugAssign_kind);
3084
3085 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003086 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003088 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003089 if (auge == NULL)
3090 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 VISIT(c, expr, auge);
3092 VISIT(c, expr, s->v.AugAssign.value);
3093 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3094 auge->v.Attribute.ctx = AugStore;
3095 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096 break;
3097 case Subscript_kind:
3098 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003099 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003100 if (auge == NULL)
3101 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003102 VISIT(c, expr, auge);
3103 VISIT(c, expr, s->v.AugAssign.value);
3104 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003105 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003107 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003109 if (!compiler_nameop(c, e->v.Name.id, Load))
3110 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111 VISIT(c, expr, s->v.AugAssign.value);
3112 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3113 return compiler_nameop(c, e->v.Name.id, Store);
3114 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003115 PyErr_Format(PyExc_SystemError,
3116 "invalid node type (%d) for augmented assignment",
3117 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003118 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119 }
3120 return 1;
3121}
3122
3123static int
3124compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3125{
3126 struct fblockinfo *f;
3127 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3128 return 0;
3129 f = &c->u->u_fblock[c->u->u_nfblocks++];
3130 f->fb_type = t;
3131 f->fb_block = b;
3132 return 1;
3133}
3134
3135static void
3136compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3137{
3138 struct compiler_unit *u = c->u;
3139 assert(u->u_nfblocks > 0);
3140 u->u_nfblocks--;
3141 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3142 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3143}
3144
3145/* Raises a SyntaxError and returns 0.
3146 If something goes wrong, a different exception may be raised.
3147*/
3148
3149static int
3150compiler_error(struct compiler *c, const char *errstr)
3151{
3152 PyObject *loc;
3153 PyObject *u = NULL, *v = NULL;
3154
3155 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3156 if (!loc) {
3157 Py_INCREF(Py_None);
3158 loc = Py_None;
3159 }
3160 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3161 Py_None, loc);
3162 if (!u)
3163 goto exit;
3164 v = Py_BuildValue("(zO)", errstr, u);
3165 if (!v)
3166 goto exit;
3167 PyErr_SetObject(PyExc_SyntaxError, v);
3168 exit:
3169 Py_DECREF(loc);
3170 Py_XDECREF(u);
3171 Py_XDECREF(v);
3172 return 0;
3173}
3174
3175static int
3176compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 /* XXX this code is duplicated */
3182 switch (ctx) {
3183 case AugLoad: /* fall through to Load */
3184 case Load: op = BINARY_SUBSCR; break;
3185 case AugStore:/* fall through to Store */
3186 case Store: op = STORE_SUBSCR; break;
3187 case Del: op = DELETE_SUBSCR; break;
3188 case Param:
3189 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003190 "invalid %s kind %d in subscript\n",
3191 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 return 0;
3193 }
3194 if (ctx == AugLoad) {
3195 ADDOP_I(c, DUP_TOPX, 2);
3196 }
3197 else if (ctx == AugStore) {
3198 ADDOP(c, ROT_THREE);
3199 }
3200 ADDOP(c, op);
3201 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202}
3203
3204static int
3205compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3206{
3207 int n = 2;
3208 assert(s->kind == Slice_kind);
3209
3210 /* only handles the cases where BUILD_SLICE is emitted */
3211 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003212 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213 }
3214 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003215 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003217
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 }
3221 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003222 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223 }
3224
3225 if (s->v.Slice.step) {
3226 n++;
3227 VISIT(c, expr, s->v.Slice.step);
3228 }
3229 ADDOP_I(c, BUILD_SLICE, n);
3230 return 1;
3231}
3232
3233static int
3234compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3235{
3236 int op = 0, slice_offset = 0, stack_count = 0;
3237
3238 assert(s->v.Slice.step == NULL);
3239 if (s->v.Slice.lower) {
3240 slice_offset++;
3241 stack_count++;
3242 if (ctx != AugStore)
3243 VISIT(c, expr, s->v.Slice.lower);
3244 }
3245 if (s->v.Slice.upper) {
3246 slice_offset += 2;
3247 stack_count++;
3248 if (ctx != AugStore)
3249 VISIT(c, expr, s->v.Slice.upper);
3250 }
3251
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003252 if (ctx == AugLoad) {
3253 switch (stack_count) {
3254 case 0: ADDOP(c, DUP_TOP); break;
3255 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3256 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3257 }
3258 }
3259 else if (ctx == AugStore) {
3260 switch (stack_count) {
3261 case 0: ADDOP(c, ROT_TWO); break;
3262 case 1: ADDOP(c, ROT_THREE); break;
3263 case 2: ADDOP(c, ROT_FOUR); break;
3264 }
3265 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266
3267 switch (ctx) {
3268 case AugLoad: /* fall through to Load */
3269 case Load: op = SLICE; break;
3270 case AugStore:/* fall through to Store */
3271 case Store: op = STORE_SLICE; break;
3272 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003273 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003274 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003275 PyErr_SetString(PyExc_SystemError,
3276 "param invalid in simple slice");
3277 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278 }
3279
3280 ADDOP(c, op + slice_offset);
3281 return 1;
3282}
3283
3284static int
3285compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3286 expr_context_ty ctx)
3287{
3288 switch (s->kind) {
3289 case Ellipsis_kind:
3290 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3291 break;
3292 case Slice_kind:
3293 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294 case Index_kind:
3295 VISIT(c, expr, s->v.Index.value);
3296 break;
3297 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003298 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003299 PyErr_SetString(PyExc_SystemError,
3300 "extended slice invalid in nested slice");
3301 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 }
3303 return 1;
3304}
3305
3306
3307static int
3308compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3309{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003310 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003312 case Index_kind:
3313 kindname = "index";
3314 if (ctx != AugStore) {
3315 VISIT(c, expr, s->v.Index.value);
3316 }
3317 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003319 kindname = "ellipsis";
3320 if (ctx != AugStore) {
3321 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3322 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323 break;
3324 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003325 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326 if (!s->v.Slice.step)
3327 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003328 if (ctx != AugStore) {
3329 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330 return 0;
3331 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003332 break;
3333 case ExtSlice_kind:
3334 kindname = "extended slice";
3335 if (ctx != AugStore) {
3336 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3337 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003338 slice_ty sub = (slice_ty)asdl_seq_GET(
3339 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003340 if (!compiler_visit_nested_slice(c, sub, ctx))
3341 return 0;
3342 }
3343 ADDOP_I(c, BUILD_TUPLE, n);
3344 }
3345 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003346 default:
3347 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003348 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003349 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003350 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003351 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352}
3353
3354/* do depth-first search of basic block graph, starting with block.
3355 post records the block indices in post-order.
3356
3357 XXX must handle implicit jumps from one block to next
3358*/
3359
3360static void
3361dfs(struct compiler *c, basicblock *b, struct assembler *a)
3362{
3363 int i;
3364 struct instr *instr = NULL;
3365
3366 if (b->b_seen)
3367 return;
3368 b->b_seen = 1;
3369 if (b->b_next != NULL)
3370 dfs(c, b->b_next, a);
3371 for (i = 0; i < b->b_iused; i++) {
3372 instr = &b->b_instr[i];
3373 if (instr->i_jrel || instr->i_jabs)
3374 dfs(c, instr->i_target, a);
3375 }
3376 a->a_postorder[a->a_nblocks++] = b;
3377}
3378
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003379static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3381{
3382 int i;
3383 struct instr *instr;
3384 if (b->b_seen || b->b_startdepth >= depth)
3385 return maxdepth;
3386 b->b_seen = 1;
3387 b->b_startdepth = depth;
3388 for (i = 0; i < b->b_iused; i++) {
3389 instr = &b->b_instr[i];
3390 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3391 if (depth > maxdepth)
3392 maxdepth = depth;
3393 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3394 if (instr->i_jrel || instr->i_jabs) {
3395 maxdepth = stackdepth_walk(c, instr->i_target,
3396 depth, maxdepth);
3397 if (instr->i_opcode == JUMP_ABSOLUTE ||
3398 instr->i_opcode == JUMP_FORWARD) {
3399 goto out; /* remaining code is dead */
3400 }
3401 }
3402 }
3403 if (b->b_next)
3404 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3405out:
3406 b->b_seen = 0;
3407 return maxdepth;
3408}
3409
3410/* Find the flow path that needs the largest stack. We assume that
3411 * cycles in the flow graph have no net effect on the stack depth.
3412 */
3413static int
3414stackdepth(struct compiler *c)
3415{
3416 basicblock *b, *entryblock;
3417 entryblock = NULL;
3418 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3419 b->b_seen = 0;
3420 b->b_startdepth = INT_MIN;
3421 entryblock = b;
3422 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003423 if (!entryblock)
3424 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425 return stackdepth_walk(c, entryblock, 0, 0);
3426}
3427
3428static int
3429assemble_init(struct assembler *a, int nblocks, int firstlineno)
3430{
3431 memset(a, 0, sizeof(struct assembler));
3432 a->a_lineno = firstlineno;
3433 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3434 if (!a->a_bytecode)
3435 return 0;
3436 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3437 if (!a->a_lnotab)
3438 return 0;
3439 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003440 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003441 if (!a->a_postorder) {
3442 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003444 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003445 return 1;
3446}
3447
3448static void
3449assemble_free(struct assembler *a)
3450{
3451 Py_XDECREF(a->a_bytecode);
3452 Py_XDECREF(a->a_lnotab);
3453 if (a->a_postorder)
3454 PyObject_Free(a->a_postorder);
3455}
3456
3457/* Return the size of a basic block in bytes. */
3458
3459static int
3460instrsize(struct instr *instr)
3461{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003462 if (!instr->i_hasarg)
3463 return 1;
3464 if (instr->i_oparg > 0xffff)
3465 return 6;
3466 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467}
3468
3469static int
3470blocksize(basicblock *b)
3471{
3472 int i;
3473 int size = 0;
3474
3475 for (i = 0; i < b->b_iused; i++)
3476 size += instrsize(&b->b_instr[i]);
3477 return size;
3478}
3479
3480/* All about a_lnotab.
3481
3482c_lnotab is an array of unsigned bytes disguised as a Python string.
3483It is used to map bytecode offsets to source code line #s (when needed
3484for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003485
Tim Peters2a7f3842001-06-09 09:26:21 +00003486The array is conceptually a list of
3487 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003488pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003489
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003490 byte code offset source code line number
3491 0 1
3492 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003493 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003494 350 307
3495 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003496
3497The first trick is that these numbers aren't stored, only the increments
3498from one row to the next (this doesn't really work, but it's a start):
3499
3500 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3501
3502The second trick is that an unsigned byte can't hold negative values, or
3503values larger than 255, so (a) there's a deep assumption that byte code
3504offsets and their corresponding line #s both increase monotonically, and (b)
3505if at least one column jumps by more than 255 from one row to the next, more
3506than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003507from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003508part. A user of c_lnotab desiring to find the source line number
3509corresponding to a bytecode address A should do something like this
3510
3511 lineno = addr = 0
3512 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003513 addr += addr_incr
3514 if addr > A:
3515 return lineno
3516 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003517
3518In order for this to work, when the addr field increments by more than 255,
3519the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003520increment is < 256. So, in the example above, assemble_lnotab (it used
3521to be called com_set_lineno) should not (as was actually done until 2.2)
3522expand 300, 300 to 255, 255, 45, 45,
3523 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003524*/
3525
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003526static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003528{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 int d_bytecode, d_lineno;
3530 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003531 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532
3533 d_bytecode = a->a_offset - a->a_lineno_off;
3534 d_lineno = i->i_lineno - a->a_lineno;
3535
3536 assert(d_bytecode >= 0);
3537 assert(d_lineno >= 0);
3538
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003539 /* XXX(nnorwitz): is there a better way to handle this?
3540 for loops are special, we want to be able to trace them
3541 each time around, so we need to set an extra line number. */
3542 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003543 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003544
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003546 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547 nbytes = a->a_lnotab_off + 2 * ncodes;
3548 len = PyString_GET_SIZE(a->a_lnotab);
3549 if (nbytes >= len) {
3550 if (len * 2 < nbytes)
3551 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003552 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 len *= 2;
3554 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3555 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003556 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003557 lnotab = (unsigned char *)
3558 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003559 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 *lnotab++ = 255;
3561 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003562 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 d_bytecode -= ncodes * 255;
3564 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003565 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 assert(d_bytecode <= 255);
3567 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003568 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569 nbytes = a->a_lnotab_off + 2 * ncodes;
3570 len = PyString_GET_SIZE(a->a_lnotab);
3571 if (nbytes >= len) {
3572 if (len * 2 < nbytes)
3573 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003574 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 len *= 2;
3576 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3577 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003578 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003579 lnotab = (unsigned char *)
3580 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003582 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003584 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003586 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 d_lineno -= ncodes * 255;
3589 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003590 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003591
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 len = PyString_GET_SIZE(a->a_lnotab);
3593 if (a->a_lnotab_off + 2 >= len) {
3594 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003595 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003596 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003597 lnotab = (unsigned char *)
3598 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003599
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 a->a_lnotab_off += 2;
3601 if (d_bytecode) {
3602 *lnotab++ = d_bytecode;
3603 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003604 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003605 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 *lnotab++ = 0;
3607 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609 a->a_lineno = i->i_lineno;
3610 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003611 return 1;
3612}
3613
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614/* assemble_emit()
3615 Extend the bytecode with a new instruction.
3616 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003617*/
3618
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003619static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003621{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003622 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003623 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 char *code;
3625
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003626 size = instrsize(i);
3627 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003629 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003630 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003632 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 if (a->a_offset + size >= len) {
3634 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003635 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003636 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3638 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003639 if (size == 6) {
3640 assert(i->i_hasarg);
3641 *code++ = (char)EXTENDED_ARG;
3642 *code++ = ext & 0xff;
3643 *code++ = ext >> 8;
3644 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003645 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003646 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003647 if (i->i_hasarg) {
3648 assert(size == 3 || size == 6);
3649 *code++ = arg & 0xff;
3650 *code++ = arg >> 8;
3651 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003653}
3654
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003655static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003657{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003659 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003660 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003661
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662 /* Compute the size of each block and fixup jump args.
3663 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003664start:
3665 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003667 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 bsize = blocksize(b);
3669 b->b_offset = totsize;
3670 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003671 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003672 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3674 bsize = b->b_offset;
3675 for (i = 0; i < b->b_iused; i++) {
3676 struct instr *instr = &b->b_instr[i];
3677 /* Relative jumps are computed relative to
3678 the instruction pointer after fetching
3679 the jump instruction.
3680 */
3681 bsize += instrsize(instr);
3682 if (instr->i_jabs)
3683 instr->i_oparg = instr->i_target->b_offset;
3684 else if (instr->i_jrel) {
3685 int delta = instr->i_target->b_offset - bsize;
3686 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003687 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003688 else
3689 continue;
3690 if (instr->i_oparg > 0xffff)
3691 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003692 }
3693 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003694
3695 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003696 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003697 with a better solution.
3698
3699 In the meantime, should the goto be dropped in favor
3700 of a loop?
3701
3702 The issue is that in the first loop blocksize() is called
3703 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003704 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003705 i_oparg is calculated in the second loop above.
3706
3707 So we loop until we stop seeing new EXTENDED_ARGs.
3708 The only EXTENDED_ARGs that could be popping up are
3709 ones in jump instructions. So this should converge
3710 fairly quickly.
3711 */
3712 if (last_extended_arg_count != extended_arg_count) {
3713 last_extended_arg_count = extended_arg_count;
3714 goto start;
3715 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003716}
3717
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003718static PyObject *
3719dict_keys_inorder(PyObject *dict, int offset)
3720{
3721 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003722 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003723
3724 tuple = PyTuple_New(size);
3725 if (tuple == NULL)
3726 return NULL;
3727 while (PyDict_Next(dict, &pos, &k, &v)) {
3728 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003729 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003730 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003731 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003732 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003733 PyTuple_SET_ITEM(tuple, i - offset, k);
3734 }
3735 return tuple;
3736}
3737
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003738static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003740{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741 PySTEntryObject *ste = c->u->u_ste;
3742 int flags = 0, n;
3743 if (ste->ste_type != ModuleBlock)
3744 flags |= CO_NEWLOCALS;
3745 if (ste->ste_type == FunctionBlock) {
3746 if (!ste->ste_unoptimized)
3747 flags |= CO_OPTIMIZED;
3748 if (ste->ste_nested)
3749 flags |= CO_NESTED;
3750 if (ste->ste_generator)
3751 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003752 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753 if (ste->ste_varargs)
3754 flags |= CO_VARARGS;
3755 if (ste->ste_varkeywords)
3756 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003757 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003759
3760 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003761 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763 n = PyDict_Size(c->u->u_freevars);
3764 if (n < 0)
3765 return -1;
3766 if (n == 0) {
3767 n = PyDict_Size(c->u->u_cellvars);
3768 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003769 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770 if (n == 0) {
3771 flags |= CO_NOFREE;
3772 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003773 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003774
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003775 return flags;
3776}
3777
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778static PyCodeObject *
3779makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003780{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003781 PyObject *tmp;
3782 PyCodeObject *co = NULL;
3783 PyObject *consts = NULL;
3784 PyObject *names = NULL;
3785 PyObject *varnames = NULL;
3786 PyObject *filename = NULL;
3787 PyObject *name = NULL;
3788 PyObject *freevars = NULL;
3789 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003790 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003792
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793 tmp = dict_keys_inorder(c->u->u_consts, 0);
3794 if (!tmp)
3795 goto error;
3796 consts = PySequence_List(tmp); /* optimize_code requires a list */
3797 Py_DECREF(tmp);
3798
3799 names = dict_keys_inorder(c->u->u_names, 0);
3800 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3801 if (!consts || !names || !varnames)
3802 goto error;
3803
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003804 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3805 if (!cellvars)
3806 goto error;
3807 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3808 if (!freevars)
3809 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 filename = PyString_FromString(c->c_filename);
3811 if (!filename)
3812 goto error;
3813
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003814 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 flags = compute_code_flags(c);
3816 if (flags < 0)
3817 goto error;
3818
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003819 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 if (!bytecode)
3821 goto error;
3822
3823 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3824 if (!tmp)
3825 goto error;
3826 Py_DECREF(consts);
3827 consts = tmp;
3828
3829 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3830 bytecode, consts, names, varnames,
3831 freevars, cellvars,
3832 filename, c->u->u_name,
3833 c->u->u_firstlineno,
3834 a->a_lnotab);
3835 error:
3836 Py_XDECREF(consts);
3837 Py_XDECREF(names);
3838 Py_XDECREF(varnames);
3839 Py_XDECREF(filename);
3840 Py_XDECREF(name);
3841 Py_XDECREF(freevars);
3842 Py_XDECREF(cellvars);
3843 Py_XDECREF(bytecode);
3844 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003845}
3846
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003847
3848/* For debugging purposes only */
3849#if 0
3850static void
3851dump_instr(const struct instr *i)
3852{
3853 const char *jrel = i->i_jrel ? "jrel " : "";
3854 const char *jabs = i->i_jabs ? "jabs " : "";
3855 char arg[128];
3856
3857 *arg = '\0';
3858 if (i->i_hasarg)
3859 sprintf(arg, "arg: %d ", i->i_oparg);
3860
3861 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3862 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3863}
3864
3865static void
3866dump_basicblock(const basicblock *b)
3867{
3868 const char *seen = b->b_seen ? "seen " : "";
3869 const char *b_return = b->b_return ? "return " : "";
3870 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3871 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3872 if (b->b_instr) {
3873 int i;
3874 for (i = 0; i < b->b_iused; i++) {
3875 fprintf(stderr, " [%02d] ", i);
3876 dump_instr(b->b_instr + i);
3877 }
3878 }
3879}
3880#endif
3881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882static PyCodeObject *
3883assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003884{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 basicblock *b, *entryblock;
3886 struct assembler a;
3887 int i, j, nblocks;
3888 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003889
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890 /* Make sure every block that falls off the end returns None.
3891 XXX NEXT_BLOCK() isn't quite right, because if the last
3892 block ends with a jump or return b_next shouldn't set.
3893 */
3894 if (!c->u->u_curblock->b_return) {
3895 NEXT_BLOCK(c);
3896 if (addNone)
3897 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3898 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003899 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 nblocks = 0;
3902 entryblock = NULL;
3903 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3904 nblocks++;
3905 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003906 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003907
Neal Norwitzed657552006-07-10 00:04:44 +00003908 /* Set firstlineno if it wasn't explicitly set. */
3909 if (!c->u->u_firstlineno) {
3910 if (entryblock && entryblock->b_instr)
3911 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3912 else
3913 c->u->u_firstlineno = 1;
3914 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3916 goto error;
3917 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003918
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003919 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003920 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922 /* Emit code in reverse postorder from dfs. */
3923 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003924 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003925 for (j = 0; j < b->b_iused; j++)
3926 if (!assemble_emit(&a, &b->b_instr[j]))
3927 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003928 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003929
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3931 goto error;
3932 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3933 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003934
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935 co = makecode(c, &a);
3936 error:
3937 assemble_free(&a);
3938 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003939}