blob: a03de0d663a9ad47b30d70c46b0b4bc612908aa9 [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";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001685 static const char IN_FINALLY_ERROR_MSG[] =
1686 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687 int i;
1688
1689 if (!c->u->u_nfblocks)
1690 return compiler_error(c, LOOP_ERROR_MSG);
1691 i = c->u->u_nfblocks - 1;
1692 switch (c->u->u_fblock[i].fb_type) {
1693 case LOOP:
1694 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1695 break;
1696 case EXCEPT:
1697 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001698 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1699 /* Prevent continue anywhere under a finally
1700 even if hidden in a sub-try or except. */
1701 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1702 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1703 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 if (i == -1)
1705 return compiler_error(c, LOOP_ERROR_MSG);
1706 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1707 break;
1708 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001709 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710 }
1711
1712 return 1;
1713}
1714
1715/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1716
1717 SETUP_FINALLY L
1718 <code for body>
1719 POP_BLOCK
1720 LOAD_CONST <None>
1721 L: <code for finalbody>
1722 END_FINALLY
1723
1724 The special instructions use the block stack. Each block
1725 stack entry contains the instruction that created it (here
1726 SETUP_FINALLY), the level of the value stack at the time the
1727 block stack entry was created, and a label (here L).
1728
1729 SETUP_FINALLY:
1730 Pushes the current value stack level and the label
1731 onto the block stack.
1732 POP_BLOCK:
1733 Pops en entry from the block stack, and pops the value
1734 stack until its level is the same as indicated on the
1735 block stack. (The label is ignored.)
1736 END_FINALLY:
1737 Pops a variable number of entries from the *value* stack
1738 and re-raises the exception they specify. The number of
1739 entries popped depends on the (pseudo) exception type.
1740
1741 The block stack is unwound when an exception is raised:
1742 when a SETUP_FINALLY entry is found, the exception is pushed
1743 onto the value stack (and the exception condition is cleared),
1744 and the interpreter jumps to the label gotten from the block
1745 stack.
1746*/
1747
1748static int
1749compiler_try_finally(struct compiler *c, stmt_ty s)
1750{
1751 basicblock *body, *end;
1752 body = compiler_new_block(c);
1753 end = compiler_new_block(c);
1754 if (body == NULL || end == NULL)
1755 return 0;
1756
1757 ADDOP_JREL(c, SETUP_FINALLY, end);
1758 compiler_use_next_block(c, body);
1759 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1760 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001761 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001762 ADDOP(c, POP_BLOCK);
1763 compiler_pop_fblock(c, FINALLY_TRY, body);
1764
1765 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1766 compiler_use_next_block(c, end);
1767 if (!compiler_push_fblock(c, FINALLY_END, end))
1768 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001769 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 ADDOP(c, END_FINALLY);
1771 compiler_pop_fblock(c, FINALLY_END, end);
1772
1773 return 1;
1774}
1775
1776/*
1777 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1778 (The contents of the value stack is shown in [], with the top
1779 at the right; 'tb' is trace-back info, 'val' the exception's
1780 associated value, and 'exc' the exception.)
1781
1782 Value stack Label Instruction Argument
1783 [] SETUP_EXCEPT L1
1784 [] <code for S>
1785 [] POP_BLOCK
1786 [] JUMP_FORWARD L0
1787
1788 [tb, val, exc] L1: DUP )
1789 [tb, val, exc, exc] <evaluate E1> )
1790 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1791 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1792 [tb, val, exc, 1] POP )
1793 [tb, val, exc] POP
1794 [tb, val] <assign to V1> (or POP if no V1)
1795 [tb] POP
1796 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001797 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798
1799 [tb, val, exc, 0] L2: POP
1800 [tb, val, exc] DUP
1801 .............................etc.......................
1802
1803 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001804 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805
1806 [] L0: <next statement>
1807
1808 Of course, parts are not generated if Vi or Ei is not present.
1809*/
1810static int
1811compiler_try_except(struct compiler *c, stmt_ty s)
1812{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001813 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814 int i, n;
1815
1816 body = compiler_new_block(c);
1817 except = compiler_new_block(c);
1818 orelse = compiler_new_block(c);
1819 end = compiler_new_block(c);
1820 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1821 return 0;
1822 ADDOP_JREL(c, SETUP_EXCEPT, except);
1823 compiler_use_next_block(c, body);
1824 if (!compiler_push_fblock(c, EXCEPT, body))
1825 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001826 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 ADDOP(c, POP_BLOCK);
1828 compiler_pop_fblock(c, EXCEPT, body);
1829 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1830 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1831 compiler_use_next_block(c, except);
1832 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001833 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 s->v.TryExcept.handlers, i);
1835 if (!handler->type && i < n-1)
1836 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00001837 c->u->u_lineno_set = false;
1838 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001839 except = compiler_new_block(c);
1840 if (except == NULL)
1841 return 0;
1842 if (handler->type) {
1843 ADDOP(c, DUP_TOP);
1844 VISIT(c, expr, handler->type);
1845 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1846 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1847 ADDOP(c, POP_TOP);
1848 }
1849 ADDOP(c, POP_TOP);
1850 if (handler->name) {
1851 VISIT(c, expr, handler->name);
1852 }
1853 else {
1854 ADDOP(c, POP_TOP);
1855 }
1856 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001857 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858 ADDOP_JREL(c, JUMP_FORWARD, end);
1859 compiler_use_next_block(c, except);
1860 if (handler->type)
1861 ADDOP(c, POP_TOP);
1862 }
1863 ADDOP(c, END_FINALLY);
1864 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001865 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866 compiler_use_next_block(c, end);
1867 return 1;
1868}
1869
1870static int
1871compiler_import_as(struct compiler *c, identifier name, identifier asname)
1872{
1873 /* The IMPORT_NAME opcode was already generated. This function
1874 merely needs to bind the result to a name.
1875
1876 If there is a dot in name, we need to split it and emit a
1877 LOAD_ATTR for each name.
1878 */
1879 const char *src = PyString_AS_STRING(name);
1880 const char *dot = strchr(src, '.');
1881 if (dot) {
1882 /* Consume the base module name to get the first attribute */
1883 src = dot + 1;
1884 while (dot) {
1885 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001886 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001888 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001890 if (!attr)
1891 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001893 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894 src = dot + 1;
1895 }
1896 }
1897 return compiler_nameop(c, asname, Store);
1898}
1899
1900static int
1901compiler_import(struct compiler *c, stmt_ty s)
1902{
1903 /* The Import node stores a module name like a.b.c as a single
1904 string. This is convenient for all cases except
1905 import a.b.c as d
1906 where we need to parse that string to extract the individual
1907 module names.
1908 XXX Perhaps change the representation to make this case simpler?
1909 */
1910 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001911
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001913 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001915 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916
Neal Norwitzcbce2802006-04-03 06:26:32 +00001917 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001918 level = PyInt_FromLong(0);
1919 else
1920 level = PyInt_FromLong(-1);
1921
1922 if (level == NULL)
1923 return 0;
1924
1925 ADDOP_O(c, LOAD_CONST, level, consts);
1926 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1928 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1929
1930 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001931 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001932 if (!r)
1933 return r;
1934 }
1935 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936 identifier tmp = alias->name;
1937 const char *base = PyString_AS_STRING(alias->name);
1938 char *dot = strchr(base, '.');
1939 if (dot)
1940 tmp = PyString_FromStringAndSize(base,
1941 dot - base);
1942 r = compiler_nameop(c, tmp, Store);
1943 if (dot) {
1944 Py_DECREF(tmp);
1945 }
1946 if (!r)
1947 return r;
1948 }
1949 }
1950 return 1;
1951}
1952
1953static int
1954compiler_from_import(struct compiler *c, stmt_ty s)
1955{
1956 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
1958 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001959 PyObject *level;
1960
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961 if (!names)
1962 return 0;
1963
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001964 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001965 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001966 level = PyInt_FromLong(-1);
1967 else
1968 level = PyInt_FromLong(s->v.ImportFrom.level);
1969
1970 if (!level) {
1971 Py_DECREF(names);
1972 return 0;
1973 }
1974
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975 /* build up the names */
1976 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001977 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978 Py_INCREF(alias->name);
1979 PyTuple_SET_ITEM(names, i, alias->name);
1980 }
1981
1982 if (s->lineno > c->c_future->ff_lineno) {
1983 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1984 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001985 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986 Py_DECREF(names);
1987 return compiler_error(c,
1988 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001989 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990
1991 }
1992 }
1993
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001994 ADDOP_O(c, LOAD_CONST, level, consts);
1995 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001997 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1999 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002000 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 identifier store_name;
2002
2003 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2004 assert(n == 1);
2005 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 }
2008
2009 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2010 store_name = alias->name;
2011 if (alias->asname)
2012 store_name = alias->asname;
2013
2014 if (!compiler_nameop(c, store_name, Store)) {
2015 Py_DECREF(names);
2016 return 0;
2017 }
2018 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002019 /* remove imported module */
2020 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 return 1;
2022}
2023
2024static int
2025compiler_assert(struct compiler *c, stmt_ty s)
2026{
2027 static PyObject *assertion_error = NULL;
2028 basicblock *end;
2029
2030 if (Py_OptimizeFlag)
2031 return 1;
2032 if (assertion_error == NULL) {
2033 assertion_error = PyString_FromString("AssertionError");
2034 if (assertion_error == NULL)
2035 return 0;
2036 }
2037 VISIT(c, expr, s->v.Assert.test);
2038 end = compiler_new_block(c);
2039 if (end == NULL)
2040 return 0;
2041 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2042 ADDOP(c, POP_TOP);
2043 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2044 if (s->v.Assert.msg) {
2045 VISIT(c, expr, s->v.Assert.msg);
2046 ADDOP_I(c, RAISE_VARARGS, 2);
2047 }
2048 else {
2049 ADDOP_I(c, RAISE_VARARGS, 1);
2050 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002051 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 ADDOP(c, POP_TOP);
2053 return 1;
2054}
2055
2056static int
2057compiler_visit_stmt(struct compiler *c, stmt_ty s)
2058{
2059 int i, n;
2060
Jeremy Hylton12603c42006-04-01 16:18:02 +00002061 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062 c->u->u_lineno = s->lineno;
2063 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002066 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002068 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002070 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 if (c->u->u_ste->ste_type != FunctionBlock)
2072 return compiler_error(c, "'return' outside function");
2073 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 VISIT(c, expr, s->v.Return.value);
2075 }
2076 else
2077 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2078 ADDOP(c, RETURN_VALUE);
2079 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002080 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002081 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002083 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 n = asdl_seq_LEN(s->v.Assign.targets);
2085 VISIT(c, expr, s->v.Assign.value);
2086 for (i = 0; i < n; i++) {
2087 if (i < n - 1)
2088 ADDOP(c, DUP_TOP);
2089 VISIT(c, expr,
2090 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2091 }
2092 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002093 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002101 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 n = 0;
2105 if (s->v.Raise.type) {
2106 VISIT(c, expr, s->v.Raise.type);
2107 n++;
2108 if (s->v.Raise.inst) {
2109 VISIT(c, expr, s->v.Raise.inst);
2110 n++;
2111 if (s->v.Raise.tback) {
2112 VISIT(c, expr, s->v.Raise.tback);
2113 n++;
2114 }
2115 }
2116 }
2117 ADDOP_I(c, RAISE_VARARGS, n);
2118 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002119 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002121 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002123 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002125 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130 VISIT(c, expr, s->v.Exec.body);
2131 if (s->v.Exec.globals) {
2132 VISIT(c, expr, s->v.Exec.globals);
2133 if (s->v.Exec.locals) {
2134 VISIT(c, expr, s->v.Exec.locals);
2135 } else {
2136 ADDOP(c, DUP_TOP);
2137 }
2138 } else {
2139 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2140 ADDOP(c, DUP_TOP);
2141 }
2142 ADDOP(c, EXEC_STMT);
2143 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002144 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002146 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002147 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002148 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 ADDOP(c, PRINT_EXPR);
2150 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002151 else if (s->v.Expr.value->kind != Str_kind &&
2152 s->v.Expr.value->kind != Num_kind) {
2153 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 ADDOP(c, POP_TOP);
2155 }
2156 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002157 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002159 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160 if (!c->u->u_nfblocks)
2161 return compiler_error(c, "'break' outside loop");
2162 ADDOP(c, BREAK_LOOP);
2163 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002164 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002166 case With_kind:
2167 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168 }
2169 return 1;
2170}
2171
2172static int
2173unaryop(unaryop_ty op)
2174{
2175 switch (op) {
2176 case Invert:
2177 return UNARY_INVERT;
2178 case Not:
2179 return UNARY_NOT;
2180 case UAdd:
2181 return UNARY_POSITIVE;
2182 case USub:
2183 return UNARY_NEGATIVE;
2184 }
2185 return 0;
2186}
2187
2188static int
2189binop(struct compiler *c, operator_ty op)
2190{
2191 switch (op) {
2192 case Add:
2193 return BINARY_ADD;
2194 case Sub:
2195 return BINARY_SUBTRACT;
2196 case Mult:
2197 return BINARY_MULTIPLY;
2198 case Div:
2199 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2200 return BINARY_TRUE_DIVIDE;
2201 else
2202 return BINARY_DIVIDE;
2203 case Mod:
2204 return BINARY_MODULO;
2205 case Pow:
2206 return BINARY_POWER;
2207 case LShift:
2208 return BINARY_LSHIFT;
2209 case RShift:
2210 return BINARY_RSHIFT;
2211 case BitOr:
2212 return BINARY_OR;
2213 case BitXor:
2214 return BINARY_XOR;
2215 case BitAnd:
2216 return BINARY_AND;
2217 case FloorDiv:
2218 return BINARY_FLOOR_DIVIDE;
2219 }
2220 return 0;
2221}
2222
2223static int
2224cmpop(cmpop_ty op)
2225{
2226 switch (op) {
2227 case Eq:
2228 return PyCmp_EQ;
2229 case NotEq:
2230 return PyCmp_NE;
2231 case Lt:
2232 return PyCmp_LT;
2233 case LtE:
2234 return PyCmp_LE;
2235 case Gt:
2236 return PyCmp_GT;
2237 case GtE:
2238 return PyCmp_GE;
2239 case Is:
2240 return PyCmp_IS;
2241 case IsNot:
2242 return PyCmp_IS_NOT;
2243 case In:
2244 return PyCmp_IN;
2245 case NotIn:
2246 return PyCmp_NOT_IN;
2247 }
2248 return PyCmp_BAD;
2249}
2250
2251static int
2252inplace_binop(struct compiler *c, operator_ty op)
2253{
2254 switch (op) {
2255 case Add:
2256 return INPLACE_ADD;
2257 case Sub:
2258 return INPLACE_SUBTRACT;
2259 case Mult:
2260 return INPLACE_MULTIPLY;
2261 case Div:
2262 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2263 return INPLACE_TRUE_DIVIDE;
2264 else
2265 return INPLACE_DIVIDE;
2266 case Mod:
2267 return INPLACE_MODULO;
2268 case Pow:
2269 return INPLACE_POWER;
2270 case LShift:
2271 return INPLACE_LSHIFT;
2272 case RShift:
2273 return INPLACE_RSHIFT;
2274 case BitOr:
2275 return INPLACE_OR;
2276 case BitXor:
2277 return INPLACE_XOR;
2278 case BitAnd:
2279 return INPLACE_AND;
2280 case FloorDiv:
2281 return INPLACE_FLOOR_DIVIDE;
2282 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002283 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002284 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285 return 0;
2286}
2287
2288static int
2289compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2290{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002291 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2293
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002294 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002295 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 /* XXX AugStore isn't used anywhere! */
2297
2298 /* First check for assignment to __debug__. Param? */
2299 if ((ctx == Store || ctx == AugStore || ctx == Del)
2300 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2301 return compiler_error(c, "can not assign to __debug__");
2302 }
2303
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002304 mangled = _Py_Mangle(c->u->u_private, name);
2305 if (!mangled)
2306 return 0;
2307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308 op = 0;
2309 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002310 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311 switch (scope) {
2312 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002313 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 optype = OP_DEREF;
2315 break;
2316 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002317 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 optype = OP_DEREF;
2319 break;
2320 case LOCAL:
2321 if (c->u->u_ste->ste_type == FunctionBlock)
2322 optype = OP_FAST;
2323 break;
2324 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002325 if (c->u->u_ste->ste_type == FunctionBlock &&
2326 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327 optype = OP_GLOBAL;
2328 break;
2329 case GLOBAL_EXPLICIT:
2330 optype = OP_GLOBAL;
2331 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002332 default:
2333 /* scope can be 0 */
2334 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 }
2336
2337 /* XXX Leave assert here, but handle __doc__ and the like better */
2338 assert(scope || PyString_AS_STRING(name)[0] == '_');
2339
2340 switch (optype) {
2341 case OP_DEREF:
2342 switch (ctx) {
2343 case Load: op = LOAD_DEREF; break;
2344 case Store: op = STORE_DEREF; break;
2345 case AugLoad:
2346 case AugStore:
2347 break;
2348 case Del:
2349 PyErr_Format(PyExc_SyntaxError,
2350 "can not delete variable '%s' referenced "
2351 "in nested scope",
2352 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002353 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002356 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002357 PyErr_SetString(PyExc_SystemError,
2358 "param invalid for deref variable");
2359 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 }
2361 break;
2362 case OP_FAST:
2363 switch (ctx) {
2364 case Load: op = LOAD_FAST; break;
2365 case Store: op = STORE_FAST; break;
2366 case Del: op = DELETE_FAST; break;
2367 case AugLoad:
2368 case AugStore:
2369 break;
2370 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002371 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002372 PyErr_SetString(PyExc_SystemError,
2373 "param invalid for local variable");
2374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002376 ADDOP_O(c, op, mangled, varnames);
2377 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002378 return 1;
2379 case OP_GLOBAL:
2380 switch (ctx) {
2381 case Load: op = LOAD_GLOBAL; break;
2382 case Store: op = STORE_GLOBAL; break;
2383 case Del: op = DELETE_GLOBAL; break;
2384 case AugLoad:
2385 case AugStore:
2386 break;
2387 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002388 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002389 PyErr_SetString(PyExc_SystemError,
2390 "param invalid for global variable");
2391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392 }
2393 break;
2394 case OP_NAME:
2395 switch (ctx) {
2396 case Load: op = LOAD_NAME; break;
2397 case Store: op = STORE_NAME; break;
2398 case Del: op = DELETE_NAME; break;
2399 case AugLoad:
2400 case AugStore:
2401 break;
2402 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002403 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002404 PyErr_SetString(PyExc_SystemError,
2405 "param invalid for name variable");
2406 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 }
2408 break;
2409 }
2410
2411 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002412 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002413 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002414 if (arg < 0)
2415 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002416 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417}
2418
2419static int
2420compiler_boolop(struct compiler *c, expr_ty e)
2421{
2422 basicblock *end;
2423 int jumpi, i, n;
2424 asdl_seq *s;
2425
2426 assert(e->kind == BoolOp_kind);
2427 if (e->v.BoolOp.op == And)
2428 jumpi = JUMP_IF_FALSE;
2429 else
2430 jumpi = JUMP_IF_TRUE;
2431 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002432 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433 return 0;
2434 s = e->v.BoolOp.values;
2435 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002436 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002438 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 ADDOP_JREL(c, jumpi, end);
2440 ADDOP(c, POP_TOP)
2441 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002442 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443 compiler_use_next_block(c, end);
2444 return 1;
2445}
2446
2447static int
2448compiler_list(struct compiler *c, expr_ty e)
2449{
2450 int n = asdl_seq_LEN(e->v.List.elts);
2451 if (e->v.List.ctx == Store) {
2452 ADDOP_I(c, UNPACK_SEQUENCE, n);
2453 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002454 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 if (e->v.List.ctx == Load) {
2456 ADDOP_I(c, BUILD_LIST, n);
2457 }
2458 return 1;
2459}
2460
2461static int
2462compiler_tuple(struct compiler *c, expr_ty e)
2463{
2464 int n = asdl_seq_LEN(e->v.Tuple.elts);
2465 if (e->v.Tuple.ctx == Store) {
2466 ADDOP_I(c, UNPACK_SEQUENCE, n);
2467 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002468 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 if (e->v.Tuple.ctx == Load) {
2470 ADDOP_I(c, BUILD_TUPLE, n);
2471 }
2472 return 1;
2473}
2474
2475static int
2476compiler_compare(struct compiler *c, expr_ty e)
2477{
2478 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002479 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480
2481 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2482 VISIT(c, expr, e->v.Compare.left);
2483 n = asdl_seq_LEN(e->v.Compare.ops);
2484 assert(n > 0);
2485 if (n > 1) {
2486 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002487 if (cleanup == NULL)
2488 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002489 VISIT(c, expr,
2490 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 }
2492 for (i = 1; i < n; i++) {
2493 ADDOP(c, DUP_TOP);
2494 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002496 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00002497 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2499 NEXT_BLOCK(c);
2500 ADDOP(c, POP_TOP);
2501 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002502 VISIT(c, expr,
2503 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002505 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002507 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508 if (n > 1) {
2509 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002510 if (end == NULL)
2511 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002512 ADDOP_JREL(c, JUMP_FORWARD, end);
2513 compiler_use_next_block(c, cleanup);
2514 ADDOP(c, ROT_TWO);
2515 ADDOP(c, POP_TOP);
2516 compiler_use_next_block(c, end);
2517 }
2518 return 1;
2519}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00002520#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521
2522static int
2523compiler_call(struct compiler *c, expr_ty e)
2524{
2525 int n, code = 0;
2526
2527 VISIT(c, expr, e->v.Call.func);
2528 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002529 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002531 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2533 }
2534 if (e->v.Call.starargs) {
2535 VISIT(c, expr, e->v.Call.starargs);
2536 code |= 1;
2537 }
2538 if (e->v.Call.kwargs) {
2539 VISIT(c, expr, e->v.Call.kwargs);
2540 code |= 2;
2541 }
2542 switch (code) {
2543 case 0:
2544 ADDOP_I(c, CALL_FUNCTION, n);
2545 break;
2546 case 1:
2547 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2548 break;
2549 case 2:
2550 ADDOP_I(c, CALL_FUNCTION_KW, n);
2551 break;
2552 case 3:
2553 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2554 break;
2555 }
2556 return 1;
2557}
2558
2559static int
2560compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002561 asdl_seq *generators, int gen_index,
2562 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002563{
2564 /* generate code for the iterator, then each of the ifs,
2565 and then write to the element */
2566
2567 comprehension_ty l;
2568 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002569 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570
2571 start = compiler_new_block(c);
2572 skip = compiler_new_block(c);
2573 if_cleanup = compiler_new_block(c);
2574 anchor = compiler_new_block(c);
2575
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002576 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2577 anchor == NULL)
2578 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579
Anthony Baxter7b782b62006-04-11 12:01:56 +00002580 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581 VISIT(c, expr, l->iter);
2582 ADDOP(c, GET_ITER);
2583 compiler_use_next_block(c, start);
2584 ADDOP_JREL(c, FOR_ITER, anchor);
2585 NEXT_BLOCK(c);
2586 VISIT(c, expr, l->target);
2587
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002588 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589 n = asdl_seq_LEN(l->ifs);
2590 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002591 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 VISIT(c, expr, e);
2593 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2594 NEXT_BLOCK(c);
2595 ADDOP(c, POP_TOP);
2596 }
2597
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002598 if (++gen_index < asdl_seq_LEN(generators))
2599 if (!compiler_listcomp_generator(c, tmpname,
2600 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002603 /* only append after the last for generator */
2604 if (gen_index >= asdl_seq_LEN(generators)) {
2605 if (!compiler_nameop(c, tmpname, Load))
2606 return 0;
2607 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002608 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002609
2610 compiler_use_next_block(c, skip);
2611 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 for (i = 0; i < n; i++) {
2613 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614 if (i == 0)
2615 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 ADDOP(c, POP_TOP);
2617 }
2618 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2619 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002620 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002622 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 return 0;
2624
2625 return 1;
2626}
2627
2628static int
2629compiler_listcomp(struct compiler *c, expr_ty e)
2630{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 static identifier append;
2634 asdl_seq *generators = e->v.ListComp.generators;
2635
2636 assert(e->kind == ListComp_kind);
2637 if (!append) {
2638 append = PyString_InternFromString("append");
2639 if (!append)
2640 return 0;
2641 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002642 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643 if (!tmp)
2644 return 0;
2645 ADDOP_I(c, BUILD_LIST, 0);
2646 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002648 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2649 e->v.ListComp.elt);
2650 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651 return rc;
2652}
2653
2654static int
2655compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002656 asdl_seq *generators, int gen_index,
2657 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658{
2659 /* generate code for the iterator, then each of the ifs,
2660 and then write to the element */
2661
2662 comprehension_ty ge;
2663 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002664 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665
2666 start = compiler_new_block(c);
2667 skip = compiler_new_block(c);
2668 if_cleanup = compiler_new_block(c);
2669 anchor = compiler_new_block(c);
2670 end = compiler_new_block(c);
2671
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002672 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 anchor == NULL || end == NULL)
2674 return 0;
2675
Anthony Baxter7b782b62006-04-11 12:01:56 +00002676 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677 ADDOP_JREL(c, SETUP_LOOP, end);
2678 if (!compiler_push_fblock(c, LOOP, start))
2679 return 0;
2680
2681 if (gen_index == 0) {
2682 /* Receive outermost iter as an implicit argument */
2683 c->u->u_argcount = 1;
2684 ADDOP_I(c, LOAD_FAST, 0);
2685 }
2686 else {
2687 /* Sub-iter - calculate on the fly */
2688 VISIT(c, expr, ge->iter);
2689 ADDOP(c, GET_ITER);
2690 }
2691 compiler_use_next_block(c, start);
2692 ADDOP_JREL(c, FOR_ITER, anchor);
2693 NEXT_BLOCK(c);
2694 VISIT(c, expr, ge->target);
2695
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002696 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 n = asdl_seq_LEN(ge->ifs);
2698 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002699 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 VISIT(c, expr, e);
2701 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2702 NEXT_BLOCK(c);
2703 ADDOP(c, POP_TOP);
2704 }
2705
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2708 return 0;
2709
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 /* only append after the last 'for' generator */
2711 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 VISIT(c, expr, elt);
2713 ADDOP(c, YIELD_VALUE);
2714 ADDOP(c, POP_TOP);
2715
2716 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002717 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 for (i = 0; i < n; i++) {
2719 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002720 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721 compiler_use_next_block(c, if_cleanup);
2722
2723 ADDOP(c, POP_TOP);
2724 }
2725 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2726 compiler_use_next_block(c, anchor);
2727 ADDOP(c, POP_BLOCK);
2728 compiler_pop_fblock(c, LOOP, start);
2729 compiler_use_next_block(c, end);
2730
2731 return 1;
2732}
2733
2734static int
2735compiler_genexp(struct compiler *c, expr_ty e)
2736{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002737 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738 PyCodeObject *co;
2739 expr_ty outermost_iter = ((comprehension_ty)
2740 (asdl_seq_GET(e->v.GeneratorExp.generators,
2741 0)))->iter;
2742
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002743 if (!name) {
2744 name = PyString_FromString("<genexpr>");
2745 if (!name)
2746 return 0;
2747 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002748
2749 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2750 return 0;
2751 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2752 e->v.GeneratorExp.elt);
2753 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002754 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755 if (co == NULL)
2756 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002758 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002759 Py_DECREF(co);
2760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761 VISIT(c, expr, outermost_iter);
2762 ADDOP(c, GET_ITER);
2763 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002764
2765 return 1;
2766}
2767
2768static int
2769compiler_visit_keyword(struct compiler *c, keyword_ty k)
2770{
2771 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2772 VISIT(c, expr, k->value);
2773 return 1;
2774}
2775
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002776/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777 whether they are true or false.
2778
2779 Return values: 1 for true, 0 for false, -1 for non-constant.
2780 */
2781
2782static int
2783expr_constant(expr_ty e)
2784{
2785 switch (e->kind) {
2786 case Num_kind:
2787 return PyObject_IsTrue(e->v.Num.n);
2788 case Str_kind:
2789 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002790 case Name_kind:
2791 /* __debug__ is not assignable, so we can optimize
2792 * it away in if and while statements */
2793 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2794 "__debug__") == 0)
2795 return ! Py_OptimizeFlag;
2796 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797 default:
2798 return -1;
2799 }
2800}
2801
Guido van Rossumc2e20742006-02-27 22:32:47 +00002802/*
2803 Implements the with statement from PEP 343.
2804
2805 The semantics outlined in that PEP are as follows:
2806
2807 with EXPR as VAR:
2808 BLOCK
2809
2810 It is implemented roughly as:
2811
Guido van Rossumda5b7012006-05-02 19:47:52 +00002812 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002813 exit = context.__exit__ # not calling it
2814 value = context.__enter__()
2815 try:
2816 VAR = value # if VAR present in the syntax
2817 BLOCK
2818 finally:
2819 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002821 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002822 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002823 exit(*exc)
2824 */
2825static int
2826compiler_with(struct compiler *c, stmt_ty s)
2827{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002828 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002829 basicblock *block, *finally;
2830 identifier tmpexit, tmpvalue = NULL;
2831
2832 assert(s->kind == With_kind);
2833
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002835 enter_attr = PyString_InternFromString("__enter__");
2836 if (!enter_attr)
2837 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002838 }
2839 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002840 exit_attr = PyString_InternFromString("__exit__");
2841 if (!exit_attr)
2842 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002843 }
2844
2845 block = compiler_new_block(c);
2846 finally = compiler_new_block(c);
2847 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002848 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002849
2850 /* Create a temporary variable to hold context.__exit__ */
2851 tmpexit = compiler_new_tmpname(c);
2852 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002853 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002854 PyArena_AddPyObject(c->c_arena, tmpexit);
2855
2856 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002857 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002858 We need to do this rather than preserving it on the stack
2859 because SETUP_FINALLY remembers the stack level.
2860 We need to do the assignment *inside* the try/finally
2861 so that context.__exit__() is called when the assignment
2862 fails. But we need to call context.__enter__() *before*
2863 the try/finally so that if it fails we won't call
2864 context.__exit__().
2865 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002866 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002867 if (tmpvalue == NULL)
2868 return 0;
2869 PyArena_AddPyObject(c->c_arena, tmpvalue);
2870 }
2871
Guido van Rossumda5b7012006-05-02 19:47:52 +00002872 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002873 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002874
2875 /* Squirrel away context.__exit__ */
2876 ADDOP(c, DUP_TOP);
2877 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2878 if (!compiler_nameop(c, tmpexit, Store))
2879 return 0;
2880
2881 /* Call context.__enter__() */
2882 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2883 ADDOP_I(c, CALL_FUNCTION, 0);
2884
2885 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002886 /* Store it in tmpvalue */
2887 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002888 return 0;
2889 }
2890 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002891 /* Discard result from context.__enter__() */
2892 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002893 }
2894
2895 /* Start the try block */
2896 ADDOP_JREL(c, SETUP_FINALLY, finally);
2897
2898 compiler_use_next_block(c, block);
2899 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002900 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002901 }
2902
2903 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002904 /* Bind saved result of context.__enter__() to VAR */
2905 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002906 !compiler_nameop(c, tmpvalue, Del))
2907 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002908 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002909 }
2910
2911 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002912 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002913
2914 /* End of try block; start the finally block */
2915 ADDOP(c, POP_BLOCK);
2916 compiler_pop_fblock(c, FINALLY_TRY, block);
2917
2918 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2919 compiler_use_next_block(c, finally);
2920 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002921 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002922
2923 /* Finally block starts; push tmpexit and issue our magic opcode. */
2924 if (!compiler_nameop(c, tmpexit, Load) ||
2925 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002927 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002928
2929 /* Finally block ends. */
2930 ADDOP(c, END_FINALLY);
2931 compiler_pop_fblock(c, FINALLY_END, finally);
2932 return 1;
2933}
2934
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935static int
2936compiler_visit_expr(struct compiler *c, expr_ty e)
2937{
2938 int i, n;
2939
Jeremy Hylton12603c42006-04-01 16:18:02 +00002940 /* If expr e has a different line number than the last expr/stmt,
2941 set a new line number for the next instruction.
2942 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 if (e->lineno > c->u->u_lineno) {
2944 c->u->u_lineno = e->lineno;
2945 c->u->u_lineno_set = false;
2946 }
2947 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002948 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002950 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 VISIT(c, expr, e->v.BinOp.left);
2952 VISIT(c, expr, e->v.BinOp.right);
2953 ADDOP(c, binop(c, e->v.BinOp.op));
2954 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002955 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 VISIT(c, expr, e->v.UnaryOp.operand);
2957 ADDOP(c, unaryop(e->v.UnaryOp.op));
2958 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002959 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002961 case IfExp_kind:
2962 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002963 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964 /* XXX get rid of arg? */
2965 ADDOP_I(c, BUILD_MAP, 0);
2966 n = asdl_seq_LEN(e->v.Dict.values);
2967 /* We must arrange things just right for STORE_SUBSCR.
2968 It wants the stack to look like (value) (dict) (key) */
2969 for (i = 0; i < n; i++) {
2970 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002971 VISIT(c, expr,
2972 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002974 VISIT(c, expr,
2975 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 ADDOP(c, STORE_SUBSCR);
2977 }
2978 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002979 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 return compiler_genexp(c, e);
2983 case Yield_kind:
2984 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002985 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986 /*
2987 for (i = 0; i < c->u->u_nfblocks; i++) {
2988 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2989 return compiler_error(
2990 c, "'yield' not allowed in a 'try' "
2991 "block with a 'finally' clause");
2992 }
2993 */
2994 if (e->v.Yield.value) {
2995 VISIT(c, expr, e->v.Yield.value);
2996 }
2997 else {
2998 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2999 }
3000 ADDOP(c, YIELD_VALUE);
3001 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003002 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003004 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003006 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007 VISIT(c, expr, e->v.Repr.value);
3008 ADDOP(c, UNARY_CONVERT);
3009 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003010 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3012 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003013 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3015 break;
3016 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003017 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018 if (e->v.Attribute.ctx != AugStore)
3019 VISIT(c, expr, e->v.Attribute.value);
3020 switch (e->v.Attribute.ctx) {
3021 case AugLoad:
3022 ADDOP(c, DUP_TOP);
3023 /* Fall through to load */
3024 case Load:
3025 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3026 break;
3027 case AugStore:
3028 ADDOP(c, ROT_TWO);
3029 /* Fall through to save */
3030 case Store:
3031 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3032 break;
3033 case Del:
3034 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3035 break;
3036 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003037 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003038 PyErr_SetString(PyExc_SystemError,
3039 "param invalid in attribute expression");
3040 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041 }
3042 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003043 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 switch (e->v.Subscript.ctx) {
3045 case AugLoad:
3046 VISIT(c, expr, e->v.Subscript.value);
3047 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3048 break;
3049 case Load:
3050 VISIT(c, expr, e->v.Subscript.value);
3051 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3052 break;
3053 case AugStore:
3054 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3055 break;
3056 case Store:
3057 VISIT(c, expr, e->v.Subscript.value);
3058 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3059 break;
3060 case Del:
3061 VISIT(c, expr, e->v.Subscript.value);
3062 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3063 break;
3064 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003065 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003066 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003067 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003068 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003069 }
3070 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003071 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3073 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003076 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 return compiler_tuple(c, e);
3078 }
3079 return 1;
3080}
3081
3082static int
3083compiler_augassign(struct compiler *c, stmt_ty s)
3084{
3085 expr_ty e = s->v.AugAssign.target;
3086 expr_ty auge;
3087
3088 assert(s->kind == AugAssign_kind);
3089
3090 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003091 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003093 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003094 if (auge == NULL)
3095 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096 VISIT(c, expr, auge);
3097 VISIT(c, expr, s->v.AugAssign.value);
3098 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3099 auge->v.Attribute.ctx = AugStore;
3100 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101 break;
3102 case Subscript_kind:
3103 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003104 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003105 if (auge == NULL)
3106 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107 VISIT(c, expr, auge);
3108 VISIT(c, expr, s->v.AugAssign.value);
3109 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003110 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003112 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003113 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003114 if (!compiler_nameop(c, e->v.Name.id, Load))
3115 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003116 VISIT(c, expr, s->v.AugAssign.value);
3117 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3118 return compiler_nameop(c, e->v.Name.id, Store);
3119 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003120 PyErr_Format(PyExc_SystemError,
3121 "invalid node type (%d) for augmented assignment",
3122 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003124 }
3125 return 1;
3126}
3127
3128static int
3129compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3130{
3131 struct fblockinfo *f;
3132 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3133 return 0;
3134 f = &c->u->u_fblock[c->u->u_nfblocks++];
3135 f->fb_type = t;
3136 f->fb_block = b;
3137 return 1;
3138}
3139
3140static void
3141compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3142{
3143 struct compiler_unit *u = c->u;
3144 assert(u->u_nfblocks > 0);
3145 u->u_nfblocks--;
3146 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3147 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3148}
3149
3150/* Raises a SyntaxError and returns 0.
3151 If something goes wrong, a different exception may be raised.
3152*/
3153
3154static int
3155compiler_error(struct compiler *c, const char *errstr)
3156{
3157 PyObject *loc;
3158 PyObject *u = NULL, *v = NULL;
3159
3160 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3161 if (!loc) {
3162 Py_INCREF(Py_None);
3163 loc = Py_None;
3164 }
3165 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3166 Py_None, loc);
3167 if (!u)
3168 goto exit;
3169 v = Py_BuildValue("(zO)", errstr, u);
3170 if (!v)
3171 goto exit;
3172 PyErr_SetObject(PyExc_SyntaxError, v);
3173 exit:
3174 Py_DECREF(loc);
3175 Py_XDECREF(u);
3176 Py_XDECREF(v);
3177 return 0;
3178}
3179
3180static int
3181compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003182 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003184 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003186 /* XXX this code is duplicated */
3187 switch (ctx) {
3188 case AugLoad: /* fall through to Load */
3189 case Load: op = BINARY_SUBSCR; break;
3190 case AugStore:/* fall through to Store */
3191 case Store: op = STORE_SUBSCR; break;
3192 case Del: op = DELETE_SUBSCR; break;
3193 case Param:
3194 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003195 "invalid %s kind %d in subscript\n",
3196 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197 return 0;
3198 }
3199 if (ctx == AugLoad) {
3200 ADDOP_I(c, DUP_TOPX, 2);
3201 }
3202 else if (ctx == AugStore) {
3203 ADDOP(c, ROT_THREE);
3204 }
3205 ADDOP(c, op);
3206 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207}
3208
3209static int
3210compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3211{
3212 int n = 2;
3213 assert(s->kind == Slice_kind);
3214
3215 /* only handles the cases where BUILD_SLICE is emitted */
3216 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003217 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 }
3219 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003220 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003224 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225 }
3226 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003227 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228 }
3229
3230 if (s->v.Slice.step) {
3231 n++;
3232 VISIT(c, expr, s->v.Slice.step);
3233 }
3234 ADDOP_I(c, BUILD_SLICE, n);
3235 return 1;
3236}
3237
3238static int
3239compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3240{
3241 int op = 0, slice_offset = 0, stack_count = 0;
3242
3243 assert(s->v.Slice.step == NULL);
3244 if (s->v.Slice.lower) {
3245 slice_offset++;
3246 stack_count++;
3247 if (ctx != AugStore)
3248 VISIT(c, expr, s->v.Slice.lower);
3249 }
3250 if (s->v.Slice.upper) {
3251 slice_offset += 2;
3252 stack_count++;
3253 if (ctx != AugStore)
3254 VISIT(c, expr, s->v.Slice.upper);
3255 }
3256
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003257 if (ctx == AugLoad) {
3258 switch (stack_count) {
3259 case 0: ADDOP(c, DUP_TOP); break;
3260 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3261 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3262 }
3263 }
3264 else if (ctx == AugStore) {
3265 switch (stack_count) {
3266 case 0: ADDOP(c, ROT_TWO); break;
3267 case 1: ADDOP(c, ROT_THREE); break;
3268 case 2: ADDOP(c, ROT_FOUR); break;
3269 }
3270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271
3272 switch (ctx) {
3273 case AugLoad: /* fall through to Load */
3274 case Load: op = SLICE; break;
3275 case AugStore:/* fall through to Store */
3276 case Store: op = STORE_SLICE; break;
3277 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003278 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003279 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003280 PyErr_SetString(PyExc_SystemError,
3281 "param invalid in simple slice");
3282 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283 }
3284
3285 ADDOP(c, op + slice_offset);
3286 return 1;
3287}
3288
3289static int
3290compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3291 expr_context_ty ctx)
3292{
3293 switch (s->kind) {
3294 case Ellipsis_kind:
3295 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3296 break;
3297 case Slice_kind:
3298 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299 case Index_kind:
3300 VISIT(c, expr, s->v.Index.value);
3301 break;
3302 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003303 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003304 PyErr_SetString(PyExc_SystemError,
3305 "extended slice invalid in nested slice");
3306 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307 }
3308 return 1;
3309}
3310
3311
3312static int
3313compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3314{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003315 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003317 case Index_kind:
3318 kindname = "index";
3319 if (ctx != AugStore) {
3320 VISIT(c, expr, s->v.Index.value);
3321 }
3322 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003324 kindname = "ellipsis";
3325 if (ctx != AugStore) {
3326 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3327 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328 break;
3329 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003330 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003331 if (!s->v.Slice.step)
3332 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003333 if (ctx != AugStore) {
3334 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335 return 0;
3336 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003337 break;
3338 case ExtSlice_kind:
3339 kindname = "extended slice";
3340 if (ctx != AugStore) {
3341 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3342 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003343 slice_ty sub = (slice_ty)asdl_seq_GET(
3344 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003345 if (!compiler_visit_nested_slice(c, sub, ctx))
3346 return 0;
3347 }
3348 ADDOP_I(c, BUILD_TUPLE, n);
3349 }
3350 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003351 default:
3352 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003353 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003356 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357}
3358
3359/* do depth-first search of basic block graph, starting with block.
3360 post records the block indices in post-order.
3361
3362 XXX must handle implicit jumps from one block to next
3363*/
3364
3365static void
3366dfs(struct compiler *c, basicblock *b, struct assembler *a)
3367{
3368 int i;
3369 struct instr *instr = NULL;
3370
3371 if (b->b_seen)
3372 return;
3373 b->b_seen = 1;
3374 if (b->b_next != NULL)
3375 dfs(c, b->b_next, a);
3376 for (i = 0; i < b->b_iused; i++) {
3377 instr = &b->b_instr[i];
3378 if (instr->i_jrel || instr->i_jabs)
3379 dfs(c, instr->i_target, a);
3380 }
3381 a->a_postorder[a->a_nblocks++] = b;
3382}
3383
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003384static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3386{
3387 int i;
3388 struct instr *instr;
3389 if (b->b_seen || b->b_startdepth >= depth)
3390 return maxdepth;
3391 b->b_seen = 1;
3392 b->b_startdepth = depth;
3393 for (i = 0; i < b->b_iused; i++) {
3394 instr = &b->b_instr[i];
3395 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3396 if (depth > maxdepth)
3397 maxdepth = depth;
3398 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3399 if (instr->i_jrel || instr->i_jabs) {
3400 maxdepth = stackdepth_walk(c, instr->i_target,
3401 depth, maxdepth);
3402 if (instr->i_opcode == JUMP_ABSOLUTE ||
3403 instr->i_opcode == JUMP_FORWARD) {
3404 goto out; /* remaining code is dead */
3405 }
3406 }
3407 }
3408 if (b->b_next)
3409 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3410out:
3411 b->b_seen = 0;
3412 return maxdepth;
3413}
3414
3415/* Find the flow path that needs the largest stack. We assume that
3416 * cycles in the flow graph have no net effect on the stack depth.
3417 */
3418static int
3419stackdepth(struct compiler *c)
3420{
3421 basicblock *b, *entryblock;
3422 entryblock = NULL;
3423 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3424 b->b_seen = 0;
3425 b->b_startdepth = INT_MIN;
3426 entryblock = b;
3427 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003428 if (!entryblock)
3429 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430 return stackdepth_walk(c, entryblock, 0, 0);
3431}
3432
3433static int
3434assemble_init(struct assembler *a, int nblocks, int firstlineno)
3435{
3436 memset(a, 0, sizeof(struct assembler));
3437 a->a_lineno = firstlineno;
3438 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3439 if (!a->a_bytecode)
3440 return 0;
3441 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3442 if (!a->a_lnotab)
3443 return 0;
3444 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003445 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003446 if (!a->a_postorder) {
3447 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003448 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003449 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450 return 1;
3451}
3452
3453static void
3454assemble_free(struct assembler *a)
3455{
3456 Py_XDECREF(a->a_bytecode);
3457 Py_XDECREF(a->a_lnotab);
3458 if (a->a_postorder)
3459 PyObject_Free(a->a_postorder);
3460}
3461
3462/* Return the size of a basic block in bytes. */
3463
3464static int
3465instrsize(struct instr *instr)
3466{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003467 if (!instr->i_hasarg)
3468 return 1;
3469 if (instr->i_oparg > 0xffff)
3470 return 6;
3471 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003472}
3473
3474static int
3475blocksize(basicblock *b)
3476{
3477 int i;
3478 int size = 0;
3479
3480 for (i = 0; i < b->b_iused; i++)
3481 size += instrsize(&b->b_instr[i]);
3482 return size;
3483}
3484
3485/* All about a_lnotab.
3486
3487c_lnotab is an array of unsigned bytes disguised as a Python string.
3488It is used to map bytecode offsets to source code line #s (when needed
3489for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003490
Tim Peters2a7f3842001-06-09 09:26:21 +00003491The array is conceptually a list of
3492 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003494
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 byte code offset source code line number
3496 0 1
3497 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003498 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003499 350 307
3500 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003501
3502The first trick is that these numbers aren't stored, only the increments
3503from one row to the next (this doesn't really work, but it's a start):
3504
3505 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3506
3507The second trick is that an unsigned byte can't hold negative values, or
3508values larger than 255, so (a) there's a deep assumption that byte code
3509offsets and their corresponding line #s both increase monotonically, and (b)
3510if at least one column jumps by more than 255 from one row to the next, more
3511than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003512from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003513part. A user of c_lnotab desiring to find the source line number
3514corresponding to a bytecode address A should do something like this
3515
3516 lineno = addr = 0
3517 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003518 addr += addr_incr
3519 if addr > A:
3520 return lineno
3521 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003522
3523In order for this to work, when the addr field increments by more than 255,
3524the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003525increment is < 256. So, in the example above, assemble_lnotab (it used
3526to be called com_set_lineno) should not (as was actually done until 2.2)
3527expand 300, 300 to 255, 255, 45, 45,
3528 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003529*/
3530
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003531static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003533{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 int d_bytecode, d_lineno;
3535 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003536 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537
3538 d_bytecode = a->a_offset - a->a_lineno_off;
3539 d_lineno = i->i_lineno - a->a_lineno;
3540
3541 assert(d_bytecode >= 0);
3542 assert(d_lineno >= 0);
3543
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003544 /* XXX(nnorwitz): is there a better way to handle this?
3545 for loops are special, we want to be able to trace them
3546 each time around, so we need to set an extra line number. */
3547 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003548 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003549
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003551 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 nbytes = a->a_lnotab_off + 2 * ncodes;
3553 len = PyString_GET_SIZE(a->a_lnotab);
3554 if (nbytes >= len) {
3555 if (len * 2 < nbytes)
3556 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003557 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 len *= 2;
3559 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3560 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003561 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003562 lnotab = (unsigned char *)
3563 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003564 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 *lnotab++ = 255;
3566 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003567 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 d_bytecode -= ncodes * 255;
3569 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003570 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571 assert(d_bytecode <= 255);
3572 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003573 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 nbytes = a->a_lnotab_off + 2 * ncodes;
3575 len = PyString_GET_SIZE(a->a_lnotab);
3576 if (nbytes >= len) {
3577 if (len * 2 < nbytes)
3578 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003579 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 len *= 2;
3581 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3582 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003583 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003584 lnotab = (unsigned char *)
3585 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003587 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003589 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003591 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 d_lineno -= ncodes * 255;
3594 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003595 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003596
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 len = PyString_GET_SIZE(a->a_lnotab);
3598 if (a->a_lnotab_off + 2 >= len) {
3599 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003600 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003601 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003602 lnotab = (unsigned char *)
3603 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003604
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 a->a_lnotab_off += 2;
3606 if (d_bytecode) {
3607 *lnotab++ = d_bytecode;
3608 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003609 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003610 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 *lnotab++ = 0;
3612 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 a->a_lineno = i->i_lineno;
3615 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003616 return 1;
3617}
3618
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619/* assemble_emit()
3620 Extend the bytecode with a new instruction.
3621 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003622*/
3623
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003624static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003626{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003627 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003628 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003629 char *code;
3630
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003631 size = instrsize(i);
3632 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003634 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003637 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 if (a->a_offset + size >= len) {
3639 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003640 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3643 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003644 if (size == 6) {
3645 assert(i->i_hasarg);
3646 *code++ = (char)EXTENDED_ARG;
3647 *code++ = ext & 0xff;
3648 *code++ = ext >> 8;
3649 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003650 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003652 if (i->i_hasarg) {
3653 assert(size == 3 || size == 6);
3654 *code++ = arg & 0xff;
3655 *code++ = arg >> 8;
3656 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003658}
3659
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003660static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003662{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003664 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003665 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667 /* Compute the size of each block and fixup jump args.
3668 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003669start:
3670 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003672 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673 bsize = blocksize(b);
3674 b->b_offset = totsize;
3675 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003676 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003677 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003678 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3679 bsize = b->b_offset;
3680 for (i = 0; i < b->b_iused; i++) {
3681 struct instr *instr = &b->b_instr[i];
3682 /* Relative jumps are computed relative to
3683 the instruction pointer after fetching
3684 the jump instruction.
3685 */
3686 bsize += instrsize(instr);
3687 if (instr->i_jabs)
3688 instr->i_oparg = instr->i_target->b_offset;
3689 else if (instr->i_jrel) {
3690 int delta = instr->i_target->b_offset - bsize;
3691 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003692 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003693 else
3694 continue;
3695 if (instr->i_oparg > 0xffff)
3696 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003697 }
3698 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003699
3700 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003701 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003702 with a better solution.
3703
3704 In the meantime, should the goto be dropped in favor
3705 of a loop?
3706
3707 The issue is that in the first loop blocksize() is called
3708 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003709 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003710 i_oparg is calculated in the second loop above.
3711
3712 So we loop until we stop seeing new EXTENDED_ARGs.
3713 The only EXTENDED_ARGs that could be popping up are
3714 ones in jump instructions. So this should converge
3715 fairly quickly.
3716 */
3717 if (last_extended_arg_count != extended_arg_count) {
3718 last_extended_arg_count = extended_arg_count;
3719 goto start;
3720 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003721}
3722
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003723static PyObject *
3724dict_keys_inorder(PyObject *dict, int offset)
3725{
3726 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003727 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003728
3729 tuple = PyTuple_New(size);
3730 if (tuple == NULL)
3731 return NULL;
3732 while (PyDict_Next(dict, &pos, &k, &v)) {
3733 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003734 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003735 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003736 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003737 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003738 PyTuple_SET_ITEM(tuple, i - offset, k);
3739 }
3740 return tuple;
3741}
3742
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003743static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003745{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746 PySTEntryObject *ste = c->u->u_ste;
3747 int flags = 0, n;
3748 if (ste->ste_type != ModuleBlock)
3749 flags |= CO_NEWLOCALS;
3750 if (ste->ste_type == FunctionBlock) {
3751 if (!ste->ste_unoptimized)
3752 flags |= CO_OPTIMIZED;
3753 if (ste->ste_nested)
3754 flags |= CO_NESTED;
3755 if (ste->ste_generator)
3756 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003757 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758 if (ste->ste_varargs)
3759 flags |= CO_VARARGS;
3760 if (ste->ste_varkeywords)
3761 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003762 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003764
3765 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003766 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768 n = PyDict_Size(c->u->u_freevars);
3769 if (n < 0)
3770 return -1;
3771 if (n == 0) {
3772 n = PyDict_Size(c->u->u_cellvars);
3773 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003774 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 if (n == 0) {
3776 flags |= CO_NOFREE;
3777 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003778 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003779
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003780 return flags;
3781}
3782
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783static PyCodeObject *
3784makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003785{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 PyObject *tmp;
3787 PyCodeObject *co = NULL;
3788 PyObject *consts = NULL;
3789 PyObject *names = NULL;
3790 PyObject *varnames = NULL;
3791 PyObject *filename = NULL;
3792 PyObject *name = NULL;
3793 PyObject *freevars = NULL;
3794 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003795 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003797
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798 tmp = dict_keys_inorder(c->u->u_consts, 0);
3799 if (!tmp)
3800 goto error;
3801 consts = PySequence_List(tmp); /* optimize_code requires a list */
3802 Py_DECREF(tmp);
3803
3804 names = dict_keys_inorder(c->u->u_names, 0);
3805 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3806 if (!consts || !names || !varnames)
3807 goto error;
3808
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003809 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3810 if (!cellvars)
3811 goto error;
3812 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3813 if (!freevars)
3814 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 filename = PyString_FromString(c->c_filename);
3816 if (!filename)
3817 goto error;
3818
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003819 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 flags = compute_code_flags(c);
3821 if (flags < 0)
3822 goto error;
3823
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003824 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 if (!bytecode)
3826 goto error;
3827
3828 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3829 if (!tmp)
3830 goto error;
3831 Py_DECREF(consts);
3832 consts = tmp;
3833
3834 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3835 bytecode, consts, names, varnames,
3836 freevars, cellvars,
3837 filename, c->u->u_name,
3838 c->u->u_firstlineno,
3839 a->a_lnotab);
3840 error:
3841 Py_XDECREF(consts);
3842 Py_XDECREF(names);
3843 Py_XDECREF(varnames);
3844 Py_XDECREF(filename);
3845 Py_XDECREF(name);
3846 Py_XDECREF(freevars);
3847 Py_XDECREF(cellvars);
3848 Py_XDECREF(bytecode);
3849 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003850}
3851
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003852
3853/* For debugging purposes only */
3854#if 0
3855static void
3856dump_instr(const struct instr *i)
3857{
3858 const char *jrel = i->i_jrel ? "jrel " : "";
3859 const char *jabs = i->i_jabs ? "jabs " : "";
3860 char arg[128];
3861
3862 *arg = '\0';
3863 if (i->i_hasarg)
3864 sprintf(arg, "arg: %d ", i->i_oparg);
3865
3866 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3867 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3868}
3869
3870static void
3871dump_basicblock(const basicblock *b)
3872{
3873 const char *seen = b->b_seen ? "seen " : "";
3874 const char *b_return = b->b_return ? "return " : "";
3875 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3876 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3877 if (b->b_instr) {
3878 int i;
3879 for (i = 0; i < b->b_iused; i++) {
3880 fprintf(stderr, " [%02d] ", i);
3881 dump_instr(b->b_instr + i);
3882 }
3883 }
3884}
3885#endif
3886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887static PyCodeObject *
3888assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003889{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890 basicblock *b, *entryblock;
3891 struct assembler a;
3892 int i, j, nblocks;
3893 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003894
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895 /* Make sure every block that falls off the end returns None.
3896 XXX NEXT_BLOCK() isn't quite right, because if the last
3897 block ends with a jump or return b_next shouldn't set.
3898 */
3899 if (!c->u->u_curblock->b_return) {
3900 NEXT_BLOCK(c);
3901 if (addNone)
3902 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3903 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003904 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003905
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906 nblocks = 0;
3907 entryblock = NULL;
3908 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3909 nblocks++;
3910 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003911 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003912
Neal Norwitzed657552006-07-10 00:04:44 +00003913 /* Set firstlineno if it wasn't explicitly set. */
3914 if (!c->u->u_firstlineno) {
3915 if (entryblock && entryblock->b_instr)
3916 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3917 else
3918 c->u->u_firstlineno = 1;
3919 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3921 goto error;
3922 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003923
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003924 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003925 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927 /* Emit code in reverse postorder from dfs. */
3928 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003929 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930 for (j = 0; j < b->b_iused; j++)
3931 if (!assemble_emit(&a, &b->b_instr[j]))
3932 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003933 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003934
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3936 goto error;
3937 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3938 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940 co = makecode(c, &a);
3941 error:
3942 assemble_free(&a);
3943 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003944}