blob: 0dd1082151e7c6ffc37f22afd19341df19684050 [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.
Neal Norwitzf733a012006-10-29 18:30:10 +00009 * 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 Hylton819de6c2007-02-27 16:13:23 +000011 * this file.
Neal Norwitzf733a012006-10-29 18:30:10 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Neal Norwitzf733a012006-10-29 18:30:10 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000042struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000043 unsigned i_jabs : 1;
44 unsigned i_jrel : 1;
45 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000067 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000068 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000069 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000070 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000073 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
83enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
84
85struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000087 basicblock *fb_block;
88};
89
90/* The following items change on entry and exit of code blocks.
91 They must be saved and restored when returning to a block.
92*/
93struct compiler_unit {
94 PySTEntryObject *u_ste;
95
96 PyObject *u_name;
97 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +000098 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099 the argument for opcodes that refer to those collections.
100 */
101 PyObject *u_consts; /* all constants */
102 PyObject *u_names; /* all names */
103 PyObject *u_varnames; /* local variables */
104 PyObject *u_cellvars; /* cell variables */
105 PyObject *u_freevars; /* free variables */
106
107 PyObject *u_private; /* for private name mangling */
108
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000109 int u_argcount; /* number of arguments for block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000110 /* Pointer to the most recently allocated block. By following b_list
111 members, you can reach all early allocated blocks. */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000112 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113 basicblock *u_curblock; /* pointer to current block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000114 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000115
116 int u_nfblocks;
117 struct fblockinfo u_fblock[CO_MAXBLOCKS];
118
119 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000120 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 bool u_lineno_set; /* boolean to indicate whether instr
122 has been generated with current lineno */
123};
124
125/* This struct captures the global state of a compilation.
126
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000127The u pointer points to the current compilation unit, while units
128for enclosing blocks are stored in c_stack. The u and c_stack are
129managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130*/
131
132struct compiler {
133 const char *c_filename;
134 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136 PyCompilerFlags *c_flags;
137
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000138 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000139 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 struct compiler_unit *u; /* compiler state for current block */
142 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145};
146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147static int compiler_enter_scope(struct compiler *, identifier, void *, int);
148static void compiler_free(struct compiler *);
149static basicblock *compiler_new_block(struct compiler *);
150static int compiler_next_instr(struct compiler *, basicblock *);
151static int compiler_addop(struct compiler *, int);
152static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
153static int compiler_addop_i(struct compiler *, int, int);
154static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155static basicblock *compiler_use_new_block(struct compiler *);
156static int compiler_error(struct compiler *, const char *);
157static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
158
159static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
160static int compiler_visit_stmt(struct compiler *, stmt_ty);
161static int compiler_visit_keyword(struct compiler *, keyword_ty);
162static int compiler_visit_expr(struct compiler *, expr_ty);
163static int compiler_augassign(struct compiler *, stmt_ty);
164static int compiler_visit_slice(struct compiler *, slice_ty,
165 expr_context_ty);
166
167static int compiler_push_fblock(struct compiler *, enum fblocktype,
168 basicblock *);
169static void compiler_pop_fblock(struct compiler *, enum fblocktype,
170 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000171/* Returns true if there is a loop on the fblock stack. */
172static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173
174static int inplace_binop(struct compiler *, operator_ty);
175static int expr_constant(expr_ty e);
176
Guido van Rossumc2e20742006-02-27 22:32:47 +0000177static int compiler_with(struct compiler *, stmt_ty);
178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static PyCodeObject *assemble(struct compiler *, int addNone);
180static PyObject *__doc__;
181
182PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000183_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000184{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185 /* Name mangling: __private becomes _classname__private.
186 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000187 const char *p, *name = PyString_AsString(ident);
188 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189 size_t nlen, plen;
Neal Norwitz84167d02006-08-12 01:45:47 +0000190 if (privateobj == NULL || !PyString_Check(privateobj) ||
191 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000192 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000194 }
Anthony Baxter7b782b62006-04-11 12:01:56 +0000195 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 nlen = strlen(name);
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000197 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000198
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000199 The only time a name with a dot can occur is when
200 we are compiling an import statement that has a
201 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000202
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000203 TODO(jhylton): Decide whether we want to support
204 mangling of the module name, e.g. __M.X.
205 */
Jeremy Hylton37075c52007-02-27 01:01:59 +0000206 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000207 || strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211 /* Strip leading underscores from class name */
212 while (*p == '_')
213 p++;
214 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
220 if (!ident)
221 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 buffer = PyString_AS_STRING(ident);
224 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 strncpy(buffer+1, p, plen);
226 strcpy(buffer+1+plen, name);
227 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000228}
229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230static int
231compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000232{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000234
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235 c->c_stack = PyList_New(0);
236 if (!c->c_stack)
237 return 0;
238
239 return 1;
240}
241
242PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000243PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000244 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245{
246 struct compiler c;
247 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000248 PyCompilerFlags local_flags;
249 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 if (!__doc__) {
252 __doc__ = PyString_InternFromString("__doc__");
253 if (!__doc__)
254 return NULL;
255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
257 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000258 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000260 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261 c.c_future = PyFuture_FromAST(mod, filename);
262 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000263 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000265 local_flags.cf_flags = 0;
266 flags = &local_flags;
267 }
268 merged = c.c_future->ff_features | flags->cf_flags;
269 c.c_future->ff_features = merged;
270 flags->cf_flags = merged;
271 c.c_flags = flags;
272 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273
274 c.c_st = PySymtable_Build(mod, filename, c.c_future);
275 if (c.c_st == NULL) {
276 if (!PyErr_Occurred())
277 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000278 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279 }
280
281 /* XXX initialize to NULL for now, need to handle */
282 c.c_encoding = NULL;
283
284 co = compiler_mod(&c, mod);
285
Thomas Wouters1175c432006-02-27 22:49:54 +0000286 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000288 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289 return co;
290}
291
292PyCodeObject *
293PyNode_Compile(struct _node *n, const char *filename)
294{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000295 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000296 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000297 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000298 if (!arena)
299 return NULL;
300 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000301 if (mod)
302 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000303 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000304 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000305}
306
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000307static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000309{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310 if (c->c_st)
311 PySymtable_Free(c->c_st);
312 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000313 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000315}
316
Guido van Rossum79f25d91997-04-29 20:08:16 +0000317static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000319{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000320 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000321 PyObject *v, *k;
322 PyObject *dict = PyDict_New();
323 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 n = PyList_Size(list);
326 for (i = 0; i < n; i++) {
327 v = PyInt_FromLong(i);
328 if (!v) {
329 Py_DECREF(dict);
330 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000331 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000332 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000333 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
335 Py_XDECREF(k);
336 Py_DECREF(v);
337 Py_DECREF(dict);
338 return NULL;
339 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000340 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 return dict;
344}
345
346/* Return new dict containing names from src that match scope(s).
347
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000348src is a symbol table dictionary. If the scope of a name matches
349either scope_type or flag is set, insert it into the new dict. The
350values are integers, starting at offset and increasing by one for
351each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352*/
353
354static PyObject *
355dictbytype(PyObject *src, int scope_type, int flag, int offset)
356{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000357 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 PyObject *k, *v, *dest = PyDict_New();
359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360 assert(offset >= 0);
361 if (dest == NULL)
362 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
364 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000365 /* XXX this should probably be a macro in symtable.h */
366 assert(PyInt_Check(v));
367 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
370 PyObject *tuple, *item = PyInt_FromLong(i);
371 if (item == NULL) {
372 Py_DECREF(dest);
373 return NULL;
374 }
375 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000376 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
378 Py_DECREF(item);
379 Py_DECREF(dest);
380 Py_XDECREF(tuple);
381 return NULL;
382 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000386 }
387 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000388}
389
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390static void
391compiler_unit_check(struct compiler_unit *u)
392{
393 basicblock *block;
394 for (block = u->u_blocks; block != NULL; block = block->b_list) {
395 assert(block != (void *)0xcbcbcbcb);
396 assert(block != (void *)0xfbfbfbfb);
397 assert(block != (void *)0xdbdbdbdb);
398 if (block->b_instr != NULL) {
399 assert(block->b_ialloc > 0);
400 assert(block->b_iused > 0);
401 assert(block->b_ialloc >= block->b_iused);
402 }
403 else {
404 assert (block->b_iused == 0);
405 assert (block->b_ialloc == 0);
406 }
407 }
408}
409
410static void
411compiler_unit_free(struct compiler_unit *u)
412{
413 basicblock *b, *next;
414
415 compiler_unit_check(u);
416 b = u->u_blocks;
417 while (b != NULL) {
418 if (b->b_instr)
419 PyObject_Free((void *)b->b_instr);
420 next = b->b_list;
421 PyObject_Free((void *)b);
422 b = next;
423 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000424 Py_CLEAR(u->u_ste);
425 Py_CLEAR(u->u_name);
426 Py_CLEAR(u->u_consts);
427 Py_CLEAR(u->u_names);
428 Py_CLEAR(u->u_varnames);
429 Py_CLEAR(u->u_freevars);
430 Py_CLEAR(u->u_cellvars);
431 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000432 PyObject_Free(u);
433}
434
435static int
436compiler_enter_scope(struct compiler *c, identifier name, void *key,
437 int lineno)
438{
439 struct compiler_unit *u;
440
Anthony Baxter7b782b62006-04-11 12:01:56 +0000441 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000442 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000443 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444 PyErr_NoMemory();
445 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000446 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000447 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448 u->u_argcount = 0;
449 u->u_ste = PySymtable_Lookup(c->c_st, key);
450 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000451 compiler_unit_free(u);
452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453 }
454 Py_INCREF(name);
455 u->u_name = name;
456 u->u_varnames = list2dict(u->u_ste->ste_varnames);
457 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000458 if (!u->u_varnames || !u->u_cellvars) {
459 compiler_unit_free(u);
460 return 0;
461 }
462
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000465 if (!u->u_freevars) {
466 compiler_unit_free(u);
467 return 0;
468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469
470 u->u_blocks = NULL;
471 u->u_tmpname = 0;
472 u->u_nfblocks = 0;
473 u->u_firstlineno = lineno;
474 u->u_lineno = 0;
475 u->u_lineno_set = false;
476 u->u_consts = PyDict_New();
477 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000478 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000479 return 0;
480 }
481 u->u_names = PyDict_New();
482 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000483 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484 return 0;
485 }
486
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000487 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000488
489 /* Push the old compiler_unit on the stack. */
490 if (c->u) {
491 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000492 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
493 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000494 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000495 return 0;
496 }
497 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 u->u_private = c->u->u_private;
499 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500 }
501 c->u = u;
502
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000503 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000504 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000505 return 0;
506
507 return 1;
508}
509
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000510static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511compiler_exit_scope(struct compiler *c)
512{
513 int n;
514 PyObject *wrapper;
515
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000516 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 compiler_unit_free(c->u);
518 /* Restore c->u to the parent unit. */
519 n = PyList_GET_SIZE(c->c_stack) - 1;
520 if (n >= 0) {
521 wrapper = PyList_GET_ITEM(c->c_stack, n);
522 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000523 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000526 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 compiler_unit_check(c->u);
528 }
529 else
530 c->u = NULL;
531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532}
533
Guido van Rossumc2e20742006-02-27 22:32:47 +0000534/* Allocate a new "anonymous" local variable.
535 Used by list comprehensions and with statements.
536*/
537
538static PyObject *
539compiler_new_tmpname(struct compiler *c)
540{
541 char tmpname[256];
542 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
543 return PyString_FromString(tmpname);
544}
545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546/* Allocate a new block and return a pointer to it.
547 Returns NULL on error.
548*/
549
550static basicblock *
551compiler_new_block(struct compiler *c)
552{
553 basicblock *b;
554 struct compiler_unit *u;
555
556 u = c->u;
557 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000558 if (b == NULL) {
559 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000563 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564 b->b_list = u->u_blocks;
565 u->u_blocks = b;
566 return b;
567}
568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569static basicblock *
570compiler_use_new_block(struct compiler *c)
571{
572 basicblock *block = compiler_new_block(c);
573 if (block == NULL)
574 return NULL;
575 c->u->u_curblock = block;
576 return block;
577}
578
579static basicblock *
580compiler_next_block(struct compiler *c)
581{
582 basicblock *block = compiler_new_block(c);
583 if (block == NULL)
584 return NULL;
585 c->u->u_curblock->b_next = block;
586 c->u->u_curblock = block;
587 return block;
588}
589
590static basicblock *
591compiler_use_next_block(struct compiler *c, basicblock *block)
592{
593 assert(block != NULL);
594 c->u->u_curblock->b_next = block;
595 c->u->u_curblock = block;
596 return block;
597}
598
599/* Returns the offset of the next instruction in the current block's
600 b_instr array. Resizes the b_instr as necessary.
601 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000602*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603
604static int
605compiler_next_instr(struct compiler *c, basicblock *b)
606{
607 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000608 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000609 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000610 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 if (b->b_instr == NULL) {
612 PyErr_NoMemory();
613 return -1;
614 }
615 b->b_ialloc = DEFAULT_BLOCK_SIZE;
616 memset((char *)b->b_instr, 0,
617 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000620 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621 size_t oldsize, newsize;
622 oldsize = b->b_ialloc * sizeof(struct instr);
623 newsize = oldsize << 1;
624 if (newsize == 0) {
625 PyErr_NoMemory();
626 return -1;
627 }
628 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000629 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000630 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000631 if (tmp == NULL) {
632 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000634 }
635 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
637 }
638 return b->b_iused++;
639}
640
Jeremy Hylton12603c42006-04-01 16:18:02 +0000641/* Set the i_lineno member of the instruction at offse off if the
642 line number for the current expression/statement (?) has not
643 already been set. If it has been set, the call has no effect.
644
645 Every time a new node is b
Neal Norwitzf733a012006-10-29 18:30:10 +0000646*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648static void
649compiler_set_lineno(struct compiler *c, int off)
650{
651 basicblock *b;
652 if (c->u->u_lineno_set)
653 return;
654 c->u->u_lineno_set = true;
655 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657}
658
659static int
660opcode_stack_effect(int opcode, int oparg)
661{
662 switch (opcode) {
663 case POP_TOP:
664 return -1;
665 case ROT_TWO:
666 case ROT_THREE:
667 return 0;
668 case DUP_TOP:
669 return 1;
670 case ROT_FOUR:
671 return 0;
672
673 case UNARY_POSITIVE:
674 case UNARY_NEGATIVE:
675 case UNARY_NOT:
676 case UNARY_CONVERT:
677 case UNARY_INVERT:
678 return 0;
679
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000680 case LIST_APPEND:
681 return -2;
682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683 case BINARY_POWER:
684 case BINARY_MULTIPLY:
685 case BINARY_DIVIDE:
686 case BINARY_MODULO:
687 case BINARY_ADD:
688 case BINARY_SUBTRACT:
689 case BINARY_SUBSCR:
690 case BINARY_FLOOR_DIVIDE:
691 case BINARY_TRUE_DIVIDE:
692 return -1;
693 case INPLACE_FLOOR_DIVIDE:
694 case INPLACE_TRUE_DIVIDE:
695 return -1;
696
697 case SLICE+0:
698 return 1;
699 case SLICE+1:
700 return 0;
701 case SLICE+2:
702 return 0;
703 case SLICE+3:
704 return -1;
705
706 case STORE_SLICE+0:
707 return -2;
708 case STORE_SLICE+1:
709 return -3;
710 case STORE_SLICE+2:
711 return -3;
712 case STORE_SLICE+3:
713 return -4;
714
715 case DELETE_SLICE+0:
716 return -1;
717 case DELETE_SLICE+1:
718 return -2;
719 case DELETE_SLICE+2:
720 return -2;
721 case DELETE_SLICE+3:
722 return -3;
723
724 case INPLACE_ADD:
725 case INPLACE_SUBTRACT:
726 case INPLACE_MULTIPLY:
727 case INPLACE_DIVIDE:
728 case INPLACE_MODULO:
729 return -1;
730 case STORE_SUBSCR:
731 return -3;
Raymond Hettingereffde122007-12-18 18:26:18 +0000732 case STORE_MAP:
733 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734 case DELETE_SUBSCR:
735 return -2;
736
737 case BINARY_LSHIFT:
738 case BINARY_RSHIFT:
739 case BINARY_AND:
740 case BINARY_XOR:
741 case BINARY_OR:
742 return -1;
743 case INPLACE_POWER:
744 return -1;
745 case GET_ITER:
746 return 0;
747
748 case PRINT_EXPR:
749 return -1;
750 case PRINT_ITEM:
751 return -1;
752 case PRINT_NEWLINE:
753 return 0;
754 case PRINT_ITEM_TO:
755 return -2;
756 case PRINT_NEWLINE_TO:
757 return -1;
758 case INPLACE_LSHIFT:
759 case INPLACE_RSHIFT:
760 case INPLACE_AND:
761 case INPLACE_XOR:
762 case INPLACE_OR:
763 return -1;
764 case BREAK_LOOP:
765 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000766 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000767 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768 case LOAD_LOCALS:
769 return 1;
770 case RETURN_VALUE:
771 return -1;
772 case IMPORT_STAR:
773 return -1;
774 case EXEC_STMT:
775 return -3;
776 case YIELD_VALUE:
777 return 0;
778
779 case POP_BLOCK:
780 return 0;
781 case END_FINALLY:
782 return -1; /* or -2 or -3 if exception occurred */
783 case BUILD_CLASS:
784 return -2;
785
786 case STORE_NAME:
787 return -1;
788 case DELETE_NAME:
789 return 0;
790 case UNPACK_SEQUENCE:
791 return oparg-1;
792 case FOR_ITER:
793 return 1;
794
795 case STORE_ATTR:
796 return -2;
797 case DELETE_ATTR:
798 return -1;
799 case STORE_GLOBAL:
800 return -1;
801 case DELETE_GLOBAL:
802 return 0;
803 case DUP_TOPX:
804 return oparg;
805 case LOAD_CONST:
806 return 1;
807 case LOAD_NAME:
808 return 1;
809 case BUILD_TUPLE:
810 case BUILD_LIST:
811 return 1-oparg;
812 case BUILD_MAP:
813 return 1;
814 case LOAD_ATTR:
815 return 0;
816 case COMPARE_OP:
817 return -1;
818 case IMPORT_NAME:
819 return 0;
820 case IMPORT_FROM:
821 return 1;
822
823 case JUMP_FORWARD:
824 case JUMP_IF_FALSE:
825 case JUMP_IF_TRUE:
826 case JUMP_ABSOLUTE:
827 return 0;
828
829 case LOAD_GLOBAL:
830 return 1;
831
832 case CONTINUE_LOOP:
833 return 0;
834 case SETUP_LOOP:
835 return 0;
836 case SETUP_EXCEPT:
837 case SETUP_FINALLY:
838 return 3; /* actually pushed by an exception */
839
840 case LOAD_FAST:
841 return 1;
842 case STORE_FAST:
843 return -1;
844 case DELETE_FAST:
845 return 0;
846
847 case RAISE_VARARGS:
848 return -oparg;
849#define NARGS(o) (((o) % 256) + 2*((o) / 256))
850 case CALL_FUNCTION:
851 return -NARGS(oparg);
852 case CALL_FUNCTION_VAR:
853 case CALL_FUNCTION_KW:
854 return -NARGS(oparg)-1;
855 case CALL_FUNCTION_VAR_KW:
856 return -NARGS(oparg)-2;
857#undef NARGS
858 case MAKE_FUNCTION:
859 return -oparg;
860 case BUILD_SLICE:
861 if (oparg == 3)
862 return -2;
863 else
864 return -1;
865
866 case MAKE_CLOSURE:
867 return -oparg;
868 case LOAD_CLOSURE:
869 return 1;
870 case LOAD_DEREF:
871 return 1;
872 case STORE_DEREF:
873 return -1;
874 default:
875 fprintf(stderr, "opcode = %d\n", opcode);
876 Py_FatalError("opcode_stack_effect()");
877
878 }
879 return 0; /* not reachable */
880}
881
882/* Add an opcode with no argument.
883 Returns 0 on failure, 1 on success.
884*/
885
886static int
887compiler_addop(struct compiler *c, int opcode)
888{
889 basicblock *b;
890 struct instr *i;
891 int off;
892 off = compiler_next_instr(c, c->u->u_curblock);
893 if (off < 0)
894 return 0;
895 b = c->u->u_curblock;
896 i = &b->b_instr[off];
897 i->i_opcode = opcode;
898 i->i_hasarg = 0;
899 if (opcode == RETURN_VALUE)
900 b->b_return = 1;
901 compiler_set_lineno(c, off);
902 return 1;
903}
904
905static int
906compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
907{
908 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000909 Py_ssize_t arg;
Mark Dickinson105be772008-01-31 22:17:37 +0000910 unsigned char *p, *q;
911 Py_complex z;
912 double d;
913 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000915 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000916 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
917 if (PyFloat_Check(o)) {
Mark Dickinson105be772008-01-31 22:17:37 +0000918 d = PyFloat_AS_DOUBLE(o);
919 p = (unsigned char*) &d;
920 /* all we need is to make the tuple different in either the 0.0
921 * or -0.0 case from all others, just to avoid the "coercion".
922 */
923 if (*p==0 && p[sizeof(double)-1]==0)
924 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
925 else
926 t = PyTuple_Pack(2, o, o->ob_type);
927 }
928 else if (PyComplex_Check(o)) {
929 /* complex case is even messier: we need to make complex(x,
930 0.) different from complex(x, -0.) and complex(0., y)
931 different from complex(-0., y), for any x and y. In
932 particular, all four complex zeros should be
933 distinguished.*/
934 z = PyComplex_AsCComplex(o);
935 p = (unsigned char*) &(z.real);
936 q = (unsigned char*) &(z.imag);
937 /* all that matters here is that on IEEE platforms
938 real_part_zero will be true if z.real == 0., and false if
939 z.real == -0. In fact, real_part_zero will also be true
940 for some other rarely occurring nonzero floats, but this
941 doesn't matter. Similar comments apply to
942 imag_part_zero. */
943 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
944 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
945 if (real_part_zero && imag_part_zero) {
946 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
947 }
948 else if (real_part_zero && !imag_part_zero) {
949 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
950 }
951 else if (!real_part_zero && imag_part_zero) {
952 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
953 }
954 else {
955 t = PyTuple_Pack(2, o, o->ob_type);
956 }
957 }
958 else {
959 t = PyTuple_Pack(2, o, o->ob_type);
Alex Martellid8672aa2007-08-22 21:14:17 +0000960 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000961 if (t == NULL)
Mark Dickinson105be772008-01-31 22:17:37 +0000962 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
964 v = PyDict_GetItem(dict, t);
965 if (!v) {
966 arg = PyDict_Size(dict);
967 v = PyInt_FromLong(arg);
968 if (!v) {
969 Py_DECREF(t);
970 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000971 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 if (PyDict_SetItem(dict, t, v) < 0) {
973 Py_DECREF(t);
974 Py_DECREF(v);
975 return -1;
976 }
977 Py_DECREF(v);
978 }
979 else
980 arg = PyInt_AsLong(v);
981 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983}
984
985static int
986compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
987 PyObject *o)
988{
989 int arg = compiler_add_o(c, dict, o);
990 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992 return compiler_addop_i(c, opcode, arg);
993}
994
995static int
996compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000997 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998{
999 int arg;
1000 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1001 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 arg = compiler_add_o(c, dict, mangled);
1004 Py_DECREF(mangled);
1005 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007 return compiler_addop_i(c, opcode, arg);
1008}
1009
1010/* Add an opcode with an integer argument.
1011 Returns 0 on failure, 1 on success.
1012*/
1013
1014static int
1015compiler_addop_i(struct compiler *c, int opcode, int oparg)
1016{
1017 struct instr *i;
1018 int off;
1019 off = compiler_next_instr(c, c->u->u_curblock);
1020 if (off < 0)
1021 return 0;
1022 i = &c->u->u_curblock->b_instr[off];
1023 i->i_opcode = opcode;
1024 i->i_oparg = oparg;
1025 i->i_hasarg = 1;
1026 compiler_set_lineno(c, off);
1027 return 1;
1028}
1029
1030static int
1031compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1032{
1033 struct instr *i;
1034 int off;
1035
1036 assert(b != NULL);
1037 off = compiler_next_instr(c, c->u->u_curblock);
1038 if (off < 0)
1039 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040 i = &c->u->u_curblock->b_instr[off];
1041 i->i_opcode = opcode;
1042 i->i_target = b;
1043 i->i_hasarg = 1;
1044 if (absolute)
1045 i->i_jabs = 1;
1046 else
1047 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001048 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049 return 1;
1050}
1051
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001052/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1053 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054 it as the current block. NEXT_BLOCK() also creates an implicit jump
1055 from the current block to the new block.
1056*/
1057
Neal Norwitzf733a012006-10-29 18:30:10 +00001058/* The returns inside these macros make it impossible to decref objects
1059 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060*/
1061
1062
1063#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001064 if (compiler_use_new_block((C)) == NULL) \
1065 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066}
1067
1068#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001069 if (compiler_next_block((C)) == NULL) \
1070 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
1073#define ADDOP(C, OP) { \
1074 if (!compiler_addop((C), (OP))) \
1075 return 0; \
1076}
1077
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001078#define ADDOP_IN_SCOPE(C, OP) { \
1079 if (!compiler_addop((C), (OP))) { \
1080 compiler_exit_scope(c); \
1081 return 0; \
1082 } \
1083}
1084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085#define ADDOP_O(C, OP, O, TYPE) { \
1086 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1087 return 0; \
1088}
1089
1090#define ADDOP_NAME(C, OP, O, TYPE) { \
1091 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1092 return 0; \
1093}
1094
1095#define ADDOP_I(C, OP, O) { \
1096 if (!compiler_addop_i((C), (OP), (O))) \
1097 return 0; \
1098}
1099
1100#define ADDOP_JABS(C, OP, O) { \
1101 if (!compiler_addop_j((C), (OP), (O), 1)) \
1102 return 0; \
1103}
1104
1105#define ADDOP_JREL(C, OP, O) { \
1106 if (!compiler_addop_j((C), (OP), (O), 0)) \
1107 return 0; \
1108}
1109
1110/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1111 the ASDL name to synthesize the name of the C type and the visit function.
1112*/
1113
1114#define VISIT(C, TYPE, V) {\
1115 if (!compiler_visit_ ## TYPE((C), (V))) \
1116 return 0; \
1117}
1118
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001119#define VISIT_IN_SCOPE(C, TYPE, V) {\
1120 if (!compiler_visit_ ## TYPE((C), (V))) { \
1121 compiler_exit_scope(c); \
1122 return 0; \
1123 } \
1124}
1125
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126#define VISIT_SLICE(C, V, CTX) {\
1127 if (!compiler_visit_slice((C), (V), (CTX))) \
1128 return 0; \
1129}
1130
1131#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001134 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001135 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001136 if (!compiler_visit_ ## TYPE((C), elt)) \
1137 return 0; \
1138 } \
1139}
1140
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001141#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001143 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001144 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001145 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001146 if (!compiler_visit_ ## TYPE((C), elt)) { \
1147 compiler_exit_scope(c); \
1148 return 0; \
1149 } \
1150 } \
1151}
1152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153static int
1154compiler_isdocstring(stmt_ty s)
1155{
1156 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001157 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 return s->v.Expr.value->kind == Str_kind;
1159}
1160
1161/* Compile a sequence of statements, checking for a docstring. */
1162
1163static int
1164compiler_body(struct compiler *c, asdl_seq *stmts)
1165{
1166 int i = 0;
1167 stmt_ty st;
1168
1169 if (!asdl_seq_LEN(stmts))
1170 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001171 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001172 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1173 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 i = 1;
1175 VISIT(c, expr, st->v.Expr.value);
1176 if (!compiler_nameop(c, __doc__, Store))
1177 return 0;
1178 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001179 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001180 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181 return 1;
1182}
1183
1184static PyCodeObject *
1185compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001186{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001187 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001188 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 static PyObject *module;
1190 if (!module) {
Christian Heimesd7e1b2b2008-01-28 02:07:53 +00001191 module = PyString_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192 if (!module)
1193 return NULL;
1194 }
Neal Norwitzed657552006-07-10 00:04:44 +00001195 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1196 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001197 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 switch (mod->kind) {
1199 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001200 if (!compiler_body(c, mod->v.Module.body)) {
1201 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 break;
1205 case Interactive_kind:
1206 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001207 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001208 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 break;
1210 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001211 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001212 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 break;
1214 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001215 PyErr_SetString(PyExc_SystemError,
1216 "suite should not be possible");
1217 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001218 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001219 PyErr_Format(PyExc_SystemError,
1220 "module kind %d should not be possible",
1221 mod->kind);
1222 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224 co = assemble(c, addNone);
1225 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001226 return co;
1227}
1228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229/* The test for LOCAL must come before the test for FREE in order to
1230 handle classes where name is both local and free. The local var is
1231 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001232*/
1233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234static int
1235get_ref_type(struct compiler *c, PyObject *name)
1236{
1237 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001238 if (scope == 0) {
1239 char buf[350];
1240 PyOS_snprintf(buf, sizeof(buf),
1241 "unknown scope for %.100s in %.100s(%s) in %s\n"
1242 "symbols: %s\nlocals: %s\nglobals: %s\n",
1243 PyString_AS_STRING(name),
1244 PyString_AS_STRING(c->u->u_name),
1245 PyObject_REPR(c->u->u_ste->ste_id),
1246 c->c_filename,
1247 PyObject_REPR(c->u->u_ste->ste_symbols),
1248 PyObject_REPR(c->u->u_varnames),
1249 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 Py_FatalError(buf);
1252 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001253
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001254 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255}
1256
1257static int
1258compiler_lookup_arg(PyObject *dict, PyObject *name)
1259{
1260 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001261 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001263 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001265 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001267 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268 return PyInt_AS_LONG(v);
1269}
1270
1271static int
1272compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1273{
1274 int i, free = PyCode_GetNumFree(co);
1275 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001276 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1277 ADDOP_I(c, MAKE_FUNCTION, args);
1278 return 1;
1279 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001280 for (i = 0; i < free; ++i) {
1281 /* Bypass com_addop_varname because it will generate
1282 LOAD_DEREF but LOAD_CLOSURE is needed.
1283 */
1284 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1285 int arg, reftype;
1286
1287 /* Special case: If a class contains a method with a
1288 free variable that has the same name as a method,
1289 the name will be considered free *and* local in the
1290 class. It should be handled by the closure, as
1291 well as by the normal name loookup logic.
1292 */
1293 reftype = get_ref_type(c, name);
1294 if (reftype == CELL)
1295 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1296 else /* (reftype == FREE) */
1297 arg = compiler_lookup_arg(c->u->u_freevars, name);
1298 if (arg == -1) {
1299 printf("lookup %s in %s %d %d\n"
1300 "freevars of %s: %s\n",
1301 PyObject_REPR(name),
1302 PyString_AS_STRING(c->u->u_name),
1303 reftype, arg,
1304 PyString_AS_STRING(co->co_name),
1305 PyObject_REPR(co->co_freevars));
1306 Py_FatalError("compiler_make_closure()");
1307 }
1308 ADDOP_I(c, LOAD_CLOSURE, arg);
1309 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001310 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001312 ADDOP_I(c, MAKE_CLOSURE, args);
1313 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314}
1315
1316static int
1317compiler_decorators(struct compiler *c, asdl_seq* decos)
1318{
1319 int i;
1320
1321 if (!decos)
1322 return 1;
1323
1324 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001325 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326 }
1327 return 1;
1328}
1329
1330static int
1331compiler_arguments(struct compiler *c, arguments_ty args)
1332{
1333 int i;
1334 int n = asdl_seq_LEN(args->args);
1335 /* Correctly handle nested argument lists */
1336 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001337 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338 if (arg->kind == Tuple_kind) {
1339 PyObject *id = PyString_FromFormat(".%d", i);
1340 if (id == NULL) {
1341 return 0;
1342 }
1343 if (!compiler_nameop(c, id, Load)) {
1344 Py_DECREF(id);
1345 return 0;
1346 }
1347 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001348 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349 }
1350 }
1351 return 1;
1352}
1353
1354static int
1355compiler_function(struct compiler *c, stmt_ty s)
1356{
1357 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001358 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 arguments_ty args = s->v.FunctionDef.args;
1360 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001361 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362 int i, n, docstring;
1363
1364 assert(s->kind == FunctionDef_kind);
1365
1366 if (!compiler_decorators(c, decos))
1367 return 0;
1368 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001369 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1371 s->lineno))
1372 return 0;
1373
Anthony Baxter7b782b62006-04-11 12:01:56 +00001374 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001375 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001376 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001377 first_const = st->v.Expr.value->v.Str.s;
1378 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001379 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001380 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001381 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001382
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001383 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384 compiler_arguments(c, args);
1385
1386 c->u->u_argcount = asdl_seq_LEN(args->args);
1387 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001388 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001390 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1391 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392 }
1393 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001394 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 if (co == NULL)
1396 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001398 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001399 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400
1401 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1402 ADDOP_I(c, CALL_FUNCTION, 1);
1403 }
1404
1405 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1406}
1407
1408static int
1409compiler_class(struct compiler *c, stmt_ty s)
1410{
1411 int n;
1412 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001413 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414 /* push class name on stack, needed by BUILD_CLASS */
1415 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1416 /* push the tuple of base classes on the stack */
1417 n = asdl_seq_LEN(s->v.ClassDef.bases);
1418 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001419 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420 ADDOP_I(c, BUILD_TUPLE, n);
1421 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1422 s->lineno))
1423 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001424 c->u->u_private = s->v.ClassDef.name;
1425 Py_INCREF(c->u->u_private);
1426 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427 if (!str || !compiler_nameop(c, str, Load)) {
1428 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001429 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001431 }
1432
1433 Py_DECREF(str);
1434 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 if (!str || !compiler_nameop(c, str, Store)) {
1436 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001437 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001439 }
1440 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001442 if (!compiler_body(c, s->v.ClassDef.body)) {
1443 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001445 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001447 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1448 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001450 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451 if (co == NULL)
1452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001454 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001455 Py_DECREF(co);
1456
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457 ADDOP_I(c, CALL_FUNCTION, 0);
1458 ADDOP(c, BUILD_CLASS);
1459 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1460 return 0;
1461 return 1;
1462}
1463
1464static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001465compiler_ifexp(struct compiler *c, expr_ty e)
1466{
1467 basicblock *end, *next;
1468
1469 assert(e->kind == IfExp_kind);
1470 end = compiler_new_block(c);
1471 if (end == NULL)
1472 return 0;
1473 next = compiler_new_block(c);
1474 if (next == NULL)
1475 return 0;
1476 VISIT(c, expr, e->v.IfExp.test);
1477 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1478 ADDOP(c, POP_TOP);
1479 VISIT(c, expr, e->v.IfExp.body);
1480 ADDOP_JREL(c, JUMP_FORWARD, end);
1481 compiler_use_next_block(c, next);
1482 ADDOP(c, POP_TOP);
1483 VISIT(c, expr, e->v.IfExp.orelse);
1484 compiler_use_next_block(c, end);
1485 return 1;
1486}
1487
1488static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489compiler_lambda(struct compiler *c, expr_ty e)
1490{
1491 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001492 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493 arguments_ty args = e->v.Lambda.args;
1494 assert(e->kind == Lambda_kind);
1495
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001496 if (!name) {
1497 name = PyString_InternFromString("<lambda>");
1498 if (!name)
1499 return 0;
1500 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501
1502 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001503 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1505 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001506
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001507 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508 compiler_arguments(c, args);
1509
1510 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001511 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1512 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001514 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515 if (co == NULL)
1516 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001518 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001519 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520
1521 return 1;
1522}
1523
1524static int
1525compiler_print(struct compiler *c, stmt_ty s)
1526{
1527 int i, n;
1528 bool dest;
1529
1530 assert(s->kind == Print_kind);
1531 n = asdl_seq_LEN(s->v.Print.values);
1532 dest = false;
1533 if (s->v.Print.dest) {
1534 VISIT(c, expr, s->v.Print.dest);
1535 dest = true;
1536 }
1537 for (i = 0; i < n; i++) {
1538 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1539 if (dest) {
1540 ADDOP(c, DUP_TOP);
1541 VISIT(c, expr, e);
1542 ADDOP(c, ROT_TWO);
1543 ADDOP(c, PRINT_ITEM_TO);
1544 }
1545 else {
1546 VISIT(c, expr, e);
1547 ADDOP(c, PRINT_ITEM);
1548 }
1549 }
1550 if (s->v.Print.nl) {
1551 if (dest)
1552 ADDOP(c, PRINT_NEWLINE_TO)
1553 else
1554 ADDOP(c, PRINT_NEWLINE)
1555 }
1556 else if (dest)
1557 ADDOP(c, POP_TOP);
1558 return 1;
1559}
1560
1561static int
1562compiler_if(struct compiler *c, stmt_ty s)
1563{
1564 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001565 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566 assert(s->kind == If_kind);
1567 end = compiler_new_block(c);
1568 if (end == NULL)
1569 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001570 next = compiler_new_block(c);
1571 if (next == NULL)
1572 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001573
1574 constant = expr_constant(s->v.If.test);
1575 /* constant = 0: "if 0"
1576 * constant = 1: "if 1", "if 2", ...
1577 * constant = -1: rest */
1578 if (constant == 0) {
1579 if (s->v.If.orelse)
1580 VISIT_SEQ(c, stmt, s->v.If.orelse);
1581 } else if (constant == 1) {
1582 VISIT_SEQ(c, stmt, s->v.If.body);
1583 } else {
1584 VISIT(c, expr, s->v.If.test);
1585 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1586 ADDOP(c, POP_TOP);
1587 VISIT_SEQ(c, stmt, s->v.If.body);
1588 ADDOP_JREL(c, JUMP_FORWARD, end);
1589 compiler_use_next_block(c, next);
1590 ADDOP(c, POP_TOP);
1591 if (s->v.If.orelse)
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001592 VISIT_SEQ(c, stmt, s->v.If.orelse);
Georg Brandlddbaa662006-06-04 21:56:52 +00001593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594 compiler_use_next_block(c, end);
1595 return 1;
1596}
1597
1598static int
1599compiler_for(struct compiler *c, stmt_ty s)
1600{
1601 basicblock *start, *cleanup, *end;
1602
1603 start = compiler_new_block(c);
1604 cleanup = compiler_new_block(c);
1605 end = compiler_new_block(c);
1606 if (start == NULL || end == NULL || cleanup == NULL)
1607 return 0;
1608 ADDOP_JREL(c, SETUP_LOOP, end);
1609 if (!compiler_push_fblock(c, LOOP, start))
1610 return 0;
1611 VISIT(c, expr, s->v.For.iter);
1612 ADDOP(c, GET_ITER);
1613 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001614 /* XXX(nnorwitz): is there a better way to handle this?
1615 for loops are special, we want to be able to trace them
1616 each time around, so we need to set an extra line number. */
1617 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 ADDOP_JREL(c, FOR_ITER, cleanup);
1619 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001620 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1622 compiler_use_next_block(c, cleanup);
1623 ADDOP(c, POP_BLOCK);
1624 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001625 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626 compiler_use_next_block(c, end);
1627 return 1;
1628}
1629
1630static int
1631compiler_while(struct compiler *c, stmt_ty s)
1632{
1633 basicblock *loop, *orelse, *end, *anchor = NULL;
1634 int constant = expr_constant(s->v.While.test);
1635
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001636 if (constant == 0) {
1637 if (s->v.While.orelse)
1638 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639 return 1;
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001640 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001641 loop = compiler_new_block(c);
1642 end = compiler_new_block(c);
1643 if (constant == -1) {
1644 anchor = compiler_new_block(c);
1645 if (anchor == NULL)
1646 return 0;
1647 }
1648 if (loop == NULL || end == NULL)
1649 return 0;
1650 if (s->v.While.orelse) {
1651 orelse = compiler_new_block(c);
1652 if (orelse == NULL)
1653 return 0;
1654 }
1655 else
1656 orelse = NULL;
1657
1658 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001659 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660 if (!compiler_push_fblock(c, LOOP, loop))
1661 return 0;
1662 if (constant == -1) {
1663 VISIT(c, expr, s->v.While.test);
1664 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1665 ADDOP(c, POP_TOP);
1666 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001667 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1669
1670 /* XXX should the two POP instructions be in a separate block
1671 if there is no else clause ?
1672 */
1673
1674 if (constant == -1) {
1675 compiler_use_next_block(c, anchor);
1676 ADDOP(c, POP_TOP);
1677 ADDOP(c, POP_BLOCK);
1678 }
1679 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001680 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001681 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 compiler_use_next_block(c, end);
1683
1684 return 1;
1685}
1686
1687static int
1688compiler_continue(struct compiler *c)
1689{
1690 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001691 static const char IN_FINALLY_ERROR_MSG[] =
1692 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693 int i;
1694
1695 if (!c->u->u_nfblocks)
1696 return compiler_error(c, LOOP_ERROR_MSG);
1697 i = c->u->u_nfblocks - 1;
1698 switch (c->u->u_fblock[i].fb_type) {
1699 case LOOP:
1700 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1701 break;
1702 case EXCEPT:
1703 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001704 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1705 /* Prevent continue anywhere under a finally
1706 even if hidden in a sub-try or except. */
1707 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1708 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1709 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710 if (i == -1)
1711 return compiler_error(c, LOOP_ERROR_MSG);
1712 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1713 break;
1714 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001715 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001716 }
1717
1718 return 1;
1719}
1720
1721/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1722
1723 SETUP_FINALLY L
1724 <code for body>
1725 POP_BLOCK
1726 LOAD_CONST <None>
1727 L: <code for finalbody>
1728 END_FINALLY
1729
1730 The special instructions use the block stack. Each block
1731 stack entry contains the instruction that created it (here
1732 SETUP_FINALLY), the level of the value stack at the time the
1733 block stack entry was created, and a label (here L).
1734
1735 SETUP_FINALLY:
1736 Pushes the current value stack level and the label
1737 onto the block stack.
1738 POP_BLOCK:
1739 Pops en entry from the block stack, and pops the value
1740 stack until its level is the same as indicated on the
1741 block stack. (The label is ignored.)
1742 END_FINALLY:
1743 Pops a variable number of entries from the *value* stack
1744 and re-raises the exception they specify. The number of
1745 entries popped depends on the (pseudo) exception type.
1746
1747 The block stack is unwound when an exception is raised:
1748 when a SETUP_FINALLY entry is found, the exception is pushed
1749 onto the value stack (and the exception condition is cleared),
1750 and the interpreter jumps to the label gotten from the block
1751 stack.
1752*/
1753
1754static int
1755compiler_try_finally(struct compiler *c, stmt_ty s)
1756{
1757 basicblock *body, *end;
1758 body = compiler_new_block(c);
1759 end = compiler_new_block(c);
1760 if (body == NULL || end == NULL)
1761 return 0;
1762
1763 ADDOP_JREL(c, SETUP_FINALLY, end);
1764 compiler_use_next_block(c, body);
1765 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1766 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001767 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768 ADDOP(c, POP_BLOCK);
1769 compiler_pop_fblock(c, FINALLY_TRY, body);
1770
1771 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1772 compiler_use_next_block(c, end);
1773 if (!compiler_push_fblock(c, FINALLY_END, end))
1774 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001775 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776 ADDOP(c, END_FINALLY);
1777 compiler_pop_fblock(c, FINALLY_END, end);
1778
1779 return 1;
1780}
1781
1782/*
1783 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1784 (The contents of the value stack is shown in [], with the top
1785 at the right; 'tb' is trace-back info, 'val' the exception's
1786 associated value, and 'exc' the exception.)
1787
1788 Value stack Label Instruction Argument
1789 [] SETUP_EXCEPT L1
1790 [] <code for S>
1791 [] POP_BLOCK
1792 [] JUMP_FORWARD L0
1793
1794 [tb, val, exc] L1: DUP )
1795 [tb, val, exc, exc] <evaluate E1> )
1796 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1797 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1798 [tb, val, exc, 1] POP )
1799 [tb, val, exc] POP
1800 [tb, val] <assign to V1> (or POP if no V1)
1801 [tb] POP
1802 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001803 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804
1805 [tb, val, exc, 0] L2: POP
1806 [tb, val, exc] DUP
1807 .............................etc.......................
1808
1809 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001810 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811
1812 [] L0: <next statement>
1813
1814 Of course, parts are not generated if Vi or Ei is not present.
1815*/
1816static int
1817compiler_try_except(struct compiler *c, stmt_ty s)
1818{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001819 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820 int i, n;
1821
1822 body = compiler_new_block(c);
1823 except = compiler_new_block(c);
1824 orelse = compiler_new_block(c);
1825 end = compiler_new_block(c);
1826 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1827 return 0;
1828 ADDOP_JREL(c, SETUP_EXCEPT, except);
1829 compiler_use_next_block(c, body);
1830 if (!compiler_push_fblock(c, EXCEPT, body))
1831 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001832 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833 ADDOP(c, POP_BLOCK);
1834 compiler_pop_fblock(c, EXCEPT, body);
1835 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1836 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1837 compiler_use_next_block(c, except);
1838 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001839 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840 s->v.TryExcept.handlers, i);
1841 if (!handler->type && i < n-1)
1842 return compiler_error(c, "default 'except:' must be last");
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001843 c->u->u_lineno_set = false;
1844 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845 except = compiler_new_block(c);
1846 if (except == NULL)
1847 return 0;
1848 if (handler->type) {
1849 ADDOP(c, DUP_TOP);
1850 VISIT(c, expr, handler->type);
1851 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1852 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1853 ADDOP(c, POP_TOP);
1854 }
1855 ADDOP(c, POP_TOP);
1856 if (handler->name) {
1857 VISIT(c, expr, handler->name);
1858 }
1859 else {
1860 ADDOP(c, POP_TOP);
1861 }
1862 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001863 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 ADDOP_JREL(c, JUMP_FORWARD, end);
1865 compiler_use_next_block(c, except);
1866 if (handler->type)
1867 ADDOP(c, POP_TOP);
1868 }
1869 ADDOP(c, END_FINALLY);
1870 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001871 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872 compiler_use_next_block(c, end);
1873 return 1;
1874}
1875
1876static int
1877compiler_import_as(struct compiler *c, identifier name, identifier asname)
1878{
1879 /* The IMPORT_NAME opcode was already generated. This function
1880 merely needs to bind the result to a name.
1881
1882 If there is a dot in name, we need to split it and emit a
1883 LOAD_ATTR for each name.
1884 */
1885 const char *src = PyString_AS_STRING(name);
1886 const char *dot = strchr(src, '.');
1887 if (dot) {
1888 /* Consume the base module name to get the first attribute */
1889 src = dot + 1;
1890 while (dot) {
1891 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001892 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001893 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001894 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001896 if (!attr)
1897 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001899 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001900 src = dot + 1;
1901 }
1902 }
1903 return compiler_nameop(c, asname, Store);
1904}
1905
1906static int
1907compiler_import(struct compiler *c, stmt_ty s)
1908{
1909 /* The Import node stores a module name like a.b.c as a single
1910 string. This is convenient for all cases except
1911 import a.b.c as d
1912 where we need to parse that string to extract the individual
1913 module names.
1914 XXX Perhaps change the representation to make this case simpler?
1915 */
1916 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001919 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001921 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922
Neal Norwitzcbce2802006-04-03 06:26:32 +00001923 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001924 level = PyInt_FromLong(0);
1925 else
1926 level = PyInt_FromLong(-1);
1927
1928 if (level == NULL)
1929 return 0;
1930
1931 ADDOP_O(c, LOAD_CONST, level, consts);
1932 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1934 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1935
1936 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001937 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001938 if (!r)
1939 return r;
1940 }
1941 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942 identifier tmp = alias->name;
1943 const char *base = PyString_AS_STRING(alias->name);
1944 char *dot = strchr(base, '.');
1945 if (dot)
1946 tmp = PyString_FromStringAndSize(base,
1947 dot - base);
1948 r = compiler_nameop(c, tmp, Store);
1949 if (dot) {
1950 Py_DECREF(tmp);
1951 }
1952 if (!r)
1953 return r;
1954 }
1955 }
1956 return 1;
1957}
1958
1959static int
1960compiler_from_import(struct compiler *c, stmt_ty s)
1961{
1962 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963
1964 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001965 PyObject *level;
1966
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 if (!names)
1968 return 0;
1969
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001970 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001971 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001972 level = PyInt_FromLong(-1);
1973 else
1974 level = PyInt_FromLong(s->v.ImportFrom.level);
1975
1976 if (!level) {
1977 Py_DECREF(names);
1978 return 0;
1979 }
1980
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981 /* build up the names */
1982 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001983 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 Py_INCREF(alias->name);
1985 PyTuple_SET_ITEM(names, i, alias->name);
1986 }
1987
1988 if (s->lineno > c->c_future->ff_lineno) {
1989 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1990 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001991 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 Py_DECREF(names);
1993 return compiler_error(c,
1994 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001995 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996
1997 }
1998 }
1999
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002000 ADDOP_O(c, LOAD_CONST, level, consts);
2001 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002003 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2005 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002006 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 identifier store_name;
2008
2009 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2010 assert(n == 1);
2011 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 }
2014
2015 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2016 store_name = alias->name;
2017 if (alias->asname)
2018 store_name = alias->asname;
2019
2020 if (!compiler_nameop(c, store_name, Store)) {
2021 Py_DECREF(names);
2022 return 0;
2023 }
2024 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002025 /* remove imported module */
2026 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 return 1;
2028}
2029
2030static int
2031compiler_assert(struct compiler *c, stmt_ty s)
2032{
2033 static PyObject *assertion_error = NULL;
2034 basicblock *end;
2035
2036 if (Py_OptimizeFlag)
2037 return 1;
2038 if (assertion_error == NULL) {
Christian Heimesd7e1b2b2008-01-28 02:07:53 +00002039 assertion_error = PyString_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040 if (assertion_error == NULL)
2041 return 0;
2042 }
2043 VISIT(c, expr, s->v.Assert.test);
2044 end = compiler_new_block(c);
2045 if (end == NULL)
2046 return 0;
2047 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2048 ADDOP(c, POP_TOP);
2049 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2050 if (s->v.Assert.msg) {
2051 VISIT(c, expr, s->v.Assert.msg);
2052 ADDOP_I(c, RAISE_VARARGS, 2);
2053 }
2054 else {
2055 ADDOP_I(c, RAISE_VARARGS, 1);
2056 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002057 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 ADDOP(c, POP_TOP);
2059 return 1;
2060}
2061
2062static int
2063compiler_visit_stmt(struct compiler *c, stmt_ty s)
2064{
2065 int i, n;
2066
Neal Norwitzf733a012006-10-29 18:30:10 +00002067 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 c->u->u_lineno = s->lineno;
2069 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002070
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002072 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002074 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002076 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 if (c->u->u_ste->ste_type != FunctionBlock)
2078 return compiler_error(c, "'return' outside function");
2079 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 VISIT(c, expr, s->v.Return.value);
2081 }
2082 else
2083 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2084 ADDOP(c, RETURN_VALUE);
2085 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002086 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002087 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 n = asdl_seq_LEN(s->v.Assign.targets);
2091 VISIT(c, expr, s->v.Assign.value);
2092 for (i = 0; i < n; i++) {
2093 if (i < n - 1)
2094 ADDOP(c, DUP_TOP);
2095 VISIT(c, expr,
2096 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2097 }
2098 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002101 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002107 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 n = 0;
2111 if (s->v.Raise.type) {
2112 VISIT(c, expr, s->v.Raise.type);
2113 n++;
2114 if (s->v.Raise.inst) {
2115 VISIT(c, expr, s->v.Raise.inst);
2116 n++;
2117 if (s->v.Raise.tback) {
2118 VISIT(c, expr, s->v.Raise.tback);
2119 n++;
2120 }
2121 }
2122 }
2123 ADDOP_I(c, RAISE_VARARGS, n);
2124 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002125 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002131 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002133 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002135 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 VISIT(c, expr, s->v.Exec.body);
2137 if (s->v.Exec.globals) {
2138 VISIT(c, expr, s->v.Exec.globals);
2139 if (s->v.Exec.locals) {
2140 VISIT(c, expr, s->v.Exec.locals);
2141 } else {
2142 ADDOP(c, DUP_TOP);
2143 }
2144 } else {
2145 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2146 ADDOP(c, DUP_TOP);
2147 }
2148 ADDOP(c, EXEC_STMT);
2149 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002150 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002152 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002154 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 ADDOP(c, PRINT_EXPR);
2156 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002157 else if (s->v.Expr.value->kind != Str_kind &&
2158 s->v.Expr.value->kind != Num_kind) {
2159 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160 ADDOP(c, POP_TOP);
2161 }
2162 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002163 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002165 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002166 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 return compiler_error(c, "'break' outside loop");
2168 ADDOP(c, BREAK_LOOP);
2169 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002170 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002171 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002172 case With_kind:
2173 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174 }
2175 return 1;
2176}
2177
2178static int
2179unaryop(unaryop_ty op)
2180{
2181 switch (op) {
2182 case Invert:
2183 return UNARY_INVERT;
2184 case Not:
2185 return UNARY_NOT;
2186 case UAdd:
2187 return UNARY_POSITIVE;
2188 case USub:
2189 return UNARY_NEGATIVE;
2190 }
2191 return 0;
2192}
2193
2194static int
2195binop(struct compiler *c, operator_ty op)
2196{
2197 switch (op) {
2198 case Add:
2199 return BINARY_ADD;
2200 case Sub:
2201 return BINARY_SUBTRACT;
2202 case Mult:
2203 return BINARY_MULTIPLY;
2204 case Div:
2205 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2206 return BINARY_TRUE_DIVIDE;
2207 else
2208 return BINARY_DIVIDE;
2209 case Mod:
2210 return BINARY_MODULO;
2211 case Pow:
2212 return BINARY_POWER;
2213 case LShift:
2214 return BINARY_LSHIFT;
2215 case RShift:
2216 return BINARY_RSHIFT;
2217 case BitOr:
2218 return BINARY_OR;
2219 case BitXor:
2220 return BINARY_XOR;
2221 case BitAnd:
2222 return BINARY_AND;
2223 case FloorDiv:
2224 return BINARY_FLOOR_DIVIDE;
2225 }
2226 return 0;
2227}
2228
2229static int
2230cmpop(cmpop_ty op)
2231{
2232 switch (op) {
2233 case Eq:
2234 return PyCmp_EQ;
2235 case NotEq:
2236 return PyCmp_NE;
2237 case Lt:
2238 return PyCmp_LT;
2239 case LtE:
2240 return PyCmp_LE;
2241 case Gt:
2242 return PyCmp_GT;
2243 case GtE:
2244 return PyCmp_GE;
2245 case Is:
2246 return PyCmp_IS;
2247 case IsNot:
2248 return PyCmp_IS_NOT;
2249 case In:
2250 return PyCmp_IN;
2251 case NotIn:
2252 return PyCmp_NOT_IN;
2253 }
2254 return PyCmp_BAD;
2255}
2256
2257static int
2258inplace_binop(struct compiler *c, operator_ty op)
2259{
2260 switch (op) {
2261 case Add:
2262 return INPLACE_ADD;
2263 case Sub:
2264 return INPLACE_SUBTRACT;
2265 case Mult:
2266 return INPLACE_MULTIPLY;
2267 case Div:
2268 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2269 return INPLACE_TRUE_DIVIDE;
2270 else
2271 return INPLACE_DIVIDE;
2272 case Mod:
2273 return INPLACE_MODULO;
2274 case Pow:
2275 return INPLACE_POWER;
2276 case LShift:
2277 return INPLACE_LSHIFT;
2278 case RShift:
2279 return INPLACE_RSHIFT;
2280 case BitOr:
2281 return INPLACE_OR;
2282 case BitXor:
2283 return INPLACE_XOR;
2284 case BitAnd:
2285 return INPLACE_AND;
2286 case FloorDiv:
2287 return INPLACE_FLOOR_DIVIDE;
2288 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002289 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002290 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 return 0;
2292}
2293
2294static int
2295compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2296{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002297 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2299
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002300 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002301 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 /* XXX AugStore isn't used anywhere! */
2303
2304 /* First check for assignment to __debug__. Param? */
2305 if ((ctx == Store || ctx == AugStore || ctx == Del)
2306 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2307 return compiler_error(c, "can not assign to __debug__");
2308 }
2309
Jeremy Hylton37075c52007-02-27 01:01:59 +00002310mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002311 if (!mangled)
2312 return 0;
2313
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 op = 0;
2315 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002316 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317 switch (scope) {
2318 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 optype = OP_DEREF;
2321 break;
2322 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002323 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324 optype = OP_DEREF;
2325 break;
2326 case LOCAL:
2327 if (c->u->u_ste->ste_type == FunctionBlock)
2328 optype = OP_FAST;
2329 break;
2330 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002331 if (c->u->u_ste->ste_type == FunctionBlock &&
2332 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 optype = OP_GLOBAL;
2334 break;
2335 case GLOBAL_EXPLICIT:
2336 optype = OP_GLOBAL;
2337 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002338 default:
2339 /* scope can be 0 */
2340 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 }
2342
2343 /* XXX Leave assert here, but handle __doc__ and the like better */
2344 assert(scope || PyString_AS_STRING(name)[0] == '_');
2345
2346 switch (optype) {
2347 case OP_DEREF:
2348 switch (ctx) {
2349 case Load: op = LOAD_DEREF; break;
2350 case Store: op = STORE_DEREF; break;
2351 case AugLoad:
2352 case AugStore:
2353 break;
2354 case Del:
2355 PyErr_Format(PyExc_SyntaxError,
2356 "can not delete variable '%s' referenced "
2357 "in nested scope",
2358 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002359 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002362 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002363 PyErr_SetString(PyExc_SystemError,
2364 "param invalid for deref variable");
2365 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366 }
2367 break;
2368 case OP_FAST:
2369 switch (ctx) {
2370 case Load: op = LOAD_FAST; break;
2371 case Store: op = STORE_FAST; break;
2372 case Del: op = DELETE_FAST; break;
2373 case AugLoad:
2374 case AugStore:
2375 break;
2376 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002377 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002378 PyErr_SetString(PyExc_SystemError,
2379 "param invalid for local variable");
2380 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002381 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002382 ADDOP_O(c, op, mangled, varnames);
2383 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384 return 1;
2385 case OP_GLOBAL:
2386 switch (ctx) {
2387 case Load: op = LOAD_GLOBAL; break;
2388 case Store: op = STORE_GLOBAL; break;
2389 case Del: op = DELETE_GLOBAL; break;
2390 case AugLoad:
2391 case AugStore:
2392 break;
2393 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002394 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002395 PyErr_SetString(PyExc_SystemError,
2396 "param invalid for global variable");
2397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002398 }
2399 break;
2400 case OP_NAME:
2401 switch (ctx) {
2402 case Load: op = LOAD_NAME; break;
2403 case Store: op = STORE_NAME; break;
2404 case Del: op = DELETE_NAME; break;
2405 case AugLoad:
2406 case AugStore:
2407 break;
2408 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002409 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002410 PyErr_SetString(PyExc_SystemError,
2411 "param invalid for name variable");
2412 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413 }
2414 break;
2415 }
2416
2417 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002418 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002419 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002420 if (arg < 0)
2421 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002422 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423}
2424
2425static int
2426compiler_boolop(struct compiler *c, expr_ty e)
2427{
2428 basicblock *end;
2429 int jumpi, i, n;
2430 asdl_seq *s;
2431
2432 assert(e->kind == BoolOp_kind);
2433 if (e->v.BoolOp.op == And)
2434 jumpi = JUMP_IF_FALSE;
2435 else
2436 jumpi = JUMP_IF_TRUE;
2437 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002438 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 return 0;
2440 s = e->v.BoolOp.values;
2441 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002442 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002444 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002445 ADDOP_JREL(c, jumpi, end);
2446 ADDOP(c, POP_TOP)
2447 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002448 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002449 compiler_use_next_block(c, end);
2450 return 1;
2451}
2452
2453static int
2454compiler_list(struct compiler *c, expr_ty e)
2455{
2456 int n = asdl_seq_LEN(e->v.List.elts);
2457 if (e->v.List.ctx == Store) {
2458 ADDOP_I(c, UNPACK_SEQUENCE, n);
2459 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002460 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 if (e->v.List.ctx == Load) {
2462 ADDOP_I(c, BUILD_LIST, n);
2463 }
2464 return 1;
2465}
2466
2467static int
2468compiler_tuple(struct compiler *c, expr_ty e)
2469{
2470 int n = asdl_seq_LEN(e->v.Tuple.elts);
2471 if (e->v.Tuple.ctx == Store) {
2472 ADDOP_I(c, UNPACK_SEQUENCE, n);
2473 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002474 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 if (e->v.Tuple.ctx == Load) {
2476 ADDOP_I(c, BUILD_TUPLE, n);
2477 }
2478 return 1;
2479}
2480
2481static int
2482compiler_compare(struct compiler *c, expr_ty e)
2483{
2484 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002485 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486
2487 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2488 VISIT(c, expr, e->v.Compare.left);
2489 n = asdl_seq_LEN(e->v.Compare.ops);
2490 assert(n > 0);
2491 if (n > 1) {
2492 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002493 if (cleanup == NULL)
2494 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002495 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002496 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497 }
2498 for (i = 1; i < n; i++) {
2499 ADDOP(c, DUP_TOP);
2500 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002502 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002503 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2505 NEXT_BLOCK(c);
2506 ADDOP(c, POP_TOP);
2507 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002508 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002509 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002511 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002512 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002513 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514 if (n > 1) {
2515 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002516 if (end == NULL)
2517 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518 ADDOP_JREL(c, JUMP_FORWARD, end);
2519 compiler_use_next_block(c, cleanup);
2520 ADDOP(c, ROT_TWO);
2521 ADDOP(c, POP_TOP);
2522 compiler_use_next_block(c, end);
2523 }
2524 return 1;
2525}
2526
2527static int
2528compiler_call(struct compiler *c, expr_ty e)
2529{
2530 int n, code = 0;
2531
2532 VISIT(c, expr, e->v.Call.func);
2533 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002534 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002536 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2538 }
2539 if (e->v.Call.starargs) {
2540 VISIT(c, expr, e->v.Call.starargs);
2541 code |= 1;
2542 }
2543 if (e->v.Call.kwargs) {
2544 VISIT(c, expr, e->v.Call.kwargs);
2545 code |= 2;
2546 }
2547 switch (code) {
2548 case 0:
2549 ADDOP_I(c, CALL_FUNCTION, n);
2550 break;
2551 case 1:
2552 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2553 break;
2554 case 2:
2555 ADDOP_I(c, CALL_FUNCTION_KW, n);
2556 break;
2557 case 3:
2558 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2559 break;
2560 }
2561 return 1;
2562}
2563
2564static int
2565compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002566 asdl_seq *generators, int gen_index,
2567 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568{
2569 /* generate code for the iterator, then each of the ifs,
2570 and then write to the element */
2571
2572 comprehension_ty l;
2573 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002574 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
2576 start = compiler_new_block(c);
2577 skip = compiler_new_block(c);
2578 if_cleanup = compiler_new_block(c);
2579 anchor = compiler_new_block(c);
2580
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002581 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2582 anchor == NULL)
2583 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584
Anthony Baxter7b782b62006-04-11 12:01:56 +00002585 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 VISIT(c, expr, l->iter);
2587 ADDOP(c, GET_ITER);
2588 compiler_use_next_block(c, start);
2589 ADDOP_JREL(c, FOR_ITER, anchor);
2590 NEXT_BLOCK(c);
2591 VISIT(c, expr, l->target);
2592
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002593 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594 n = asdl_seq_LEN(l->ifs);
2595 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002596 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597 VISIT(c, expr, e);
2598 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2599 NEXT_BLOCK(c);
2600 ADDOP(c, POP_TOP);
2601 }
2602
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002603 if (++gen_index < asdl_seq_LEN(generators))
2604 if (!compiler_listcomp_generator(c, tmpname,
2605 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002608 /* only append after the last for generator */
2609 if (gen_index >= asdl_seq_LEN(generators)) {
2610 if (!compiler_nameop(c, tmpname, Load))
2611 return 0;
2612 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002613 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614
2615 compiler_use_next_block(c, skip);
2616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 for (i = 0; i < n; i++) {
2618 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002619 if (i == 0)
2620 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 ADDOP(c, POP_TOP);
2622 }
2623 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2624 compiler_use_next_block(c, anchor);
Georg Brandl2c4fb8d2006-10-29 08:47:08 +00002625 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002627 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628 return 0;
2629
2630 return 1;
2631}
2632
2633static int
2634compiler_listcomp(struct compiler *c, expr_ty e)
2635{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002637 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 asdl_seq *generators = e->v.ListComp.generators;
2639
2640 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002641 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 if (!tmp)
2643 return 0;
2644 ADDOP_I(c, BUILD_LIST, 0);
2645 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002647 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2648 e->v.ListComp.elt);
2649 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 return rc;
2651}
2652
2653static int
2654compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 asdl_seq *generators, int gen_index,
2656 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657{
2658 /* generate code for the iterator, then each of the ifs,
2659 and then write to the element */
2660
2661 comprehension_ty ge;
2662 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002663 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664
2665 start = compiler_new_block(c);
2666 skip = compiler_new_block(c);
2667 if_cleanup = compiler_new_block(c);
2668 anchor = compiler_new_block(c);
2669 end = compiler_new_block(c);
2670
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002671 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 anchor == NULL || end == NULL)
2673 return 0;
2674
Anthony Baxter7b782b62006-04-11 12:01:56 +00002675 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 ADDOP_JREL(c, SETUP_LOOP, end);
2677 if (!compiler_push_fblock(c, LOOP, start))
2678 return 0;
2679
2680 if (gen_index == 0) {
2681 /* Receive outermost iter as an implicit argument */
2682 c->u->u_argcount = 1;
2683 ADDOP_I(c, LOAD_FAST, 0);
2684 }
2685 else {
2686 /* Sub-iter - calculate on the fly */
2687 VISIT(c, expr, ge->iter);
2688 ADDOP(c, GET_ITER);
2689 }
2690 compiler_use_next_block(c, start);
2691 ADDOP_JREL(c, FOR_ITER, anchor);
2692 NEXT_BLOCK(c);
2693 VISIT(c, expr, ge->target);
2694
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002695 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 n = asdl_seq_LEN(ge->ifs);
2697 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002698 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 VISIT(c, expr, e);
2700 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2701 NEXT_BLOCK(c);
2702 ADDOP(c, POP_TOP);
2703 }
2704
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002705 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2707 return 0;
2708
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002709 /* only append after the last 'for' generator */
2710 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 VISIT(c, expr, elt);
2712 ADDOP(c, YIELD_VALUE);
2713 ADDOP(c, POP_TOP);
2714
2715 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002716 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 for (i = 0; i < n; i++) {
2718 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 compiler_use_next_block(c, if_cleanup);
2721
2722 ADDOP(c, POP_TOP);
2723 }
2724 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2725 compiler_use_next_block(c, anchor);
2726 ADDOP(c, POP_BLOCK);
2727 compiler_pop_fblock(c, LOOP, start);
2728 compiler_use_next_block(c, end);
2729
2730 return 1;
2731}
2732
2733static int
2734compiler_genexp(struct compiler *c, expr_ty e)
2735{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002736 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737 PyCodeObject *co;
2738 expr_ty outermost_iter = ((comprehension_ty)
2739 (asdl_seq_GET(e->v.GeneratorExp.generators,
2740 0)))->iter;
2741
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002742 if (!name) {
2743 name = PyString_FromString("<genexpr>");
2744 if (!name)
2745 return 0;
2746 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747
2748 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2749 return 0;
2750 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2751 e->v.GeneratorExp.elt);
2752 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002753 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754 if (co == NULL)
2755 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002757 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002758 Py_DECREF(co);
2759
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760 VISIT(c, expr, outermost_iter);
2761 ADDOP(c, GET_ITER);
2762 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763
2764 return 1;
2765}
2766
2767static int
2768compiler_visit_keyword(struct compiler *c, keyword_ty k)
2769{
2770 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2771 VISIT(c, expr, k->value);
2772 return 1;
2773}
2774
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002775/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776 whether they are true or false.
2777
2778 Return values: 1 for true, 0 for false, -1 for non-constant.
2779 */
2780
2781static int
2782expr_constant(expr_ty e)
2783{
2784 switch (e->kind) {
2785 case Num_kind:
2786 return PyObject_IsTrue(e->v.Num.n);
2787 case Str_kind:
2788 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002789 case Name_kind:
2790 /* __debug__ is not assignable, so we can optimize
2791 * it away in if and while statements */
2792 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002793 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002794 return ! Py_OptimizeFlag;
2795 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 default:
2797 return -1;
2798 }
2799}
2800
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801/*
2802 Implements the with statement from PEP 343.
2803
2804 The semantics outlined in that PEP are as follows:
2805
2806 with EXPR as VAR:
2807 BLOCK
2808
2809 It is implemented roughly as:
2810
Guido van Rossumda5b7012006-05-02 19:47:52 +00002811 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002812 exit = context.__exit__ # not calling it
2813 value = context.__enter__()
2814 try:
2815 VAR = value # if VAR present in the syntax
2816 BLOCK
2817 finally:
2818 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002819 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002820 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002821 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002822 exit(*exc)
2823 */
2824static int
2825compiler_with(struct compiler *c, stmt_ty s)
2826{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002827 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002828 basicblock *block, *finally;
2829 identifier tmpexit, tmpvalue = NULL;
2830
2831 assert(s->kind == With_kind);
2832
Guido van Rossumc2e20742006-02-27 22:32:47 +00002833 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002834 enter_attr = PyString_InternFromString("__enter__");
2835 if (!enter_attr)
2836 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002837 }
2838 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002839 exit_attr = PyString_InternFromString("__exit__");
2840 if (!exit_attr)
2841 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002842 }
2843
2844 block = compiler_new_block(c);
2845 finally = compiler_new_block(c);
2846 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002848
2849 /* Create a temporary variable to hold context.__exit__ */
2850 tmpexit = compiler_new_tmpname(c);
2851 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002852 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002853 PyArena_AddPyObject(c->c_arena, tmpexit);
2854
2855 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002856 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002857 We need to do this rather than preserving it on the stack
2858 because SETUP_FINALLY remembers the stack level.
2859 We need to do the assignment *inside* the try/finally
2860 so that context.__exit__() is called when the assignment
2861 fails. But we need to call context.__enter__() *before*
2862 the try/finally so that if it fails we won't call
2863 context.__exit__().
2864 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002865 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002866 if (tmpvalue == NULL)
2867 return 0;
2868 PyArena_AddPyObject(c->c_arena, tmpvalue);
2869 }
2870
Guido van Rossumda5b7012006-05-02 19:47:52 +00002871 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002872 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002873
2874 /* Squirrel away context.__exit__ */
2875 ADDOP(c, DUP_TOP);
2876 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2877 if (!compiler_nameop(c, tmpexit, Store))
2878 return 0;
2879
2880 /* Call context.__enter__() */
2881 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2882 ADDOP_I(c, CALL_FUNCTION, 0);
2883
2884 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002885 /* Store it in tmpvalue */
2886 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002887 return 0;
2888 }
2889 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002890 /* Discard result from context.__enter__() */
2891 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002892 }
2893
2894 /* Start the try block */
2895 ADDOP_JREL(c, SETUP_FINALLY, finally);
2896
2897 compiler_use_next_block(c, block);
2898 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002899 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002900 }
2901
2902 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002903 /* Bind saved result of context.__enter__() to VAR */
2904 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002905 !compiler_nameop(c, tmpvalue, Del))
2906 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002907 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908 }
2909
2910 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002911 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002912
2913 /* End of try block; start the finally block */
2914 ADDOP(c, POP_BLOCK);
2915 compiler_pop_fblock(c, FINALLY_TRY, block);
2916
2917 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2918 compiler_use_next_block(c, finally);
2919 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002920 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002921
2922 /* Finally block starts; push tmpexit and issue our magic opcode. */
2923 if (!compiler_nameop(c, tmpexit, Load) ||
2924 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002925 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002926 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002927
2928 /* Finally block ends. */
2929 ADDOP(c, END_FINALLY);
2930 compiler_pop_fblock(c, FINALLY_END, finally);
2931 return 1;
2932}
2933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934static int
2935compiler_visit_expr(struct compiler *c, expr_ty e)
2936{
2937 int i, n;
2938
Neal Norwitzf733a012006-10-29 18:30:10 +00002939 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002940 set a new line number for the next instruction.
2941 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 if (e->lineno > c->u->u_lineno) {
2943 c->u->u_lineno = e->lineno;
2944 c->u->u_lineno_set = false;
2945 }
2946 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002947 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002949 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950 VISIT(c, expr, e->v.BinOp.left);
2951 VISIT(c, expr, e->v.BinOp.right);
2952 ADDOP(c, binop(c, e->v.BinOp.op));
2953 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002954 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955 VISIT(c, expr, e->v.UnaryOp.operand);
2956 ADDOP(c, unaryop(e->v.UnaryOp.op));
2957 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002958 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002960 case IfExp_kind:
2961 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002962 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettinger70fcfd02007-12-19 22:14:34 +00002964 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002966 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002967 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00002968 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002969 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00002970 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 }
2972 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002973 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002975 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 return compiler_genexp(c, e);
2977 case Yield_kind:
2978 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002979 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 if (e->v.Yield.value) {
2981 VISIT(c, expr, e->v.Yield.value);
2982 }
2983 else {
2984 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2985 }
2986 ADDOP(c, YIELD_VALUE);
2987 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002988 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002990 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002992 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993 VISIT(c, expr, e->v.Repr.value);
2994 ADDOP(c, UNARY_CONVERT);
2995 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002996 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2998 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002999 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003000 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3001 break;
3002 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003003 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004 if (e->v.Attribute.ctx != AugStore)
3005 VISIT(c, expr, e->v.Attribute.value);
3006 switch (e->v.Attribute.ctx) {
3007 case AugLoad:
3008 ADDOP(c, DUP_TOP);
3009 /* Fall through to load */
3010 case Load:
3011 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3012 break;
3013 case AugStore:
3014 ADDOP(c, ROT_TWO);
3015 /* Fall through to save */
3016 case Store:
3017 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3018 break;
3019 case Del:
3020 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3021 break;
3022 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003023 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003024 PyErr_SetString(PyExc_SystemError,
3025 "param invalid in attribute expression");
3026 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 }
3028 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003029 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 switch (e->v.Subscript.ctx) {
3031 case AugLoad:
3032 VISIT(c, expr, e->v.Subscript.value);
3033 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3034 break;
3035 case Load:
3036 VISIT(c, expr, e->v.Subscript.value);
3037 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3038 break;
3039 case AugStore:
3040 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3041 break;
3042 case Store:
3043 VISIT(c, expr, e->v.Subscript.value);
3044 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3045 break;
3046 case Del:
3047 VISIT(c, expr, e->v.Subscript.value);
3048 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3049 break;
3050 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003051 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003052 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003053 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003054 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 }
3056 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3059 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003060 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003062 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063 return compiler_tuple(c, e);
3064 }
3065 return 1;
3066}
3067
3068static int
3069compiler_augassign(struct compiler *c, stmt_ty s)
3070{
3071 expr_ty e = s->v.AugAssign.target;
3072 expr_ty auge;
3073
3074 assert(s->kind == AugAssign_kind);
3075
3076 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003077 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003079 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003080 if (auge == NULL)
3081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082 VISIT(c, expr, auge);
3083 VISIT(c, expr, s->v.AugAssign.value);
3084 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3085 auge->v.Attribute.ctx = AugStore;
3086 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087 break;
3088 case Subscript_kind:
3089 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003090 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003091 if (auge == NULL)
3092 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003093 VISIT(c, expr, auge);
3094 VISIT(c, expr, s->v.AugAssign.value);
3095 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003096 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003097 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003098 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003099 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003100 if (!compiler_nameop(c, e->v.Name.id, Load))
3101 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003102 VISIT(c, expr, s->v.AugAssign.value);
3103 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3104 return compiler_nameop(c, e->v.Name.id, Store);
3105 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003106 PyErr_Format(PyExc_SystemError,
3107 "invalid node type (%d) for augmented assignment",
3108 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003109 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110 }
3111 return 1;
3112}
3113
3114static int
3115compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3116{
3117 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003118 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3119 PyErr_SetString(PyExc_SystemError,
3120 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003122 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123 f = &c->u->u_fblock[c->u->u_nfblocks++];
3124 f->fb_type = t;
3125 f->fb_block = b;
3126 return 1;
3127}
3128
3129static void
3130compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3131{
3132 struct compiler_unit *u = c->u;
3133 assert(u->u_nfblocks > 0);
3134 u->u_nfblocks--;
3135 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3136 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3137}
3138
Jeremy Hylton82271f12006-10-04 02:24:52 +00003139static int
3140compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003141 int i;
3142 struct compiler_unit *u = c->u;
3143 for (i = 0; i < u->u_nfblocks; ++i) {
3144 if (u->u_fblock[i].fb_type == LOOP)
3145 return 1;
3146 }
3147 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003148}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149/* Raises a SyntaxError and returns 0.
3150 If something goes wrong, a different exception may be raised.
3151*/
3152
3153static int
3154compiler_error(struct compiler *c, const char *errstr)
3155{
3156 PyObject *loc;
3157 PyObject *u = NULL, *v = NULL;
3158
3159 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3160 if (!loc) {
3161 Py_INCREF(Py_None);
3162 loc = Py_None;
3163 }
3164 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3165 Py_None, loc);
3166 if (!u)
3167 goto exit;
3168 v = Py_BuildValue("(zO)", errstr, u);
3169 if (!v)
3170 goto exit;
3171 PyErr_SetObject(PyExc_SyntaxError, v);
3172 exit:
3173 Py_DECREF(loc);
3174 Py_XDECREF(u);
3175 Py_XDECREF(v);
3176 return 0;
3177}
3178
3179static int
3180compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003183 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003185 /* XXX this code is duplicated */
3186 switch (ctx) {
3187 case AugLoad: /* fall through to Load */
3188 case Load: op = BINARY_SUBSCR; break;
3189 case AugStore:/* fall through to Store */
3190 case Store: op = STORE_SUBSCR; break;
3191 case Del: op = DELETE_SUBSCR; break;
3192 case Param:
3193 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003194 "invalid %s kind %d in subscript\n",
3195 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196 return 0;
3197 }
3198 if (ctx == AugLoad) {
3199 ADDOP_I(c, DUP_TOPX, 2);
3200 }
3201 else if (ctx == AugStore) {
3202 ADDOP(c, ROT_THREE);
3203 }
3204 ADDOP(c, op);
3205 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206}
3207
3208static int
3209compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3210{
3211 int n = 2;
3212 assert(s->kind == Slice_kind);
3213
3214 /* only handles the cases where BUILD_SLICE is emitted */
3215 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003216 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217 }
3218 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003223 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224 }
3225 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003226 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227 }
3228
3229 if (s->v.Slice.step) {
3230 n++;
3231 VISIT(c, expr, s->v.Slice.step);
3232 }
3233 ADDOP_I(c, BUILD_SLICE, n);
3234 return 1;
3235}
3236
3237static int
3238compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3239{
3240 int op = 0, slice_offset = 0, stack_count = 0;
3241
3242 assert(s->v.Slice.step == NULL);
3243 if (s->v.Slice.lower) {
3244 slice_offset++;
3245 stack_count++;
3246 if (ctx != AugStore)
3247 VISIT(c, expr, s->v.Slice.lower);
3248 }
3249 if (s->v.Slice.upper) {
3250 slice_offset += 2;
3251 stack_count++;
3252 if (ctx != AugStore)
3253 VISIT(c, expr, s->v.Slice.upper);
3254 }
3255
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003256 if (ctx == AugLoad) {
3257 switch (stack_count) {
3258 case 0: ADDOP(c, DUP_TOP); break;
3259 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3260 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3261 }
3262 }
3263 else if (ctx == AugStore) {
3264 switch (stack_count) {
3265 case 0: ADDOP(c, ROT_TWO); break;
3266 case 1: ADDOP(c, ROT_THREE); break;
3267 case 2: ADDOP(c, ROT_FOUR); break;
3268 }
3269 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270
3271 switch (ctx) {
3272 case AugLoad: /* fall through to Load */
3273 case Load: op = SLICE; break;
3274 case AugStore:/* fall through to Store */
3275 case Store: op = STORE_SLICE; break;
3276 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003277 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003278 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003279 PyErr_SetString(PyExc_SystemError,
3280 "param invalid in simple slice");
3281 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282 }
3283
3284 ADDOP(c, op + slice_offset);
3285 return 1;
3286}
3287
3288static int
3289compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3290 expr_context_ty ctx)
3291{
3292 switch (s->kind) {
3293 case Ellipsis_kind:
3294 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3295 break;
3296 case Slice_kind:
3297 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298 case Index_kind:
3299 VISIT(c, expr, s->v.Index.value);
3300 break;
3301 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003302 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003303 PyErr_SetString(PyExc_SystemError,
3304 "extended slice invalid in nested slice");
3305 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306 }
3307 return 1;
3308}
3309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310static int
3311compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3312{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003313 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003315 case Index_kind:
3316 kindname = "index";
3317 if (ctx != AugStore) {
3318 VISIT(c, expr, s->v.Index.value);
3319 }
3320 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003322 kindname = "ellipsis";
3323 if (ctx != AugStore) {
3324 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3325 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326 break;
3327 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003328 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329 if (!s->v.Slice.step)
3330 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003331 if (ctx != AugStore) {
3332 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333 return 0;
3334 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003335 break;
3336 case ExtSlice_kind:
3337 kindname = "extended slice";
3338 if (ctx != AugStore) {
3339 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3340 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003341 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003342 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003343 if (!compiler_visit_nested_slice(c, sub, ctx))
3344 return 0;
3345 }
3346 ADDOP_I(c, BUILD_TUPLE, n);
3347 }
3348 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003349 default:
3350 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003351 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003352 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003354 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355}
3356
Neal Norwitzf733a012006-10-29 18:30:10 +00003357
3358/* End of the compiler section, beginning of the assembler section */
3359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360/* do depth-first search of basic block graph, starting with block.
3361 post records the block indices in post-order.
3362
3363 XXX must handle implicit jumps from one block to next
3364*/
3365
Neal Norwitzf733a012006-10-29 18:30:10 +00003366struct assembler {
3367 PyObject *a_bytecode; /* string containing bytecode */
3368 int a_offset; /* offset into bytecode */
3369 int a_nblocks; /* number of reachable blocks */
3370 basicblock **a_postorder; /* list of blocks in dfs postorder */
3371 PyObject *a_lnotab; /* string containing lnotab */
3372 int a_lnotab_off; /* offset into lnotab */
3373 int a_lineno; /* last lineno of emitted instruction */
3374 int a_lineno_off; /* bytecode offset of last lineno */
3375};
3376
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003377static void
3378dfs(struct compiler *c, basicblock *b, struct assembler *a)
3379{
3380 int i;
3381 struct instr *instr = NULL;
3382
3383 if (b->b_seen)
3384 return;
3385 b->b_seen = 1;
3386 if (b->b_next != NULL)
3387 dfs(c, b->b_next, a);
3388 for (i = 0; i < b->b_iused; i++) {
3389 instr = &b->b_instr[i];
3390 if (instr->i_jrel || instr->i_jabs)
3391 dfs(c, instr->i_target, a);
3392 }
3393 a->a_postorder[a->a_nblocks++] = b;
3394}
3395
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003396static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3398{
3399 int i;
3400 struct instr *instr;
3401 if (b->b_seen || b->b_startdepth >= depth)
3402 return maxdepth;
3403 b->b_seen = 1;
3404 b->b_startdepth = depth;
3405 for (i = 0; i < b->b_iused; i++) {
3406 instr = &b->b_instr[i];
3407 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3408 if (depth > maxdepth)
3409 maxdepth = depth;
3410 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3411 if (instr->i_jrel || instr->i_jabs) {
3412 maxdepth = stackdepth_walk(c, instr->i_target,
3413 depth, maxdepth);
3414 if (instr->i_opcode == JUMP_ABSOLUTE ||
3415 instr->i_opcode == JUMP_FORWARD) {
3416 goto out; /* remaining code is dead */
3417 }
3418 }
3419 }
3420 if (b->b_next)
3421 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3422out:
3423 b->b_seen = 0;
3424 return maxdepth;
3425}
3426
3427/* Find the flow path that needs the largest stack. We assume that
3428 * cycles in the flow graph have no net effect on the stack depth.
3429 */
3430static int
3431stackdepth(struct compiler *c)
3432{
3433 basicblock *b, *entryblock;
3434 entryblock = NULL;
3435 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3436 b->b_seen = 0;
3437 b->b_startdepth = INT_MIN;
3438 entryblock = b;
3439 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003440 if (!entryblock)
3441 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442 return stackdepth_walk(c, entryblock, 0, 0);
3443}
3444
3445static int
3446assemble_init(struct assembler *a, int nblocks, int firstlineno)
3447{
3448 memset(a, 0, sizeof(struct assembler));
3449 a->a_lineno = firstlineno;
3450 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3451 if (!a->a_bytecode)
3452 return 0;
3453 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3454 if (!a->a_lnotab)
3455 return 0;
3456 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003458 if (!a->a_postorder) {
3459 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003461 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462 return 1;
3463}
3464
3465static void
3466assemble_free(struct assembler *a)
3467{
3468 Py_XDECREF(a->a_bytecode);
3469 Py_XDECREF(a->a_lnotab);
3470 if (a->a_postorder)
3471 PyObject_Free(a->a_postorder);
3472}
3473
3474/* Return the size of a basic block in bytes. */
3475
3476static int
3477instrsize(struct instr *instr)
3478{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003479 if (!instr->i_hasarg)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003480 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003481 if (instr->i_oparg > 0xffff)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003482 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3483 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484}
3485
3486static int
3487blocksize(basicblock *b)
3488{
3489 int i;
3490 int size = 0;
3491
3492 for (i = 0; i < b->b_iused; i++)
3493 size += instrsize(&b->b_instr[i]);
3494 return size;
3495}
3496
3497/* All about a_lnotab.
3498
3499c_lnotab is an array of unsigned bytes disguised as a Python string.
3500It is used to map bytecode offsets to source code line #s (when needed
3501for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003502
Tim Peters2a7f3842001-06-09 09:26:21 +00003503The array is conceptually a list of
3504 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003505pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003506
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003507 byte code offset source code line number
3508 0 1
3509 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003510 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003511 350 307
3512 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003513
3514The first trick is that these numbers aren't stored, only the increments
3515from one row to the next (this doesn't really work, but it's a start):
3516
3517 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3518
3519The second trick is that an unsigned byte can't hold negative values, or
3520values larger than 255, so (a) there's a deep assumption that byte code
3521offsets and their corresponding line #s both increase monotonically, and (b)
3522if at least one column jumps by more than 255 from one row to the next, more
3523than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003524from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003525part. A user of c_lnotab desiring to find the source line number
3526corresponding to a bytecode address A should do something like this
3527
3528 lineno = addr = 0
3529 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003530 addr += addr_incr
3531 if addr > A:
3532 return lineno
3533 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003534
3535In order for this to work, when the addr field increments by more than 255,
3536the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003537increment is < 256. So, in the example above, assemble_lnotab (it used
3538to be called com_set_lineno) should not (as was actually done until 2.2)
3539expand 300, 300 to 255, 255, 45, 45,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003540 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003541*/
3542
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003543static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003545{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 int d_bytecode, d_lineno;
3547 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003548 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549
3550 d_bytecode = a->a_offset - a->a_lineno_off;
3551 d_lineno = i->i_lineno - a->a_lineno;
3552
3553 assert(d_bytecode >= 0);
3554 assert(d_lineno >= 0);
3555
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003556 /* XXX(nnorwitz): is there a better way to handle this?
3557 for loops are special, we want to be able to trace them
3558 each time around, so we need to set an extra line number. */
Nick Coghlanb90f52e2007-08-25 04:35:54 +00003559 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003560 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003561
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003563 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 nbytes = a->a_lnotab_off + 2 * ncodes;
3565 len = PyString_GET_SIZE(a->a_lnotab);
3566 if (nbytes >= len) {
3567 if (len * 2 < nbytes)
3568 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003569 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 len *= 2;
3571 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3572 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003573 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003574 lnotab = (unsigned char *)
3575 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003576 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 *lnotab++ = 255;
3578 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 d_bytecode -= ncodes * 255;
3581 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003582 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 assert(d_bytecode <= 255);
3584 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003585 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 nbytes = a->a_lnotab_off + 2 * ncodes;
3587 len = PyString_GET_SIZE(a->a_lnotab);
3588 if (nbytes >= len) {
3589 if (len * 2 < nbytes)
3590 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003591 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 len *= 2;
3593 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3594 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003595 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003596 lnotab = (unsigned char *)
3597 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003599 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003601 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003603 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 d_lineno -= ncodes * 255;
3606 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003607 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003608
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609 len = PyString_GET_SIZE(a->a_lnotab);
3610 if (a->a_lnotab_off + 2 >= len) {
3611 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003612 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003613 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003614 lnotab = (unsigned char *)
3615 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 a->a_lnotab_off += 2;
3618 if (d_bytecode) {
3619 *lnotab++ = d_bytecode;
3620 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003621 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003622 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 *lnotab++ = 0;
3624 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 a->a_lineno = i->i_lineno;
3627 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003628 return 1;
3629}
3630
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631/* assemble_emit()
3632 Extend the bytecode with a new instruction.
3633 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003634*/
3635
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003636static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003638{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003639 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003640 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641 char *code;
3642
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003643 size = instrsize(i);
3644 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003646 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003647 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003649 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650 if (a->a_offset + size >= len) {
3651 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003652 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003653 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3655 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003656 if (size == 6) {
3657 assert(i->i_hasarg);
3658 *code++ = (char)EXTENDED_ARG;
3659 *code++ = ext & 0xff;
3660 *code++ = ext >> 8;
3661 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003662 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003664 if (i->i_hasarg) {
3665 assert(size == 3 || size == 6);
3666 *code++ = arg & 0xff;
3667 *code++ = arg >> 8;
3668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003670}
3671
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003672static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003674{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003676 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003677 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 /* Compute the size of each block and fixup jump args.
3680 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003681start:
3682 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003684 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685 bsize = blocksize(b);
3686 b->b_offset = totsize;
3687 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003688 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003689 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3691 bsize = b->b_offset;
3692 for (i = 0; i < b->b_iused; i++) {
3693 struct instr *instr = &b->b_instr[i];
3694 /* Relative jumps are computed relative to
3695 the instruction pointer after fetching
3696 the jump instruction.
3697 */
3698 bsize += instrsize(instr);
3699 if (instr->i_jabs)
3700 instr->i_oparg = instr->i_target->b_offset;
3701 else if (instr->i_jrel) {
3702 int delta = instr->i_target->b_offset - bsize;
3703 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003704 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003705 else
3706 continue;
3707 if (instr->i_oparg > 0xffff)
3708 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003709 }
3710 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003711
3712 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003713 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003714 with a better solution.
3715
3716 In the meantime, should the goto be dropped in favor
3717 of a loop?
3718
3719 The issue is that in the first loop blocksize() is called
3720 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003721 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003722 i_oparg is calculated in the second loop above.
3723
3724 So we loop until we stop seeing new EXTENDED_ARGs.
3725 The only EXTENDED_ARGs that could be popping up are
3726 ones in jump instructions. So this should converge
3727 fairly quickly.
3728 */
3729 if (last_extended_arg_count != extended_arg_count) {
3730 last_extended_arg_count = extended_arg_count;
3731 goto start;
3732 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003733}
3734
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003735static PyObject *
3736dict_keys_inorder(PyObject *dict, int offset)
3737{
3738 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003739 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003740
3741 tuple = PyTuple_New(size);
3742 if (tuple == NULL)
3743 return NULL;
3744 while (PyDict_Next(dict, &pos, &k, &v)) {
3745 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003746 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003747 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003748 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003749 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003750 PyTuple_SET_ITEM(tuple, i - offset, k);
3751 }
3752 return tuple;
3753}
3754
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003755static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003757{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758 PySTEntryObject *ste = c->u->u_ste;
3759 int flags = 0, n;
3760 if (ste->ste_type != ModuleBlock)
3761 flags |= CO_NEWLOCALS;
3762 if (ste->ste_type == FunctionBlock) {
3763 if (!ste->ste_unoptimized)
3764 flags |= CO_OPTIMIZED;
3765 if (ste->ste_nested)
3766 flags |= CO_NESTED;
3767 if (ste->ste_generator)
3768 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003769 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770 if (ste->ste_varargs)
3771 flags |= CO_VARARGS;
3772 if (ste->ste_varkeywords)
3773 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003774 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003776
3777 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003778 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 n = PyDict_Size(c->u->u_freevars);
3781 if (n < 0)
3782 return -1;
3783 if (n == 0) {
3784 n = PyDict_Size(c->u->u_cellvars);
3785 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003786 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787 if (n == 0) {
3788 flags |= CO_NOFREE;
3789 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003790 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003791
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003792 return flags;
3793}
3794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795static PyCodeObject *
3796makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003797{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798 PyObject *tmp;
3799 PyCodeObject *co = NULL;
3800 PyObject *consts = NULL;
3801 PyObject *names = NULL;
3802 PyObject *varnames = NULL;
3803 PyObject *filename = NULL;
3804 PyObject *name = NULL;
3805 PyObject *freevars = NULL;
3806 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003807 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 tmp = dict_keys_inorder(c->u->u_consts, 0);
3811 if (!tmp)
3812 goto error;
3813 consts = PySequence_List(tmp); /* optimize_code requires a list */
3814 Py_DECREF(tmp);
3815
3816 names = dict_keys_inorder(c->u->u_names, 0);
3817 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3818 if (!consts || !names || !varnames)
3819 goto error;
3820
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003821 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3822 if (!cellvars)
3823 goto error;
3824 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3825 if (!freevars)
3826 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 filename = PyString_FromString(c->c_filename);
3828 if (!filename)
3829 goto error;
3830
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003831 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832 flags = compute_code_flags(c);
3833 if (flags < 0)
3834 goto error;
3835
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003836 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003837 if (!bytecode)
3838 goto error;
3839
3840 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3841 if (!tmp)
3842 goto error;
3843 Py_DECREF(consts);
3844 consts = tmp;
3845
3846 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3847 bytecode, consts, names, varnames,
3848 freevars, cellvars,
3849 filename, c->u->u_name,
3850 c->u->u_firstlineno,
3851 a->a_lnotab);
3852 error:
3853 Py_XDECREF(consts);
3854 Py_XDECREF(names);
3855 Py_XDECREF(varnames);
3856 Py_XDECREF(filename);
3857 Py_XDECREF(name);
3858 Py_XDECREF(freevars);
3859 Py_XDECREF(cellvars);
3860 Py_XDECREF(bytecode);
3861 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003862}
3863
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003864
3865/* For debugging purposes only */
3866#if 0
3867static void
3868dump_instr(const struct instr *i)
3869{
3870 const char *jrel = i->i_jrel ? "jrel " : "";
3871 const char *jabs = i->i_jabs ? "jabs " : "";
3872 char arg[128];
3873
3874 *arg = '\0';
3875 if (i->i_hasarg)
3876 sprintf(arg, "arg: %d ", i->i_oparg);
3877
3878 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3879 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3880}
3881
3882static void
3883dump_basicblock(const basicblock *b)
3884{
3885 const char *seen = b->b_seen ? "seen " : "";
3886 const char *b_return = b->b_return ? "return " : "";
3887 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3888 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3889 if (b->b_instr) {
3890 int i;
3891 for (i = 0; i < b->b_iused; i++) {
3892 fprintf(stderr, " [%02d] ", i);
3893 dump_instr(b->b_instr + i);
3894 }
3895 }
3896}
3897#endif
3898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899static PyCodeObject *
3900assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003901{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 basicblock *b, *entryblock;
3903 struct assembler a;
3904 int i, j, nblocks;
3905 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003906
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003907 /* Make sure every block that falls off the end returns None.
3908 XXX NEXT_BLOCK() isn't quite right, because if the last
3909 block ends with a jump or return b_next shouldn't set.
3910 */
3911 if (!c->u->u_curblock->b_return) {
3912 NEXT_BLOCK(c);
3913 if (addNone)
3914 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3915 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003916 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 nblocks = 0;
3919 entryblock = NULL;
3920 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3921 nblocks++;
3922 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003923 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003924
Neal Norwitzed657552006-07-10 00:04:44 +00003925 /* Set firstlineno if it wasn't explicitly set. */
3926 if (!c->u->u_firstlineno) {
3927 if (entryblock && entryblock->b_instr)
3928 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3929 else
3930 c->u->u_firstlineno = 1;
3931 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3933 goto error;
3934 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003935
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003937 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003939 /* Emit code in reverse postorder from dfs. */
3940 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003941 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942 for (j = 0; j < b->b_iused; j++)
3943 if (!assemble_emit(&a, &b->b_instr[j]))
3944 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003945 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003946
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3948 goto error;
3949 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3950 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003952 co = makecode(c, &a);
3953 error:
3954 assemble_free(&a);
3955 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003956}