blob: 0a83bfce319b0fb86ed6c629f290679fafe0d05f [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. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000187 const char *p, *name = PyString_AsString(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000188 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189 size_t nlen, plen;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000190 if (privateobj == NULL || !PyString_Check(privateobj) ||
Neal Norwitz84167d02006-08-12 01:45:47 +0000191 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 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +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);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000219
220 assert(1 <= PY_SSIZE_T_MAX - nlen);
221 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
222
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000223 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 if (!ident)
225 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000227 buffer = PyString_AS_STRING(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 strncpy(buffer+1, p, plen);
230 strcpy(buffer+1+plen, name);
231 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000232}
233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234static int
235compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000236{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 c->c_stack = PyList_New(0);
240 if (!c->c_stack)
241 return 0;
242
243 return 1;
244}
245
246PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000247PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000248 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000249{
250 struct compiler c;
251 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000252 PyCompilerFlags local_flags;
253 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 if (!__doc__) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000256 __doc__ = PyString_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000257 if (!__doc__)
258 return NULL;
259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260
261 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000262 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265 c.c_future = PyFuture_FromAST(mod, filename);
266 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000267 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000269 local_flags.cf_flags = 0;
270 flags = &local_flags;
271 }
272 merged = c.c_future->ff_features | flags->cf_flags;
273 c.c_future->ff_features = merged;
274 flags->cf_flags = merged;
275 c.c_flags = flags;
276 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
278 c.c_st = PySymtable_Build(mod, filename, c.c_future);
279 if (c.c_st == NULL) {
280 if (!PyErr_Occurred())
281 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000282 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283 }
284
285 /* XXX initialize to NULL for now, need to handle */
286 c.c_encoding = NULL;
287
288 co = compiler_mod(&c, mod);
289
Thomas Wouters1175c432006-02-27 22:49:54 +0000290 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000292 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293 return co;
294}
295
296PyCodeObject *
297PyNode_Compile(struct _node *n, const char *filename)
298{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000299 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000300 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000301 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000302 if (!arena)
303 return NULL;
304 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000305 if (mod)
306 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000307 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000308 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000309}
310
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000311static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000313{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 if (c->c_st)
315 PySymtable_Free(c->c_st);
316 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000317 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000319}
320
Guido van Rossum79f25d91997-04-29 20:08:16 +0000321static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000323{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000325 PyObject *v, *k;
326 PyObject *dict = PyDict_New();
327 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 n = PyList_Size(list);
330 for (i = 0; i < n; i++) {
331 v = PyInt_FromLong(i);
332 if (!v) {
333 Py_DECREF(dict);
334 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000335 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000336 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000337 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
339 Py_XDECREF(k);
340 Py_DECREF(v);
341 Py_DECREF(dict);
342 return NULL;
343 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000344 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 return dict;
348}
349
350/* Return new dict containing names from src that match scope(s).
351
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000352src is a symbol table dictionary. If the scope of a name matches
353either scope_type or flag is set, insert it into the new dict. The
354values are integers, starting at offset and increasing by one for
355each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356*/
357
358static PyObject *
359dictbytype(PyObject *src, int scope_type, int flag, int offset)
360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362 PyObject *k, *v, *dest = PyDict_New();
363
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 assert(offset >= 0);
365 if (dest == NULL)
366 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
368 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 /* XXX this should probably be a macro in symtable.h */
370 assert(PyInt_Check(v));
371 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
374 PyObject *tuple, *item = PyInt_FromLong(i);
375 if (item == NULL) {
376 Py_DECREF(dest);
377 return NULL;
378 }
379 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000380 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000381 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
382 Py_DECREF(item);
383 Py_DECREF(dest);
384 Py_XDECREF(tuple);
385 return NULL;
386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 }
391 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000392}
393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394static void
395compiler_unit_check(struct compiler_unit *u)
396{
397 basicblock *block;
398 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Brett Cannona6c41bc2008-02-07 07:47:31 +0000399 assert((void *)block != (void *)0xcbcbcbcb);
400 assert((void *)block != (void *)0xfbfbfbfb);
401 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402 if (block->b_instr != NULL) {
403 assert(block->b_ialloc > 0);
404 assert(block->b_iused > 0);
405 assert(block->b_ialloc >= block->b_iused);
406 }
407 else {
408 assert (block->b_iused == 0);
409 assert (block->b_ialloc == 0);
410 }
411 }
412}
413
414static void
415compiler_unit_free(struct compiler_unit *u)
416{
417 basicblock *b, *next;
418
419 compiler_unit_check(u);
420 b = u->u_blocks;
421 while (b != NULL) {
422 if (b->b_instr)
423 PyObject_Free((void *)b->b_instr);
424 next = b->b_list;
425 PyObject_Free((void *)b);
426 b = next;
427 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000428 Py_CLEAR(u->u_ste);
429 Py_CLEAR(u->u_name);
430 Py_CLEAR(u->u_consts);
431 Py_CLEAR(u->u_names);
432 Py_CLEAR(u->u_varnames);
433 Py_CLEAR(u->u_freevars);
434 Py_CLEAR(u->u_cellvars);
435 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436 PyObject_Free(u);
437}
438
439static int
440compiler_enter_scope(struct compiler *c, identifier name, void *key,
441 int lineno)
442{
443 struct compiler_unit *u;
444
Anthony Baxter7b782b62006-04-11 12:01:56 +0000445 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000446 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000447 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000448 PyErr_NoMemory();
449 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000450 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000451 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452 u->u_argcount = 0;
453 u->u_ste = PySymtable_Lookup(c->c_st, key);
454 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 compiler_unit_free(u);
456 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000457 }
458 Py_INCREF(name);
459 u->u_name = name;
460 u->u_varnames = list2dict(u->u_ste->ste_varnames);
461 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000462 if (!u->u_varnames || !u->u_cellvars) {
463 compiler_unit_free(u);
464 return 0;
465 }
466
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000468 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000469 if (!u->u_freevars) {
470 compiler_unit_free(u);
471 return 0;
472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473
474 u->u_blocks = NULL;
475 u->u_tmpname = 0;
476 u->u_nfblocks = 0;
477 u->u_firstlineno = lineno;
478 u->u_lineno = 0;
479 u->u_lineno_set = false;
480 u->u_consts = PyDict_New();
481 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000482 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483 return 0;
484 }
485 u->u_names = PyDict_New();
486 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000487 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000488 return 0;
489 }
490
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000491 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492
493 /* Push the old compiler_unit on the stack. */
494 if (c->u) {
495 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000496 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
497 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499 return 0;
500 }
501 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000502 u->u_private = c->u->u_private;
503 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504 }
505 c->u = u;
506
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000507 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000508 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 return 0;
510
511 return 1;
512}
513
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000514static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515compiler_exit_scope(struct compiler *c)
516{
517 int n;
518 PyObject *wrapper;
519
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000520 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000521 compiler_unit_free(c->u);
522 /* Restore c->u to the parent unit. */
523 n = PyList_GET_SIZE(c->c_stack) - 1;
524 if (n >= 0) {
525 wrapper = PyList_GET_ITEM(c->c_stack, n);
526 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000527 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000528 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000530 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531 compiler_unit_check(c->u);
532 }
533 else
534 c->u = NULL;
535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536}
537
538/* Allocate a new block and return a pointer to it.
539 Returns NULL on error.
540*/
541
542static basicblock *
543compiler_new_block(struct compiler *c)
544{
545 basicblock *b;
546 struct compiler_unit *u;
547
548 u = c->u;
549 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000550 if (b == NULL) {
551 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000555 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556 b->b_list = u->u_blocks;
557 u->u_blocks = b;
558 return b;
559}
560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561static basicblock *
562compiler_use_new_block(struct compiler *c)
563{
564 basicblock *block = compiler_new_block(c);
565 if (block == NULL)
566 return NULL;
567 c->u->u_curblock = block;
568 return block;
569}
570
571static basicblock *
572compiler_next_block(struct compiler *c)
573{
574 basicblock *block = compiler_new_block(c);
575 if (block == NULL)
576 return NULL;
577 c->u->u_curblock->b_next = block;
578 c->u->u_curblock = block;
579 return block;
580}
581
582static basicblock *
583compiler_use_next_block(struct compiler *c, basicblock *block)
584{
585 assert(block != NULL);
586 c->u->u_curblock->b_next = block;
587 c->u->u_curblock = block;
588 return block;
589}
590
591/* Returns the offset of the next instruction in the current block's
592 b_instr array. Resizes the b_instr as necessary.
593 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000594*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000595
596static int
597compiler_next_instr(struct compiler *c, basicblock *b)
598{
599 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000600 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000601 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000602 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603 if (b->b_instr == NULL) {
604 PyErr_NoMemory();
605 return -1;
606 }
607 b->b_ialloc = DEFAULT_BLOCK_SIZE;
608 memset((char *)b->b_instr, 0,
609 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000612 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613 size_t oldsize, newsize;
614 oldsize = b->b_ialloc * sizeof(struct instr);
615 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000616
617 if (oldsize > (PY_SIZE_MAX >> 1)) {
618 PyErr_NoMemory();
619 return -1;
620 }
621
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622 if (newsize == 0) {
623 PyErr_NoMemory();
624 return -1;
625 }
626 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000627 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000628 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000629 if (tmp == NULL) {
630 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000631 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000632 }
633 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
635 }
636 return b->b_iused++;
637}
638
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000639/* Set the i_lineno member of the instruction at offset off if the
640 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000641 already been set. If it has been set, the call has no effect.
642
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000643 The line number is reset in the following cases:
644 - when entering a new scope
645 - on each statement
646 - on each expression that start a new line
647 - before the "except" clause
648 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000649*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000650
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000651static void
652compiler_set_lineno(struct compiler *c, int off)
653{
654 basicblock *b;
655 if (c->u->u_lineno_set)
656 return;
657 c->u->u_lineno_set = true;
658 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000659 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660}
661
662static int
663opcode_stack_effect(int opcode, int oparg)
664{
665 switch (opcode) {
666 case POP_TOP:
667 return -1;
668 case ROT_TWO:
669 case ROT_THREE:
670 return 0;
671 case DUP_TOP:
672 return 1;
673 case ROT_FOUR:
674 return 0;
675
676 case UNARY_POSITIVE:
677 case UNARY_NEGATIVE:
678 case UNARY_NOT:
679 case UNARY_CONVERT:
680 case UNARY_INVERT:
681 return 0;
682
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000683 case LIST_APPEND:
Antoine Pitroud0c35152008-12-17 00:38:28 +0000684 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000685
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686 case BINARY_POWER:
687 case BINARY_MULTIPLY:
688 case BINARY_DIVIDE:
689 case BINARY_MODULO:
690 case BINARY_ADD:
691 case BINARY_SUBTRACT:
692 case BINARY_SUBSCR:
693 case BINARY_FLOOR_DIVIDE:
694 case BINARY_TRUE_DIVIDE:
695 return -1;
696 case INPLACE_FLOOR_DIVIDE:
697 case INPLACE_TRUE_DIVIDE:
698 return -1;
699
700 case SLICE+0:
701 return 1;
702 case SLICE+1:
703 return 0;
704 case SLICE+2:
705 return 0;
706 case SLICE+3:
707 return -1;
708
709 case STORE_SLICE+0:
710 return -2;
711 case STORE_SLICE+1:
712 return -3;
713 case STORE_SLICE+2:
714 return -3;
715 case STORE_SLICE+3:
716 return -4;
717
718 case DELETE_SLICE+0:
719 return -1;
720 case DELETE_SLICE+1:
721 return -2;
722 case DELETE_SLICE+2:
723 return -2;
724 case DELETE_SLICE+3:
725 return -3;
726
727 case INPLACE_ADD:
728 case INPLACE_SUBTRACT:
729 case INPLACE_MULTIPLY:
730 case INPLACE_DIVIDE:
731 case INPLACE_MODULO:
732 return -1;
733 case STORE_SUBSCR:
734 return -3;
Raymond Hettingereffde122007-12-18 18:26:18 +0000735 case STORE_MAP:
736 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737 case DELETE_SUBSCR:
738 return -2;
739
740 case BINARY_LSHIFT:
741 case BINARY_RSHIFT:
742 case BINARY_AND:
743 case BINARY_XOR:
744 case BINARY_OR:
745 return -1;
746 case INPLACE_POWER:
747 return -1;
748 case GET_ITER:
749 return 0;
750
751 case PRINT_EXPR:
752 return -1;
753 case PRINT_ITEM:
754 return -1;
755 case PRINT_NEWLINE:
756 return 0;
757 case PRINT_ITEM_TO:
758 return -2;
759 case PRINT_NEWLINE_TO:
760 return -1;
761 case INPLACE_LSHIFT:
762 case INPLACE_RSHIFT:
763 case INPLACE_AND:
764 case INPLACE_XOR:
765 case INPLACE_OR:
766 return -1;
767 case BREAK_LOOP:
768 return 0;
Benjamin Peterson1880d8b2009-05-25 13:13:44 +0000769 case SETUP_WITH:
Benjamin Peterson49a6b0e2009-05-25 20:12:57 +0000770 return 4;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000771 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000772 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773 case LOAD_LOCALS:
774 return 1;
775 case RETURN_VALUE:
776 return -1;
777 case IMPORT_STAR:
778 return -1;
779 case EXEC_STMT:
780 return -3;
781 case YIELD_VALUE:
782 return 0;
783
784 case POP_BLOCK:
785 return 0;
786 case END_FINALLY:
787 return -1; /* or -2 or -3 if exception occurred */
788 case BUILD_CLASS:
789 return -2;
790
791 case STORE_NAME:
792 return -1;
793 case DELETE_NAME:
794 return 0;
795 case UNPACK_SEQUENCE:
796 return oparg-1;
797 case FOR_ITER:
798 return 1;
799
800 case STORE_ATTR:
801 return -2;
802 case DELETE_ATTR:
803 return -1;
804 case STORE_GLOBAL:
805 return -1;
806 case DELETE_GLOBAL:
807 return 0;
808 case DUP_TOPX:
809 return oparg;
810 case LOAD_CONST:
811 return 1;
812 case LOAD_NAME:
813 return 1;
814 case BUILD_TUPLE:
815 case BUILD_LIST:
816 return 1-oparg;
817 case BUILD_MAP:
818 return 1;
819 case LOAD_ATTR:
820 return 0;
821 case COMPARE_OP:
822 return -1;
823 case IMPORT_NAME:
824 return 0;
825 case IMPORT_FROM:
826 return 1;
827
828 case JUMP_FORWARD:
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000829 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
830 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831 case JUMP_ABSOLUTE:
832 return 0;
833
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000834 case POP_JUMP_IF_FALSE:
835 case POP_JUMP_IF_TRUE:
836 return -1;
837
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838 case LOAD_GLOBAL:
839 return 1;
840
841 case CONTINUE_LOOP:
842 return 0;
843 case SETUP_LOOP:
844 return 0;
845 case SETUP_EXCEPT:
846 case SETUP_FINALLY:
847 return 3; /* actually pushed by an exception */
848
849 case LOAD_FAST:
850 return 1;
851 case STORE_FAST:
852 return -1;
853 case DELETE_FAST:
854 return 0;
855
856 case RAISE_VARARGS:
857 return -oparg;
858#define NARGS(o) (((o) % 256) + 2*((o) / 256))
859 case CALL_FUNCTION:
860 return -NARGS(oparg);
861 case CALL_FUNCTION_VAR:
862 case CALL_FUNCTION_KW:
863 return -NARGS(oparg)-1;
864 case CALL_FUNCTION_VAR_KW:
865 return -NARGS(oparg)-2;
866#undef NARGS
867 case MAKE_FUNCTION:
868 return -oparg;
869 case BUILD_SLICE:
870 if (oparg == 3)
871 return -2;
872 else
873 return -1;
874
875 case MAKE_CLOSURE:
876 return -oparg;
877 case LOAD_CLOSURE:
878 return 1;
879 case LOAD_DEREF:
880 return 1;
881 case STORE_DEREF:
882 return -1;
883 default:
884 fprintf(stderr, "opcode = %d\n", opcode);
885 Py_FatalError("opcode_stack_effect()");
886
887 }
888 return 0; /* not reachable */
889}
890
891/* Add an opcode with no argument.
892 Returns 0 on failure, 1 on success.
893*/
894
895static int
896compiler_addop(struct compiler *c, int opcode)
897{
898 basicblock *b;
899 struct instr *i;
900 int off;
901 off = compiler_next_instr(c, c->u->u_curblock);
902 if (off < 0)
903 return 0;
904 b = c->u->u_curblock;
905 i = &b->b_instr[off];
906 i->i_opcode = opcode;
907 i->i_hasarg = 0;
908 if (opcode == RETURN_VALUE)
909 b->b_return = 1;
910 compiler_set_lineno(c, off);
911 return 1;
912}
913
914static int
915compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
916{
917 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000918 Py_ssize_t arg;
Mark Dickinson105be772008-01-31 22:17:37 +0000919 unsigned char *p, *q;
920 Py_complex z;
921 double d;
922 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000923
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000924 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000925 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
926 if (PyFloat_Check(o)) {
Mark Dickinson105be772008-01-31 22:17:37 +0000927 d = PyFloat_AS_DOUBLE(o);
928 p = (unsigned char*) &d;
929 /* all we need is to make the tuple different in either the 0.0
930 * or -0.0 case from all others, just to avoid the "coercion".
931 */
932 if (*p==0 && p[sizeof(double)-1]==0)
933 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
934 else
935 t = PyTuple_Pack(2, o, o->ob_type);
936 }
937 else if (PyComplex_Check(o)) {
938 /* complex case is even messier: we need to make complex(x,
939 0.) different from complex(x, -0.) and complex(0., y)
940 different from complex(-0., y), for any x and y. In
941 particular, all four complex zeros should be
942 distinguished.*/
943 z = PyComplex_AsCComplex(o);
944 p = (unsigned char*) &(z.real);
945 q = (unsigned char*) &(z.imag);
946 /* all that matters here is that on IEEE platforms
947 real_part_zero will be true if z.real == 0., and false if
948 z.real == -0. In fact, real_part_zero will also be true
949 for some other rarely occurring nonzero floats, but this
950 doesn't matter. Similar comments apply to
951 imag_part_zero. */
952 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
953 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
954 if (real_part_zero && imag_part_zero) {
955 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
956 }
957 else if (real_part_zero && !imag_part_zero) {
958 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
959 }
960 else if (!real_part_zero && imag_part_zero) {
961 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
962 }
963 else {
964 t = PyTuple_Pack(2, o, o->ob_type);
965 }
966 }
967 else {
968 t = PyTuple_Pack(2, o, o->ob_type);
Alex Martellid8672aa2007-08-22 21:14:17 +0000969 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000970 if (t == NULL)
Mark Dickinson105be772008-01-31 22:17:37 +0000971 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972
973 v = PyDict_GetItem(dict, t);
974 if (!v) {
975 arg = PyDict_Size(dict);
976 v = PyInt_FromLong(arg);
977 if (!v) {
978 Py_DECREF(t);
979 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981 if (PyDict_SetItem(dict, t, v) < 0) {
982 Py_DECREF(t);
983 Py_DECREF(v);
984 return -1;
985 }
986 Py_DECREF(v);
987 }
988 else
989 arg = PyInt_AsLong(v);
990 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000991 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992}
993
994static int
995compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
996 PyObject *o)
997{
998 int arg = compiler_add_o(c, dict, o);
999 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001 return compiler_addop_i(c, opcode, arg);
1002}
1003
1004static int
1005compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007{
1008 int arg;
1009 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1010 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001011 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001012 arg = compiler_add_o(c, dict, mangled);
1013 Py_DECREF(mangled);
1014 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001015 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016 return compiler_addop_i(c, opcode, arg);
1017}
1018
1019/* Add an opcode with an integer argument.
1020 Returns 0 on failure, 1 on success.
1021*/
1022
1023static int
1024compiler_addop_i(struct compiler *c, int opcode, int oparg)
1025{
1026 struct instr *i;
1027 int off;
1028 off = compiler_next_instr(c, c->u->u_curblock);
1029 if (off < 0)
1030 return 0;
1031 i = &c->u->u_curblock->b_instr[off];
1032 i->i_opcode = opcode;
1033 i->i_oparg = oparg;
1034 i->i_hasarg = 1;
1035 compiler_set_lineno(c, off);
1036 return 1;
1037}
1038
1039static int
1040compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1041{
1042 struct instr *i;
1043 int off;
1044
1045 assert(b != NULL);
1046 off = compiler_next_instr(c, c->u->u_curblock);
1047 if (off < 0)
1048 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049 i = &c->u->u_curblock->b_instr[off];
1050 i->i_opcode = opcode;
1051 i->i_target = b;
1052 i->i_hasarg = 1;
1053 if (absolute)
1054 i->i_jabs = 1;
1055 else
1056 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001057 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058 return 1;
1059}
1060
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001061/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1062 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063 it as the current block. NEXT_BLOCK() also creates an implicit jump
1064 from the current block to the new block.
1065*/
1066
Neal Norwitzf733a012006-10-29 18:30:10 +00001067/* The returns inside these macros make it impossible to decref objects
1068 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069*/
1070
1071
1072#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001073 if (compiler_use_new_block((C)) == NULL) \
1074 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075}
1076
1077#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001078 if (compiler_next_block((C)) == NULL) \
1079 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080}
1081
1082#define ADDOP(C, OP) { \
1083 if (!compiler_addop((C), (OP))) \
1084 return 0; \
1085}
1086
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001087#define ADDOP_IN_SCOPE(C, OP) { \
1088 if (!compiler_addop((C), (OP))) { \
1089 compiler_exit_scope(c); \
1090 return 0; \
1091 } \
1092}
1093
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001094#define ADDOP_O(C, OP, O, TYPE) { \
1095 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1096 return 0; \
1097}
1098
1099#define ADDOP_NAME(C, OP, O, TYPE) { \
1100 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1101 return 0; \
1102}
1103
1104#define ADDOP_I(C, OP, O) { \
1105 if (!compiler_addop_i((C), (OP), (O))) \
1106 return 0; \
1107}
1108
1109#define ADDOP_JABS(C, OP, O) { \
1110 if (!compiler_addop_j((C), (OP), (O), 1)) \
1111 return 0; \
1112}
1113
1114#define ADDOP_JREL(C, OP, O) { \
1115 if (!compiler_addop_j((C), (OP), (O), 0)) \
1116 return 0; \
1117}
1118
1119/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1120 the ASDL name to synthesize the name of the C type and the visit function.
1121*/
1122
1123#define VISIT(C, TYPE, V) {\
1124 if (!compiler_visit_ ## TYPE((C), (V))) \
1125 return 0; \
1126}
1127
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001128#define VISIT_IN_SCOPE(C, TYPE, V) {\
1129 if (!compiler_visit_ ## TYPE((C), (V))) { \
1130 compiler_exit_scope(c); \
1131 return 0; \
1132 } \
1133}
1134
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135#define VISIT_SLICE(C, V, CTX) {\
1136 if (!compiler_visit_slice((C), (V), (CTX))) \
1137 return 0; \
1138}
1139
1140#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001141 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001143 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001144 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001145 if (!compiler_visit_ ## TYPE((C), elt)) \
1146 return 0; \
1147 } \
1148}
1149
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001150#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001151 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001152 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001153 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001154 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001155 if (!compiler_visit_ ## TYPE((C), elt)) { \
1156 compiler_exit_scope(c); \
1157 return 0; \
1158 } \
1159 } \
1160}
1161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162static int
1163compiler_isdocstring(stmt_ty s)
1164{
1165 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001166 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 return s->v.Expr.value->kind == Str_kind;
1168}
1169
1170/* Compile a sequence of statements, checking for a docstring. */
1171
1172static int
1173compiler_body(struct compiler *c, asdl_seq *stmts)
1174{
1175 int i = 0;
1176 stmt_ty st;
1177
1178 if (!asdl_seq_LEN(stmts))
1179 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001180 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001181 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1182 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 i = 1;
1184 VISIT(c, expr, st->v.Expr.value);
1185 if (!compiler_nameop(c, __doc__, Store))
1186 return 0;
1187 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001188 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001189 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001190 return 1;
1191}
1192
1193static PyCodeObject *
1194compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001195{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001196 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001197 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 static PyObject *module;
1199 if (!module) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001200 module = PyString_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 if (!module)
1202 return NULL;
1203 }
Neal Norwitzed657552006-07-10 00:04:44 +00001204 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1205 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001206 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207 switch (mod->kind) {
1208 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001209 if (!compiler_body(c, mod->v.Module.body)) {
1210 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001212 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 break;
1214 case Interactive_kind:
1215 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001216 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001217 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 break;
1219 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001220 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001221 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 break;
1223 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001224 PyErr_SetString(PyExc_SystemError,
1225 "suite should not be possible");
1226 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001227 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001228 PyErr_Format(PyExc_SystemError,
1229 "module kind %d should not be possible",
1230 mod->kind);
1231 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001232 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233 co = assemble(c, addNone);
1234 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001235 return co;
1236}
1237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238/* The test for LOCAL must come before the test for FREE in order to
1239 handle classes where name is both local and free. The local var is
1240 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001241*/
1242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243static int
1244get_ref_type(struct compiler *c, PyObject *name)
1245{
1246 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 if (scope == 0) {
1248 char buf[350];
1249 PyOS_snprintf(buf, sizeof(buf),
1250 "unknown scope for %.100s in %.100s(%s) in %s\n"
Amaury Forgeot d'Arc59ce0422009-01-17 20:18:59 +00001251 "symbols: %s\nlocals: %s\nglobals: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001252 PyString_AS_STRING(name),
1253 PyString_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001254 PyObject_REPR(c->u->u_ste->ste_id),
1255 c->c_filename,
1256 PyObject_REPR(c->u->u_ste->ste_symbols),
1257 PyObject_REPR(c->u->u_varnames),
1258 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001260 Py_FatalError(buf);
1261 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001262
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001263 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264}
1265
1266static int
1267compiler_lookup_arg(PyObject *dict, PyObject *name)
1268{
1269 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001270 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001274 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001276 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 return PyInt_AS_LONG(v);
1278}
1279
1280static int
1281compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1282{
1283 int i, free = PyCode_GetNumFree(co);
1284 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001285 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1286 ADDOP_I(c, MAKE_FUNCTION, args);
1287 return 1;
1288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289 for (i = 0; i < free; ++i) {
1290 /* Bypass com_addop_varname because it will generate
1291 LOAD_DEREF but LOAD_CLOSURE is needed.
1292 */
1293 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1294 int arg, reftype;
1295
1296 /* Special case: If a class contains a method with a
1297 free variable that has the same name as a method,
1298 the name will be considered free *and* local in the
1299 class. It should be handled by the closure, as
1300 well as by the normal name loookup logic.
1301 */
1302 reftype = get_ref_type(c, name);
1303 if (reftype == CELL)
1304 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1305 else /* (reftype == FREE) */
1306 arg = compiler_lookup_arg(c->u->u_freevars, name);
1307 if (arg == -1) {
1308 printf("lookup %s in %s %d %d\n"
1309 "freevars of %s: %s\n",
1310 PyObject_REPR(name),
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001311 PyString_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 reftype, arg,
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001313 PyString_AS_STRING(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314 PyObject_REPR(co->co_freevars));
1315 Py_FatalError("compiler_make_closure()");
1316 }
1317 ADDOP_I(c, LOAD_CLOSURE, arg);
1318 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001319 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001321 ADDOP_I(c, MAKE_CLOSURE, args);
1322 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323}
1324
1325static int
1326compiler_decorators(struct compiler *c, asdl_seq* decos)
1327{
1328 int i;
1329
1330 if (!decos)
1331 return 1;
1332
1333 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001334 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 }
1336 return 1;
1337}
1338
1339static int
1340compiler_arguments(struct compiler *c, arguments_ty args)
1341{
1342 int i;
1343 int n = asdl_seq_LEN(args->args);
1344 /* Correctly handle nested argument lists */
1345 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001346 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 if (arg->kind == Tuple_kind) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001348 PyObject *id = PyString_FromFormat(".%d", i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349 if (id == NULL) {
1350 return 0;
1351 }
1352 if (!compiler_nameop(c, id, Load)) {
1353 Py_DECREF(id);
1354 return 0;
1355 }
1356 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001357 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358 }
1359 }
1360 return 1;
1361}
1362
1363static int
1364compiler_function(struct compiler *c, stmt_ty s)
1365{
1366 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001367 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 arguments_ty args = s->v.FunctionDef.args;
Christian Heimes5224d282008-02-23 15:01:05 +00001369 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001370 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371 int i, n, docstring;
1372
1373 assert(s->kind == FunctionDef_kind);
1374
1375 if (!compiler_decorators(c, decos))
1376 return 0;
1377 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001378 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1380 s->lineno))
1381 return 0;
1382
Anthony Baxter7b782b62006-04-11 12:01:56 +00001383 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001384 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001385 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001386 first_const = st->v.Expr.value->v.Str.s;
1387 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001388 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001389 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001390 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001392 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393 compiler_arguments(c, args);
1394
1395 c->u->u_argcount = asdl_seq_LEN(args->args);
1396 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001397 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001399 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1400 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401 }
1402 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001403 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404 if (co == NULL)
1405 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001407 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001408 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409
1410 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1411 ADDOP_I(c, CALL_FUNCTION, 1);
1412 }
1413
1414 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1415}
1416
1417static int
1418compiler_class(struct compiler *c, stmt_ty s)
1419{
Christian Heimes5224d282008-02-23 15:01:05 +00001420 int n, i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001421 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001422 PyObject *str;
Christian Heimes5224d282008-02-23 15:01:05 +00001423 asdl_seq* decos = s->v.ClassDef.decorator_list;
1424
1425 if (!compiler_decorators(c, decos))
1426 return 0;
1427
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428 /* push class name on stack, needed by BUILD_CLASS */
1429 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1430 /* push the tuple of base classes on the stack */
1431 n = asdl_seq_LEN(s->v.ClassDef.bases);
1432 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001433 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434 ADDOP_I(c, BUILD_TUPLE, n);
1435 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1436 s->lineno))
1437 return 0;
Amaury Forgeot d'Arc69b747b2008-03-28 20:30:50 +00001438 Py_XDECREF(c->u->u_private);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001439 c->u->u_private = s->v.ClassDef.name;
1440 Py_INCREF(c->u->u_private);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001441 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442 if (!str || !compiler_nameop(c, str, Load)) {
1443 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001444 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001446 }
1447
1448 Py_DECREF(str);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001449 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450 if (!str || !compiler_nameop(c, str, Store)) {
1451 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001452 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001454 }
1455 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001457 if (!compiler_body(c, s->v.ClassDef.body)) {
1458 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001460 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001462 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1463 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001465 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466 if (co == NULL)
1467 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001469 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001470 Py_DECREF(co);
1471
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472 ADDOP_I(c, CALL_FUNCTION, 0);
1473 ADDOP(c, BUILD_CLASS);
Christian Heimes5224d282008-02-23 15:01:05 +00001474 /* apply decorators */
1475 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1476 ADDOP_I(c, CALL_FUNCTION, 1);
1477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1479 return 0;
1480 return 1;
1481}
1482
1483static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001484compiler_ifexp(struct compiler *c, expr_ty e)
1485{
1486 basicblock *end, *next;
1487
1488 assert(e->kind == IfExp_kind);
1489 end = compiler_new_block(c);
1490 if (end == NULL)
1491 return 0;
1492 next = compiler_new_block(c);
1493 if (next == NULL)
1494 return 0;
1495 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001496 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001497 VISIT(c, expr, e->v.IfExp.body);
1498 ADDOP_JREL(c, JUMP_FORWARD, end);
1499 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001500 VISIT(c, expr, e->v.IfExp.orelse);
1501 compiler_use_next_block(c, end);
1502 return 1;
1503}
1504
1505static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506compiler_lambda(struct compiler *c, expr_ty e)
1507{
1508 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001509 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510 arguments_ty args = e->v.Lambda.args;
1511 assert(e->kind == Lambda_kind);
1512
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001513 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001514 name = PyString_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001515 if (!name)
1516 return 0;
1517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518
1519 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001520 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1522 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001523
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001524 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525 compiler_arguments(c, args);
1526
1527 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001528 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson8d5934b2008-12-27 18:24:11 +00001529 if (c->u->u_ste->ste_generator) {
1530 ADDOP_IN_SCOPE(c, POP_TOP);
1531 }
1532 else {
1533 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001536 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537 if (co == NULL)
1538 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001540 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001541 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542
1543 return 1;
1544}
1545
1546static int
1547compiler_print(struct compiler *c, stmt_ty s)
1548{
1549 int i, n;
1550 bool dest;
1551
1552 assert(s->kind == Print_kind);
1553 n = asdl_seq_LEN(s->v.Print.values);
1554 dest = false;
1555 if (s->v.Print.dest) {
1556 VISIT(c, expr, s->v.Print.dest);
1557 dest = true;
1558 }
1559 for (i = 0; i < n; i++) {
1560 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1561 if (dest) {
1562 ADDOP(c, DUP_TOP);
1563 VISIT(c, expr, e);
1564 ADDOP(c, ROT_TWO);
1565 ADDOP(c, PRINT_ITEM_TO);
1566 }
1567 else {
1568 VISIT(c, expr, e);
1569 ADDOP(c, PRINT_ITEM);
1570 }
1571 }
1572 if (s->v.Print.nl) {
1573 if (dest)
1574 ADDOP(c, PRINT_NEWLINE_TO)
1575 else
1576 ADDOP(c, PRINT_NEWLINE)
1577 }
1578 else if (dest)
1579 ADDOP(c, POP_TOP);
1580 return 1;
1581}
1582
1583static int
1584compiler_if(struct compiler *c, stmt_ty s)
1585{
1586 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001587 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588 assert(s->kind == If_kind);
1589 end = compiler_new_block(c);
1590 if (end == NULL)
1591 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001592
1593 constant = expr_constant(s->v.If.test);
1594 /* constant = 0: "if 0"
1595 * constant = 1: "if 1", "if 2", ...
1596 * constant = -1: rest */
1597 if (constant == 0) {
1598 if (s->v.If.orelse)
1599 VISIT_SEQ(c, stmt, s->v.If.orelse);
1600 } else if (constant == 1) {
1601 VISIT_SEQ(c, stmt, s->v.If.body);
1602 } else {
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001603 if (s->v.If.orelse) {
1604 next = compiler_new_block(c);
1605 if (next == NULL)
1606 return 0;
1607 }
1608 else
1609 next = end;
Georg Brandlddbaa662006-06-04 21:56:52 +00001610 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001611 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Georg Brandlddbaa662006-06-04 21:56:52 +00001612 VISIT_SEQ(c, stmt, s->v.If.body);
1613 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001614 if (s->v.If.orelse) {
1615 compiler_use_next_block(c, next);
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001616 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001617 }
Georg Brandlddbaa662006-06-04 21:56:52 +00001618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001619 compiler_use_next_block(c, end);
1620 return 1;
1621}
1622
1623static int
1624compiler_for(struct compiler *c, stmt_ty s)
1625{
1626 basicblock *start, *cleanup, *end;
1627
1628 start = compiler_new_block(c);
1629 cleanup = compiler_new_block(c);
1630 end = compiler_new_block(c);
1631 if (start == NULL || end == NULL || cleanup == NULL)
1632 return 0;
1633 ADDOP_JREL(c, SETUP_LOOP, end);
1634 if (!compiler_push_fblock(c, LOOP, start))
1635 return 0;
1636 VISIT(c, expr, s->v.For.iter);
1637 ADDOP(c, GET_ITER);
1638 compiler_use_next_block(c, start);
1639 ADDOP_JREL(c, FOR_ITER, cleanup);
1640 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001641 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001642 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1643 compiler_use_next_block(c, cleanup);
1644 ADDOP(c, POP_BLOCK);
1645 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001646 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001647 compiler_use_next_block(c, end);
1648 return 1;
1649}
1650
1651static int
1652compiler_while(struct compiler *c, stmt_ty s)
1653{
1654 basicblock *loop, *orelse, *end, *anchor = NULL;
1655 int constant = expr_constant(s->v.While.test);
1656
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001657 if (constant == 0) {
1658 if (s->v.While.orelse)
1659 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660 return 1;
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001661 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662 loop = compiler_new_block(c);
1663 end = compiler_new_block(c);
1664 if (constant == -1) {
1665 anchor = compiler_new_block(c);
1666 if (anchor == NULL)
1667 return 0;
1668 }
1669 if (loop == NULL || end == NULL)
1670 return 0;
1671 if (s->v.While.orelse) {
1672 orelse = compiler_new_block(c);
1673 if (orelse == NULL)
1674 return 0;
1675 }
1676 else
1677 orelse = NULL;
1678
1679 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001680 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681 if (!compiler_push_fblock(c, LOOP, loop))
1682 return 0;
1683 if (constant == -1) {
1684 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001685 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001687 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1689
1690 /* XXX should the two POP instructions be in a separate block
1691 if there is no else clause ?
1692 */
1693
1694 if (constant == -1) {
1695 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 ADDOP(c, POP_BLOCK);
1697 }
1698 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001699 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001700 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701 compiler_use_next_block(c, end);
1702
1703 return 1;
1704}
1705
1706static int
1707compiler_continue(struct compiler *c)
1708{
1709 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001710 static const char IN_FINALLY_ERROR_MSG[] =
1711 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001712 int i;
1713
1714 if (!c->u->u_nfblocks)
1715 return compiler_error(c, LOOP_ERROR_MSG);
1716 i = c->u->u_nfblocks - 1;
1717 switch (c->u->u_fblock[i].fb_type) {
1718 case LOOP:
1719 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1720 break;
1721 case EXCEPT:
1722 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001723 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1724 /* Prevent continue anywhere under a finally
1725 even if hidden in a sub-try or except. */
1726 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1727 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1728 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001729 if (i == -1)
1730 return compiler_error(c, LOOP_ERROR_MSG);
1731 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1732 break;
1733 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001734 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735 }
1736
1737 return 1;
1738}
1739
1740/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1741
1742 SETUP_FINALLY L
1743 <code for body>
1744 POP_BLOCK
1745 LOAD_CONST <None>
1746 L: <code for finalbody>
1747 END_FINALLY
1748
1749 The special instructions use the block stack. Each block
1750 stack entry contains the instruction that created it (here
1751 SETUP_FINALLY), the level of the value stack at the time the
1752 block stack entry was created, and a label (here L).
1753
1754 SETUP_FINALLY:
1755 Pushes the current value stack level and the label
1756 onto the block stack.
1757 POP_BLOCK:
1758 Pops en entry from the block stack, and pops the value
1759 stack until its level is the same as indicated on the
1760 block stack. (The label is ignored.)
1761 END_FINALLY:
1762 Pops a variable number of entries from the *value* stack
1763 and re-raises the exception they specify. The number of
1764 entries popped depends on the (pseudo) exception type.
1765
1766 The block stack is unwound when an exception is raised:
1767 when a SETUP_FINALLY entry is found, the exception is pushed
1768 onto the value stack (and the exception condition is cleared),
1769 and the interpreter jumps to the label gotten from the block
1770 stack.
1771*/
1772
1773static int
1774compiler_try_finally(struct compiler *c, stmt_ty s)
1775{
1776 basicblock *body, *end;
1777 body = compiler_new_block(c);
1778 end = compiler_new_block(c);
1779 if (body == NULL || end == NULL)
1780 return 0;
1781
1782 ADDOP_JREL(c, SETUP_FINALLY, end);
1783 compiler_use_next_block(c, body);
1784 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1785 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001786 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787 ADDOP(c, POP_BLOCK);
1788 compiler_pop_fblock(c, FINALLY_TRY, body);
1789
1790 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1791 compiler_use_next_block(c, end);
1792 if (!compiler_push_fblock(c, FINALLY_END, end))
1793 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001794 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795 ADDOP(c, END_FINALLY);
1796 compiler_pop_fblock(c, FINALLY_END, end);
1797
1798 return 1;
1799}
1800
1801/*
1802 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1803 (The contents of the value stack is shown in [], with the top
1804 at the right; 'tb' is trace-back info, 'val' the exception's
1805 associated value, and 'exc' the exception.)
1806
1807 Value stack Label Instruction Argument
1808 [] SETUP_EXCEPT L1
1809 [] <code for S>
1810 [] POP_BLOCK
1811 [] JUMP_FORWARD L0
1812
1813 [tb, val, exc] L1: DUP )
1814 [tb, val, exc, exc] <evaluate E1> )
1815 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001816 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817 [tb, val, exc] POP
1818 [tb, val] <assign to V1> (or POP if no V1)
1819 [tb] POP
1820 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001821 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001823 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824 .............................etc.......................
1825
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001826 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827
1828 [] L0: <next statement>
1829
1830 Of course, parts are not generated if Vi or Ei is not present.
1831*/
1832static int
1833compiler_try_except(struct compiler *c, stmt_ty s)
1834{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001835 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 int i, n;
1837
1838 body = compiler_new_block(c);
1839 except = compiler_new_block(c);
1840 orelse = compiler_new_block(c);
1841 end = compiler_new_block(c);
1842 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1843 return 0;
1844 ADDOP_JREL(c, SETUP_EXCEPT, except);
1845 compiler_use_next_block(c, body);
1846 if (!compiler_push_fblock(c, EXCEPT, body))
1847 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001848 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849 ADDOP(c, POP_BLOCK);
1850 compiler_pop_fblock(c, EXCEPT, body);
1851 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1852 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1853 compiler_use_next_block(c, except);
1854 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001855 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856 s->v.TryExcept.handlers, i);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001857 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +00001859 c->u->u_lineno_set = false;
1860 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 except = compiler_new_block(c);
1862 if (except == NULL)
1863 return 0;
Georg Brandla48f3ab2008-03-30 06:40:17 +00001864 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 ADDOP(c, DUP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001866 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001868 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 }
1870 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001871 if (handler->v.ExceptHandler.name) {
1872 VISIT(c, expr, handler->v.ExceptHandler.name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873 }
1874 else {
1875 ADDOP(c, POP_TOP);
1876 }
1877 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001878 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 ADDOP_JREL(c, JUMP_FORWARD, end);
1880 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881 }
1882 ADDOP(c, END_FINALLY);
1883 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001884 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885 compiler_use_next_block(c, end);
1886 return 1;
1887}
1888
1889static int
1890compiler_import_as(struct compiler *c, identifier name, identifier asname)
1891{
1892 /* The IMPORT_NAME opcode was already generated. This function
1893 merely needs to bind the result to a name.
1894
1895 If there is a dot in name, we need to split it and emit a
1896 LOAD_ATTR for each name.
1897 */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001898 const char *src = PyString_AS_STRING(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899 const char *dot = strchr(src, '.');
1900 if (dot) {
1901 /* Consume the base module name to get the first attribute */
1902 src = dot + 1;
1903 while (dot) {
1904 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001905 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906 dot = strchr(src, '.');
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001907 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001909 if (!attr)
1910 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001912 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913 src = dot + 1;
1914 }
1915 }
1916 return compiler_nameop(c, asname, Store);
1917}
1918
1919static int
1920compiler_import(struct compiler *c, stmt_ty s)
1921{
1922 /* The Import node stores a module name like a.b.c as a single
1923 string. This is convenient for all cases except
1924 import a.b.c as d
1925 where we need to parse that string to extract the individual
1926 module names.
1927 XXX Perhaps change the representation to make this case simpler?
1928 */
1929 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001930
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001932 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001934 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
Neal Norwitzcbce2802006-04-03 06:26:32 +00001936 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001937 level = PyInt_FromLong(0);
1938 else
1939 level = PyInt_FromLong(-1);
1940
1941 if (level == NULL)
1942 return 0;
1943
1944 ADDOP_O(c, LOAD_CONST, level, consts);
1945 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1947 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1948
1949 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001950 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001951 if (!r)
1952 return r;
1953 }
1954 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955 identifier tmp = alias->name;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001956 const char *base = PyString_AS_STRING(alias->name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957 char *dot = strchr(base, '.');
1958 if (dot)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001959 tmp = PyString_FromStringAndSize(base,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 dot - base);
1961 r = compiler_nameop(c, tmp, Store);
1962 if (dot) {
1963 Py_DECREF(tmp);
1964 }
1965 if (!r)
1966 return r;
1967 }
1968 }
1969 return 1;
1970}
1971
1972static int
1973compiler_from_import(struct compiler *c, stmt_ty s)
1974{
1975 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
1977 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001978 PyObject *level;
Benjamin Petersona72be3b2009-06-13 20:23:33 +00001979 static PyObject *empty_string;
1980
1981 if (!empty_string) {
1982 empty_string = PyString_FromString("");
1983 if (!empty_string)
1984 return 0;
1985 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001986
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 if (!names)
1988 return 0;
1989
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001990 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001991 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001992 level = PyInt_FromLong(-1);
1993 else
1994 level = PyInt_FromLong(s->v.ImportFrom.level);
1995
1996 if (!level) {
1997 Py_DECREF(names);
1998 return 0;
1999 }
2000
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 /* build up the names */
2002 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002003 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 Py_INCREF(alias->name);
2005 PyTuple_SET_ITEM(names, i, alias->name);
2006 }
2007
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002008 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2009 !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
2010 Py_DECREF(level);
2011 Py_DECREF(names);
2012 return compiler_error(c, "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002013 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 }
2015
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002016 ADDOP_O(c, LOAD_CONST, level, consts);
2017 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002018 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002019 Py_DECREF(names);
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002020 if (s->v.ImportFrom.module) {
2021 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2022 }
2023 else {
2024 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2025 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002027 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028 identifier store_name;
2029
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002030 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031 assert(n == 1);
2032 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002033 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034 }
2035
2036 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2037 store_name = alias->name;
2038 if (alias->asname)
2039 store_name = alias->asname;
2040
2041 if (!compiler_nameop(c, store_name, Store)) {
2042 Py_DECREF(names);
2043 return 0;
2044 }
2045 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002046 /* remove imported module */
2047 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048 return 1;
2049}
2050
2051static int
2052compiler_assert(struct compiler *c, stmt_ty s)
2053{
2054 static PyObject *assertion_error = NULL;
2055 basicblock *end;
2056
2057 if (Py_OptimizeFlag)
2058 return 1;
2059 if (assertion_error == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002060 assertion_error = PyString_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 if (assertion_error == NULL)
2062 return 0;
2063 }
Neal Norwitz400aeda2008-03-15 22:03:18 +00002064 if (s->v.Assert.test->kind == Tuple_kind &&
2065 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2066 const char* msg =
2067 "assertion is always true, perhaps remove parentheses?";
2068 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2069 c->u->u_lineno, NULL, NULL) == -1)
2070 return 0;
2071 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 VISIT(c, expr, s->v.Assert.test);
2073 end = compiler_new_block(c);
2074 if (end == NULL)
2075 return 0;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002076 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2078 if (s->v.Assert.msg) {
2079 VISIT(c, expr, s->v.Assert.msg);
2080 ADDOP_I(c, RAISE_VARARGS, 2);
2081 }
2082 else {
2083 ADDOP_I(c, RAISE_VARARGS, 1);
2084 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002085 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 return 1;
2087}
2088
2089static int
2090compiler_visit_stmt(struct compiler *c, stmt_ty s)
2091{
2092 int i, n;
2093
Neal Norwitzf733a012006-10-29 18:30:10 +00002094 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 c->u->u_lineno = s->lineno;
2096 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002097
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002101 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 if (c->u->u_ste->ste_type != FunctionBlock)
2105 return compiler_error(c, "'return' outside function");
2106 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 VISIT(c, expr, s->v.Return.value);
2108 }
2109 else
2110 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2111 ADDOP(c, RETURN_VALUE);
2112 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002113 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002114 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002116 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 n = asdl_seq_LEN(s->v.Assign.targets);
2118 VISIT(c, expr, s->v.Assign.value);
2119 for (i = 0; i < n; i++) {
2120 if (i < n - 1)
2121 ADDOP(c, DUP_TOP);
2122 VISIT(c, expr,
2123 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2124 }
2125 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002126 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002128 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002130 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002132 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002134 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002136 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137 n = 0;
2138 if (s->v.Raise.type) {
2139 VISIT(c, expr, s->v.Raise.type);
2140 n++;
2141 if (s->v.Raise.inst) {
2142 VISIT(c, expr, s->v.Raise.inst);
2143 n++;
2144 if (s->v.Raise.tback) {
2145 VISIT(c, expr, s->v.Raise.tback);
2146 n++;
2147 }
2148 }
2149 }
2150 ADDOP_I(c, RAISE_VARARGS, n);
2151 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002152 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002154 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002156 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002158 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002160 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002162 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 VISIT(c, expr, s->v.Exec.body);
2164 if (s->v.Exec.globals) {
2165 VISIT(c, expr, s->v.Exec.globals);
2166 if (s->v.Exec.locals) {
2167 VISIT(c, expr, s->v.Exec.locals);
2168 } else {
2169 ADDOP(c, DUP_TOP);
2170 }
2171 } else {
2172 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2173 ADDOP(c, DUP_TOP);
2174 }
2175 ADDOP(c, EXEC_STMT);
2176 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002177 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002179 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002181 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182 ADDOP(c, PRINT_EXPR);
2183 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002184 else if (s->v.Expr.value->kind != Str_kind &&
2185 s->v.Expr.value->kind != Num_kind) {
2186 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002187 ADDOP(c, POP_TOP);
2188 }
2189 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002190 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002192 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002193 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194 return compiler_error(c, "'break' outside loop");
2195 ADDOP(c, BREAK_LOOP);
2196 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002197 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002199 case With_kind:
2200 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201 }
2202 return 1;
2203}
2204
2205static int
2206unaryop(unaryop_ty op)
2207{
2208 switch (op) {
2209 case Invert:
2210 return UNARY_INVERT;
2211 case Not:
2212 return UNARY_NOT;
2213 case UAdd:
2214 return UNARY_POSITIVE;
2215 case USub:
2216 return UNARY_NEGATIVE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002217 default:
2218 PyErr_Format(PyExc_SystemError,
2219 "unary op %d should not be possible", op);
2220 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222}
2223
2224static int
2225binop(struct compiler *c, operator_ty op)
2226{
2227 switch (op) {
2228 case Add:
2229 return BINARY_ADD;
2230 case Sub:
2231 return BINARY_SUBTRACT;
2232 case Mult:
2233 return BINARY_MULTIPLY;
2234 case Div:
2235 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2236 return BINARY_TRUE_DIVIDE;
2237 else
2238 return BINARY_DIVIDE;
2239 case Mod:
2240 return BINARY_MODULO;
2241 case Pow:
2242 return BINARY_POWER;
2243 case LShift:
2244 return BINARY_LSHIFT;
2245 case RShift:
2246 return BINARY_RSHIFT;
2247 case BitOr:
2248 return BINARY_OR;
2249 case BitXor:
2250 return BINARY_XOR;
2251 case BitAnd:
2252 return BINARY_AND;
2253 case FloorDiv:
2254 return BINARY_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002255 default:
2256 PyErr_Format(PyExc_SystemError,
2257 "binary op %d should not be possible", op);
2258 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260}
2261
2262static int
2263cmpop(cmpop_ty op)
2264{
2265 switch (op) {
2266 case Eq:
2267 return PyCmp_EQ;
2268 case NotEq:
2269 return PyCmp_NE;
2270 case Lt:
2271 return PyCmp_LT;
2272 case LtE:
2273 return PyCmp_LE;
2274 case Gt:
2275 return PyCmp_GT;
2276 case GtE:
2277 return PyCmp_GE;
2278 case Is:
2279 return PyCmp_IS;
2280 case IsNot:
2281 return PyCmp_IS_NOT;
2282 case In:
2283 return PyCmp_IN;
2284 case NotIn:
2285 return PyCmp_NOT_IN;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002286 default:
2287 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289}
2290
2291static int
2292inplace_binop(struct compiler *c, operator_ty op)
2293{
2294 switch (op) {
2295 case Add:
2296 return INPLACE_ADD;
2297 case Sub:
2298 return INPLACE_SUBTRACT;
2299 case Mult:
2300 return INPLACE_MULTIPLY;
2301 case Div:
2302 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2303 return INPLACE_TRUE_DIVIDE;
2304 else
2305 return INPLACE_DIVIDE;
2306 case Mod:
2307 return INPLACE_MODULO;
2308 case Pow:
2309 return INPLACE_POWER;
2310 case LShift:
2311 return INPLACE_LSHIFT;
2312 case RShift:
2313 return INPLACE_RSHIFT;
2314 case BitOr:
2315 return INPLACE_OR;
2316 case BitXor:
2317 return INPLACE_XOR;
2318 case BitAnd:
2319 return INPLACE_AND;
2320 case FloorDiv:
2321 return INPLACE_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002322 default:
2323 PyErr_Format(PyExc_SystemError,
2324 "inplace binary op %d should not be possible", op);
2325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002326 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327}
2328
2329static int
2330compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2331{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002332 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2334
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002335 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002336 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 /* XXX AugStore isn't used anywhere! */
2338
Neal Norwitz0031ff32008-02-25 01:45:37 +00002339 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002340 if (!mangled)
2341 return 0;
2342
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343 op = 0;
2344 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002345 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002346 switch (scope) {
2347 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002348 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 optype = OP_DEREF;
2350 break;
2351 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002352 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353 optype = OP_DEREF;
2354 break;
2355 case LOCAL:
2356 if (c->u->u_ste->ste_type == FunctionBlock)
2357 optype = OP_FAST;
2358 break;
2359 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002360 if (c->u->u_ste->ste_type == FunctionBlock &&
2361 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362 optype = OP_GLOBAL;
2363 break;
2364 case GLOBAL_EXPLICIT:
2365 optype = OP_GLOBAL;
2366 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002367 default:
2368 /* scope can be 0 */
2369 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370 }
2371
2372 /* XXX Leave assert here, but handle __doc__ and the like better */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002373 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002374
2375 switch (optype) {
2376 case OP_DEREF:
2377 switch (ctx) {
2378 case Load: op = LOAD_DEREF; break;
2379 case Store: op = STORE_DEREF; break;
2380 case AugLoad:
2381 case AugStore:
2382 break;
2383 case Del:
2384 PyErr_Format(PyExc_SyntaxError,
2385 "can not delete variable '%s' referenced "
2386 "in nested scope",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002387 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002388 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002391 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002392 PyErr_SetString(PyExc_SystemError,
2393 "param invalid for deref variable");
2394 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395 }
2396 break;
2397 case OP_FAST:
2398 switch (ctx) {
2399 case Load: op = LOAD_FAST; break;
2400 case Store: op = STORE_FAST; break;
2401 case Del: op = DELETE_FAST; break;
2402 case AugLoad:
2403 case AugStore:
2404 break;
2405 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002406 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002407 PyErr_SetString(PyExc_SystemError,
2408 "param invalid for local variable");
2409 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002411 ADDOP_O(c, op, mangled, varnames);
2412 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413 return 1;
2414 case OP_GLOBAL:
2415 switch (ctx) {
2416 case Load: op = LOAD_GLOBAL; break;
2417 case Store: op = STORE_GLOBAL; break;
2418 case Del: op = DELETE_GLOBAL; break;
2419 case AugLoad:
2420 case AugStore:
2421 break;
2422 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002423 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002424 PyErr_SetString(PyExc_SystemError,
2425 "param invalid for global variable");
2426 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427 }
2428 break;
2429 case OP_NAME:
2430 switch (ctx) {
2431 case Load: op = LOAD_NAME; break;
2432 case Store: op = STORE_NAME; break;
2433 case Del: op = DELETE_NAME; break;
2434 case AugLoad:
2435 case AugStore:
2436 break;
2437 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002438 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002439 PyErr_SetString(PyExc_SystemError,
2440 "param invalid for name variable");
2441 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442 }
2443 break;
2444 }
2445
2446 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002447 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002448 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002449 if (arg < 0)
2450 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002451 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002452}
2453
2454static int
2455compiler_boolop(struct compiler *c, expr_ty e)
2456{
2457 basicblock *end;
2458 int jumpi, i, n;
2459 asdl_seq *s;
2460
2461 assert(e->kind == BoolOp_kind);
2462 if (e->v.BoolOp.op == And)
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002463 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 else
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002465 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002467 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 return 0;
2469 s = e->v.BoolOp.values;
2470 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002471 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002473 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002474 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002476 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 compiler_use_next_block(c, end);
2478 return 1;
2479}
2480
2481static int
2482compiler_list(struct compiler *c, expr_ty e)
2483{
2484 int n = asdl_seq_LEN(e->v.List.elts);
2485 if (e->v.List.ctx == Store) {
2486 ADDOP_I(c, UNPACK_SEQUENCE, n);
2487 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002488 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 if (e->v.List.ctx == Load) {
2490 ADDOP_I(c, BUILD_LIST, n);
2491 }
2492 return 1;
2493}
2494
2495static int
2496compiler_tuple(struct compiler *c, expr_ty e)
2497{
2498 int n = asdl_seq_LEN(e->v.Tuple.elts);
2499 if (e->v.Tuple.ctx == Store) {
2500 ADDOP_I(c, UNPACK_SEQUENCE, n);
2501 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002502 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503 if (e->v.Tuple.ctx == Load) {
2504 ADDOP_I(c, BUILD_TUPLE, n);
2505 }
2506 return 1;
2507}
2508
2509static int
2510compiler_compare(struct compiler *c, expr_ty e)
2511{
2512 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002513 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514
2515 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2516 VISIT(c, expr, e->v.Compare.left);
2517 n = asdl_seq_LEN(e->v.Compare.ops);
2518 assert(n > 0);
2519 if (n > 1) {
2520 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002521 if (cleanup == NULL)
2522 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002523 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002524 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 }
2526 for (i = 1; i < n; i++) {
2527 ADDOP(c, DUP_TOP);
2528 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002530 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002531 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002532 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002535 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002536 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002538 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002540 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 if (n > 1) {
2542 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002543 if (end == NULL)
2544 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545 ADDOP_JREL(c, JUMP_FORWARD, end);
2546 compiler_use_next_block(c, cleanup);
2547 ADDOP(c, ROT_TWO);
2548 ADDOP(c, POP_TOP);
2549 compiler_use_next_block(c, end);
2550 }
2551 return 1;
2552}
2553
2554static int
2555compiler_call(struct compiler *c, expr_ty e)
2556{
2557 int n, code = 0;
2558
2559 VISIT(c, expr, e->v.Call.func);
2560 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002561 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002563 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2565 }
2566 if (e->v.Call.starargs) {
2567 VISIT(c, expr, e->v.Call.starargs);
2568 code |= 1;
2569 }
2570 if (e->v.Call.kwargs) {
2571 VISIT(c, expr, e->v.Call.kwargs);
2572 code |= 2;
2573 }
2574 switch (code) {
2575 case 0:
2576 ADDOP_I(c, CALL_FUNCTION, n);
2577 break;
2578 case 1:
2579 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2580 break;
2581 case 2:
2582 ADDOP_I(c, CALL_FUNCTION_KW, n);
2583 break;
2584 case 3:
2585 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2586 break;
2587 }
2588 return 1;
2589}
2590
2591static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002592compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
2593 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594{
2595 /* generate code for the iterator, then each of the ifs,
2596 and then write to the element */
2597
2598 comprehension_ty l;
2599 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002600 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601
2602 start = compiler_new_block(c);
2603 skip = compiler_new_block(c);
2604 if_cleanup = compiler_new_block(c);
2605 anchor = compiler_new_block(c);
2606
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002607 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2608 anchor == NULL)
2609 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610
Anthony Baxter7b782b62006-04-11 12:01:56 +00002611 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 VISIT(c, expr, l->iter);
2613 ADDOP(c, GET_ITER);
2614 compiler_use_next_block(c, start);
2615 ADDOP_JREL(c, FOR_ITER, anchor);
2616 NEXT_BLOCK(c);
2617 VISIT(c, expr, l->target);
2618
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002619 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620 n = asdl_seq_LEN(l->ifs);
2621 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002622 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002624 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 }
2627
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002628 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitroud0c35152008-12-17 00:38:28 +00002629 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 /* only append after the last for generator */
2633 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 VISIT(c, expr, elt);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002635 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636
2637 compiler_use_next_block(c, skip);
2638 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002639 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2641 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642
2643 return 1;
2644}
2645
2646static int
2647compiler_listcomp(struct compiler *c, expr_ty e)
2648{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 assert(e->kind == ListComp_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 ADDOP_I(c, BUILD_LIST, 0);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002651 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2652 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653}
2654
2655static int
2656compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002657 asdl_seq *generators, int gen_index,
2658 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659{
2660 /* generate code for the iterator, then each of the ifs,
2661 and then write to the element */
2662
2663 comprehension_ty ge;
2664 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666
2667 start = compiler_new_block(c);
2668 skip = compiler_new_block(c);
2669 if_cleanup = compiler_new_block(c);
2670 anchor = compiler_new_block(c);
2671 end = compiler_new_block(c);
2672
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 anchor == NULL || end == NULL)
2675 return 0;
2676
Anthony Baxter7b782b62006-04-11 12:01:56 +00002677 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 ADDOP_JREL(c, SETUP_LOOP, end);
2679 if (!compiler_push_fblock(c, LOOP, start))
2680 return 0;
2681
2682 if (gen_index == 0) {
2683 /* Receive outermost iter as an implicit argument */
2684 c->u->u_argcount = 1;
2685 ADDOP_I(c, LOAD_FAST, 0);
2686 }
2687 else {
2688 /* Sub-iter - calculate on the fly */
2689 VISIT(c, expr, ge->iter);
2690 ADDOP(c, GET_ITER);
2691 }
2692 compiler_use_next_block(c, start);
2693 ADDOP_JREL(c, FOR_ITER, anchor);
2694 NEXT_BLOCK(c);
2695 VISIT(c, expr, ge->target);
2696
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002697 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 n = asdl_seq_LEN(ge->ifs);
2699 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002700 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002702 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 NEXT_BLOCK(c);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002704 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2708 return 0;
2709
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 /* only append after the last 'for' generator */
2711 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 VISIT(c, expr, elt);
2713 ADDOP(c, YIELD_VALUE);
2714 ADDOP(c, POP_TOP);
2715
2716 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002717 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002718 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2720 compiler_use_next_block(c, anchor);
2721 ADDOP(c, POP_BLOCK);
2722 compiler_pop_fblock(c, LOOP, start);
2723 compiler_use_next_block(c, end);
2724
2725 return 1;
2726}
2727
2728static int
2729compiler_genexp(struct compiler *c, expr_ty e)
2730{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002731 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 PyCodeObject *co;
2733 expr_ty outermost_iter = ((comprehension_ty)
2734 (asdl_seq_GET(e->v.GeneratorExp.generators,
2735 0)))->iter;
2736
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002737 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002738 name = PyString_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002739 if (!name)
2740 return 0;
2741 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742
2743 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2744 return 0;
2745 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2746 e->v.GeneratorExp.elt);
2747 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002748 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749 if (co == NULL)
2750 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002752 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002753 Py_DECREF(co);
2754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755 VISIT(c, expr, outermost_iter);
2756 ADDOP(c, GET_ITER);
2757 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758
2759 return 1;
2760}
2761
2762static int
2763compiler_visit_keyword(struct compiler *c, keyword_ty k)
2764{
2765 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2766 VISIT(c, expr, k->value);
2767 return 1;
2768}
2769
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002770/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771 whether they are true or false.
2772
2773 Return values: 1 for true, 0 for false, -1 for non-constant.
2774 */
2775
2776static int
2777expr_constant(expr_ty e)
2778{
2779 switch (e->kind) {
2780 case Num_kind:
2781 return PyObject_IsTrue(e->v.Num.n);
2782 case Str_kind:
2783 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002784 case Name_kind:
2785 /* __debug__ is not assignable, so we can optimize
2786 * it away in if and while statements */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002787 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002788 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002789 return ! Py_OptimizeFlag;
2790 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 default:
2792 return -1;
2793 }
2794}
2795
Guido van Rossumc2e20742006-02-27 22:32:47 +00002796/*
2797 Implements the with statement from PEP 343.
2798
2799 The semantics outlined in that PEP are as follows:
2800
2801 with EXPR as VAR:
2802 BLOCK
2803
2804 It is implemented roughly as:
2805
Guido van Rossumda5b7012006-05-02 19:47:52 +00002806 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002807 exit = context.__exit__ # not calling it
2808 value = context.__enter__()
2809 try:
2810 VAR = value # if VAR present in the syntax
2811 BLOCK
2812 finally:
2813 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002814 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002815 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002817 exit(*exc)
2818 */
2819static int
2820compiler_with(struct compiler *c, stmt_ty s)
2821{
Guido van Rossumc2e20742006-02-27 22:32:47 +00002822 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002823
2824 assert(s->kind == With_kind);
2825
Guido van Rossumc2e20742006-02-27 22:32:47 +00002826 block = compiler_new_block(c);
2827 finally = compiler_new_block(c);
2828 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002829 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830
Guido van Rossumda5b7012006-05-02 19:47:52 +00002831 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002832 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002833 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002835 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 compiler_use_next_block(c, block);
2837 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002838 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002839 }
2840
2841 if (s->v.With.optional_vars) {
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002842 VISIT(c, expr, s->v.With.optional_vars);
2843 }
2844 else {
2845 /* Discard result from context.__enter__() */
2846 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002847 }
2848
2849 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002850 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851
2852 /* End of try block; start the finally block */
2853 ADDOP(c, POP_BLOCK);
2854 compiler_pop_fblock(c, FINALLY_TRY, block);
2855
2856 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2857 compiler_use_next_block(c, finally);
2858 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002859 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002860
Nick Coghlan7af53be2008-03-07 14:13:28 +00002861 /* Finally block starts; context.__exit__ is on the stack under
2862 the exception or return information. Just issue our magic
2863 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002864 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002865
2866 /* Finally block ends. */
2867 ADDOP(c, END_FINALLY);
2868 compiler_pop_fblock(c, FINALLY_END, finally);
2869 return 1;
2870}
2871
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872static int
2873compiler_visit_expr(struct compiler *c, expr_ty e)
2874{
2875 int i, n;
2876
Neal Norwitzf733a012006-10-29 18:30:10 +00002877 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002878 set a new line number for the next instruction.
2879 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880 if (e->lineno > c->u->u_lineno) {
2881 c->u->u_lineno = e->lineno;
2882 c->u->u_lineno_set = false;
2883 }
2884 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002885 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002887 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888 VISIT(c, expr, e->v.BinOp.left);
2889 VISIT(c, expr, e->v.BinOp.right);
2890 ADDOP(c, binop(c, e->v.BinOp.op));
2891 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002892 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893 VISIT(c, expr, e->v.UnaryOp.operand);
2894 ADDOP(c, unaryop(e->v.UnaryOp.op));
2895 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002898 case IfExp_kind:
2899 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002900 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettinger70fcfd02007-12-19 22:14:34 +00002902 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002904 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002905 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00002906 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002907 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00002908 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909 }
2910 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002911 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002913 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 return compiler_genexp(c, e);
2915 case Yield_kind:
2916 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002917 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 if (e->v.Yield.value) {
2919 VISIT(c, expr, e->v.Yield.value);
2920 }
2921 else {
2922 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2923 }
2924 ADDOP(c, YIELD_VALUE);
2925 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002928 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002930 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 VISIT(c, expr, e->v.Repr.value);
2932 ADDOP(c, UNARY_CONVERT);
2933 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002934 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2936 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002937 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2939 break;
2940 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002941 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 if (e->v.Attribute.ctx != AugStore)
2943 VISIT(c, expr, e->v.Attribute.value);
2944 switch (e->v.Attribute.ctx) {
2945 case AugLoad:
2946 ADDOP(c, DUP_TOP);
2947 /* Fall through to load */
2948 case Load:
2949 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2950 break;
2951 case AugStore:
2952 ADDOP(c, ROT_TWO);
2953 /* Fall through to save */
2954 case Store:
2955 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2956 break;
2957 case Del:
2958 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2959 break;
2960 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002961 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002962 PyErr_SetString(PyExc_SystemError,
2963 "param invalid in attribute expression");
2964 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965 }
2966 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002967 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968 switch (e->v.Subscript.ctx) {
2969 case AugLoad:
2970 VISIT(c, expr, e->v.Subscript.value);
2971 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2972 break;
2973 case Load:
2974 VISIT(c, expr, e->v.Subscript.value);
2975 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2976 break;
2977 case AugStore:
2978 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2979 break;
2980 case Store:
2981 VISIT(c, expr, e->v.Subscript.value);
2982 VISIT_SLICE(c, e->v.Subscript.slice, Store);
2983 break;
2984 case Del:
2985 VISIT(c, expr, e->v.Subscript.value);
2986 VISIT_SLICE(c, e->v.Subscript.slice, Del);
2987 break;
2988 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002989 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002990 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002991 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00002992 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993 }
2994 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002995 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
2997 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002998 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003000 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001 return compiler_tuple(c, e);
3002 }
3003 return 1;
3004}
3005
3006static int
3007compiler_augassign(struct compiler *c, stmt_ty s)
3008{
3009 expr_ty e = s->v.AugAssign.target;
3010 expr_ty auge;
3011
3012 assert(s->kind == AugAssign_kind);
3013
3014 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003015 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003017 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003018 if (auge == NULL)
3019 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003020 VISIT(c, expr, auge);
3021 VISIT(c, expr, s->v.AugAssign.value);
3022 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3023 auge->v.Attribute.ctx = AugStore;
3024 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025 break;
3026 case Subscript_kind:
3027 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003028 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003029 if (auge == NULL)
3030 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031 VISIT(c, expr, auge);
3032 VISIT(c, expr, s->v.AugAssign.value);
3033 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003034 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003036 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003038 if (!compiler_nameop(c, e->v.Name.id, Load))
3039 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 VISIT(c, expr, s->v.AugAssign.value);
3041 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3042 return compiler_nameop(c, e->v.Name.id, Store);
3043 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003044 PyErr_Format(PyExc_SystemError,
3045 "invalid node type (%d) for augmented assignment",
3046 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003047 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048 }
3049 return 1;
3050}
3051
3052static int
3053compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3054{
3055 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003056 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3057 PyErr_SetString(PyExc_SystemError,
3058 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003060 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061 f = &c->u->u_fblock[c->u->u_nfblocks++];
3062 f->fb_type = t;
3063 f->fb_block = b;
3064 return 1;
3065}
3066
3067static void
3068compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3069{
3070 struct compiler_unit *u = c->u;
3071 assert(u->u_nfblocks > 0);
3072 u->u_nfblocks--;
3073 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3074 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3075}
3076
Jeremy Hylton82271f12006-10-04 02:24:52 +00003077static int
3078compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003079 int i;
3080 struct compiler_unit *u = c->u;
3081 for (i = 0; i < u->u_nfblocks; ++i) {
3082 if (u->u_fblock[i].fb_type == LOOP)
3083 return 1;
3084 }
3085 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003086}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087/* Raises a SyntaxError and returns 0.
3088 If something goes wrong, a different exception may be raised.
3089*/
3090
3091static int
3092compiler_error(struct compiler *c, const char *errstr)
3093{
3094 PyObject *loc;
3095 PyObject *u = NULL, *v = NULL;
3096
3097 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3098 if (!loc) {
3099 Py_INCREF(Py_None);
3100 loc = Py_None;
3101 }
3102 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3103 Py_None, loc);
3104 if (!u)
3105 goto exit;
3106 v = Py_BuildValue("(zO)", errstr, u);
3107 if (!v)
3108 goto exit;
3109 PyErr_SetObject(PyExc_SyntaxError, v);
3110 exit:
3111 Py_DECREF(loc);
3112 Py_XDECREF(u);
3113 Py_XDECREF(v);
3114 return 0;
3115}
3116
3117static int
3118compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003119 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003120{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003121 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 /* XXX this code is duplicated */
3124 switch (ctx) {
3125 case AugLoad: /* fall through to Load */
3126 case Load: op = BINARY_SUBSCR; break;
3127 case AugStore:/* fall through to Store */
3128 case Store: op = STORE_SUBSCR; break;
3129 case Del: op = DELETE_SUBSCR; break;
3130 case Param:
3131 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003132 "invalid %s kind %d in subscript\n",
3133 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 return 0;
3135 }
3136 if (ctx == AugLoad) {
3137 ADDOP_I(c, DUP_TOPX, 2);
3138 }
3139 else if (ctx == AugStore) {
3140 ADDOP(c, ROT_THREE);
3141 }
3142 ADDOP(c, op);
3143 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144}
3145
3146static int
3147compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3148{
3149 int n = 2;
3150 assert(s->kind == Slice_kind);
3151
3152 /* only handles the cases where BUILD_SLICE is emitted */
3153 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003154 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155 }
3156 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003157 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003159
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162 }
3163 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165 }
3166
3167 if (s->v.Slice.step) {
3168 n++;
3169 VISIT(c, expr, s->v.Slice.step);
3170 }
3171 ADDOP_I(c, BUILD_SLICE, n);
3172 return 1;
3173}
3174
3175static int
3176compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3177{
3178 int op = 0, slice_offset = 0, stack_count = 0;
3179
3180 assert(s->v.Slice.step == NULL);
3181 if (s->v.Slice.lower) {
3182 slice_offset++;
3183 stack_count++;
3184 if (ctx != AugStore)
3185 VISIT(c, expr, s->v.Slice.lower);
3186 }
3187 if (s->v.Slice.upper) {
3188 slice_offset += 2;
3189 stack_count++;
3190 if (ctx != AugStore)
3191 VISIT(c, expr, s->v.Slice.upper);
3192 }
3193
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003194 if (ctx == AugLoad) {
3195 switch (stack_count) {
3196 case 0: ADDOP(c, DUP_TOP); break;
3197 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3198 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3199 }
3200 }
3201 else if (ctx == AugStore) {
3202 switch (stack_count) {
3203 case 0: ADDOP(c, ROT_TWO); break;
3204 case 1: ADDOP(c, ROT_THREE); break;
3205 case 2: ADDOP(c, ROT_FOUR); break;
3206 }
3207 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208
3209 switch (ctx) {
3210 case AugLoad: /* fall through to Load */
3211 case Load: op = SLICE; break;
3212 case AugStore:/* fall through to Store */
3213 case Store: op = STORE_SLICE; break;
3214 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003215 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003216 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003217 PyErr_SetString(PyExc_SystemError,
3218 "param invalid in simple slice");
3219 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 }
3221
3222 ADDOP(c, op + slice_offset);
3223 return 1;
3224}
3225
3226static int
3227compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3228 expr_context_ty ctx)
3229{
3230 switch (s->kind) {
3231 case Ellipsis_kind:
3232 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3233 break;
3234 case Slice_kind:
3235 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236 case Index_kind:
3237 VISIT(c, expr, s->v.Index.value);
3238 break;
3239 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003240 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003241 PyErr_SetString(PyExc_SystemError,
3242 "extended slice invalid in nested slice");
3243 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244 }
3245 return 1;
3246}
3247
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248static int
3249compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3250{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003251 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003253 case Index_kind:
3254 kindname = "index";
3255 if (ctx != AugStore) {
3256 VISIT(c, expr, s->v.Index.value);
3257 }
3258 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003260 kindname = "ellipsis";
3261 if (ctx != AugStore) {
3262 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3263 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 break;
3265 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003266 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 if (!s->v.Slice.step)
3268 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003269 if (ctx != AugStore) {
3270 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271 return 0;
3272 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003273 break;
3274 case ExtSlice_kind:
3275 kindname = "extended slice";
3276 if (ctx != AugStore) {
3277 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3278 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003279 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003280 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003281 if (!compiler_visit_nested_slice(c, sub, ctx))
3282 return 0;
3283 }
3284 ADDOP_I(c, BUILD_TUPLE, n);
3285 }
3286 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003287 default:
3288 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003289 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003290 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003291 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003292 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293}
3294
Neal Norwitzf733a012006-10-29 18:30:10 +00003295
3296/* End of the compiler section, beginning of the assembler section */
3297
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298/* do depth-first search of basic block graph, starting with block.
3299 post records the block indices in post-order.
3300
3301 XXX must handle implicit jumps from one block to next
3302*/
3303
Neal Norwitzf733a012006-10-29 18:30:10 +00003304struct assembler {
3305 PyObject *a_bytecode; /* string containing bytecode */
3306 int a_offset; /* offset into bytecode */
3307 int a_nblocks; /* number of reachable blocks */
3308 basicblock **a_postorder; /* list of blocks in dfs postorder */
3309 PyObject *a_lnotab; /* string containing lnotab */
3310 int a_lnotab_off; /* offset into lnotab */
3311 int a_lineno; /* last lineno of emitted instruction */
3312 int a_lineno_off; /* bytecode offset of last lineno */
3313};
3314
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315static void
3316dfs(struct compiler *c, basicblock *b, struct assembler *a)
3317{
3318 int i;
3319 struct instr *instr = NULL;
3320
3321 if (b->b_seen)
3322 return;
3323 b->b_seen = 1;
3324 if (b->b_next != NULL)
3325 dfs(c, b->b_next, a);
3326 for (i = 0; i < b->b_iused; i++) {
3327 instr = &b->b_instr[i];
3328 if (instr->i_jrel || instr->i_jabs)
3329 dfs(c, instr->i_target, a);
3330 }
3331 a->a_postorder[a->a_nblocks++] = b;
3332}
3333
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003334static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3336{
3337 int i;
3338 struct instr *instr;
3339 if (b->b_seen || b->b_startdepth >= depth)
3340 return maxdepth;
3341 b->b_seen = 1;
3342 b->b_startdepth = depth;
3343 for (i = 0; i < b->b_iused; i++) {
3344 instr = &b->b_instr[i];
3345 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3346 if (depth > maxdepth)
3347 maxdepth = depth;
3348 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3349 if (instr->i_jrel || instr->i_jabs) {
3350 maxdepth = stackdepth_walk(c, instr->i_target,
3351 depth, maxdepth);
3352 if (instr->i_opcode == JUMP_ABSOLUTE ||
3353 instr->i_opcode == JUMP_FORWARD) {
3354 goto out; /* remaining code is dead */
3355 }
3356 }
3357 }
3358 if (b->b_next)
3359 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3360out:
3361 b->b_seen = 0;
3362 return maxdepth;
3363}
3364
3365/* Find the flow path that needs the largest stack. We assume that
3366 * cycles in the flow graph have no net effect on the stack depth.
3367 */
3368static int
3369stackdepth(struct compiler *c)
3370{
3371 basicblock *b, *entryblock;
3372 entryblock = NULL;
3373 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3374 b->b_seen = 0;
3375 b->b_startdepth = INT_MIN;
3376 entryblock = b;
3377 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003378 if (!entryblock)
3379 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380 return stackdepth_walk(c, entryblock, 0, 0);
3381}
3382
3383static int
3384assemble_init(struct assembler *a, int nblocks, int firstlineno)
3385{
3386 memset(a, 0, sizeof(struct assembler));
3387 a->a_lineno = firstlineno;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003388 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003389 if (!a->a_bytecode)
3390 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003391 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392 if (!a->a_lnotab)
3393 return 0;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003394 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3395 PyErr_NoMemory();
3396 return 0;
3397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003399 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003400 if (!a->a_postorder) {
3401 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003402 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003403 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003404 return 1;
3405}
3406
3407static void
3408assemble_free(struct assembler *a)
3409{
3410 Py_XDECREF(a->a_bytecode);
3411 Py_XDECREF(a->a_lnotab);
3412 if (a->a_postorder)
3413 PyObject_Free(a->a_postorder);
3414}
3415
3416/* Return the size of a basic block in bytes. */
3417
3418static int
3419instrsize(struct instr *instr)
3420{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003421 if (!instr->i_hasarg)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003422 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003423 if (instr->i_oparg > 0xffff)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003424 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3425 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003426}
3427
3428static int
3429blocksize(basicblock *b)
3430{
3431 int i;
3432 int size = 0;
3433
3434 for (i = 0; i < b->b_iused; i++)
3435 size += instrsize(&b->b_instr[i]);
3436 return size;
3437}
3438
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003439/* Appends a pair to the end of the line number table, a_lnotab, representing
3440 the instruction's bytecode offset and line number. See
3441 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003442
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003443static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003445{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446 int d_bytecode, d_lineno;
3447 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003448 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003449
3450 d_bytecode = a->a_offset - a->a_lineno_off;
3451 d_lineno = i->i_lineno - a->a_lineno;
3452
3453 assert(d_bytecode >= 0);
3454 assert(d_lineno >= 0);
3455
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003456 if(d_bytecode == 0 && d_lineno == 0)
3457 return 1;
3458
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003460 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003462 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003463 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003464 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003465 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003466 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003468 else {
3469 PyErr_NoMemory();
3470 return 0;
3471 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003472 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003474 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003475 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003476 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003477 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478 *lnotab++ = 255;
3479 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003480 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481 d_bytecode -= ncodes * 255;
3482 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003483 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484 assert(d_bytecode <= 255);
3485 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003486 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003487 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003488 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003490 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003492 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003494 else {
3495 PyErr_NoMemory();
3496 return 0;
3497 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003498 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003500 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003501 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003502 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003504 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003506 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003508 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510 d_lineno -= ncodes * 255;
3511 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003512 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003513
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003514 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515 if (a->a_lnotab_off + 2 >= len) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003516 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003517 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003518 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003519 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003520 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003521
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522 a->a_lnotab_off += 2;
3523 if (d_bytecode) {
3524 *lnotab++ = d_bytecode;
3525 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003526 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003527 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 *lnotab++ = 0;
3529 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003530 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531 a->a_lineno = i->i_lineno;
3532 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003533 return 1;
3534}
3535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536/* assemble_emit()
3537 Extend the bytecode with a new instruction.
3538 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003539*/
3540
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003541static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003543{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003544 int size, arg = 0, ext = 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003545 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 char *code;
3547
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003548 size = instrsize(i);
3549 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003551 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003552 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003554 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 if (a->a_offset + size >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003556 if (len > PY_SSIZE_T_MAX / 2)
3557 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003558 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003559 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003560 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003561 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003563 if (size == 6) {
3564 assert(i->i_hasarg);
3565 *code++ = (char)EXTENDED_ARG;
3566 *code++ = ext & 0xff;
3567 *code++ = ext >> 8;
3568 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003569 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003571 if (i->i_hasarg) {
3572 assert(size == 3 || size == 6);
3573 *code++ = arg & 0xff;
3574 *code++ = arg >> 8;
3575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003577}
3578
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003579static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003581{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003583 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003584 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003585
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 /* Compute the size of each block and fixup jump args.
3587 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003588start:
3589 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003591 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 bsize = blocksize(b);
3593 b->b_offset = totsize;
3594 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003595 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003596 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3598 bsize = b->b_offset;
3599 for (i = 0; i < b->b_iused; i++) {
3600 struct instr *instr = &b->b_instr[i];
3601 /* Relative jumps are computed relative to
3602 the instruction pointer after fetching
3603 the jump instruction.
3604 */
3605 bsize += instrsize(instr);
3606 if (instr->i_jabs)
3607 instr->i_oparg = instr->i_target->b_offset;
3608 else if (instr->i_jrel) {
3609 int delta = instr->i_target->b_offset - bsize;
3610 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003611 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003612 else
3613 continue;
3614 if (instr->i_oparg > 0xffff)
3615 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003616 }
3617 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003618
3619 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003620 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003621 with a better solution.
3622
3623 In the meantime, should the goto be dropped in favor
3624 of a loop?
3625
3626 The issue is that in the first loop blocksize() is called
3627 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003628 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003629 i_oparg is calculated in the second loop above.
3630
3631 So we loop until we stop seeing new EXTENDED_ARGs.
3632 The only EXTENDED_ARGs that could be popping up are
3633 ones in jump instructions. So this should converge
3634 fairly quickly.
3635 */
3636 if (last_extended_arg_count != extended_arg_count) {
3637 last_extended_arg_count = extended_arg_count;
3638 goto start;
3639 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003640}
3641
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003642static PyObject *
3643dict_keys_inorder(PyObject *dict, int offset)
3644{
3645 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003646 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003647
3648 tuple = PyTuple_New(size);
3649 if (tuple == NULL)
3650 return NULL;
3651 while (PyDict_Next(dict, &pos, &k, &v)) {
3652 i = PyInt_AS_LONG(v);
Benjamin Petersonda9327f2009-01-31 23:43:25 +00003653 /* The keys of the dictionary are tuples. (see compiler_add_o)
3654 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003655 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003656 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003657 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003658 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003659 PyTuple_SET_ITEM(tuple, i - offset, k);
3660 }
3661 return tuple;
3662}
3663
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003664static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003665compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003666{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667 PySTEntryObject *ste = c->u->u_ste;
3668 int flags = 0, n;
3669 if (ste->ste_type != ModuleBlock)
3670 flags |= CO_NEWLOCALS;
3671 if (ste->ste_type == FunctionBlock) {
3672 if (!ste->ste_unoptimized)
3673 flags |= CO_OPTIMIZED;
3674 if (ste->ste_nested)
3675 flags |= CO_NESTED;
3676 if (ste->ste_generator)
3677 flags |= CO_GENERATOR;
Benjamin Peterson12554cb2009-01-31 23:54:38 +00003678 if (ste->ste_varargs)
3679 flags |= CO_VARARGS;
3680 if (ste->ste_varkeywords)
3681 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003682 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003683
3684 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003685 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003686
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687 n = PyDict_Size(c->u->u_freevars);
3688 if (n < 0)
3689 return -1;
3690 if (n == 0) {
3691 n = PyDict_Size(c->u->u_cellvars);
3692 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003693 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694 if (n == 0) {
3695 flags |= CO_NOFREE;
3696 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003697 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003698
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003699 return flags;
3700}
3701
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702static PyCodeObject *
3703makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003704{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003705 PyObject *tmp;
3706 PyCodeObject *co = NULL;
3707 PyObject *consts = NULL;
3708 PyObject *names = NULL;
3709 PyObject *varnames = NULL;
3710 PyObject *filename = NULL;
3711 PyObject *name = NULL;
3712 PyObject *freevars = NULL;
3713 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003714 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003715 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003716
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717 tmp = dict_keys_inorder(c->u->u_consts, 0);
3718 if (!tmp)
3719 goto error;
3720 consts = PySequence_List(tmp); /* optimize_code requires a list */
3721 Py_DECREF(tmp);
3722
3723 names = dict_keys_inorder(c->u->u_names, 0);
3724 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3725 if (!consts || !names || !varnames)
3726 goto error;
3727
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003728 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3729 if (!cellvars)
3730 goto error;
3731 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3732 if (!freevars)
3733 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003734 filename = PyString_FromString(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735 if (!filename)
3736 goto error;
3737
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003738 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 flags = compute_code_flags(c);
3740 if (flags < 0)
3741 goto error;
3742
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003743 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744 if (!bytecode)
3745 goto error;
3746
3747 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3748 if (!tmp)
3749 goto error;
3750 Py_DECREF(consts);
3751 consts = tmp;
3752
3753 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3754 bytecode, consts, names, varnames,
3755 freevars, cellvars,
3756 filename, c->u->u_name,
3757 c->u->u_firstlineno,
3758 a->a_lnotab);
3759 error:
3760 Py_XDECREF(consts);
3761 Py_XDECREF(names);
3762 Py_XDECREF(varnames);
3763 Py_XDECREF(filename);
3764 Py_XDECREF(name);
3765 Py_XDECREF(freevars);
3766 Py_XDECREF(cellvars);
3767 Py_XDECREF(bytecode);
3768 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003769}
3770
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003771
3772/* For debugging purposes only */
3773#if 0
3774static void
3775dump_instr(const struct instr *i)
3776{
3777 const char *jrel = i->i_jrel ? "jrel " : "";
3778 const char *jabs = i->i_jabs ? "jabs " : "";
3779 char arg[128];
3780
3781 *arg = '\0';
3782 if (i->i_hasarg)
3783 sprintf(arg, "arg: %d ", i->i_oparg);
3784
3785 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3786 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3787}
3788
3789static void
3790dump_basicblock(const basicblock *b)
3791{
3792 const char *seen = b->b_seen ? "seen " : "";
3793 const char *b_return = b->b_return ? "return " : "";
3794 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3795 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3796 if (b->b_instr) {
3797 int i;
3798 for (i = 0; i < b->b_iused; i++) {
3799 fprintf(stderr, " [%02d] ", i);
3800 dump_instr(b->b_instr + i);
3801 }
3802 }
3803}
3804#endif
3805
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806static PyCodeObject *
3807assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003808{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809 basicblock *b, *entryblock;
3810 struct assembler a;
3811 int i, j, nblocks;
3812 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003813
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 /* Make sure every block that falls off the end returns None.
3815 XXX NEXT_BLOCK() isn't quite right, because if the last
3816 block ends with a jump or return b_next shouldn't set.
3817 */
3818 if (!c->u->u_curblock->b_return) {
3819 NEXT_BLOCK(c);
3820 if (addNone)
3821 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3822 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003823 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003824
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 nblocks = 0;
3826 entryblock = NULL;
3827 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3828 nblocks++;
3829 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003830 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003831
Neal Norwitzed657552006-07-10 00:04:44 +00003832 /* Set firstlineno if it wasn't explicitly set. */
3833 if (!c->u->u_firstlineno) {
3834 if (entryblock && entryblock->b_instr)
3835 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3836 else
3837 c->u->u_firstlineno = 1;
3838 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003839 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3840 goto error;
3841 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003842
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003844 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846 /* Emit code in reverse postorder from dfs. */
3847 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003848 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849 for (j = 0; j < b->b_iused; j++)
3850 if (!assemble_emit(&a, &b->b_instr[j]))
3851 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003852 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003853
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003854 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003856 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 co = makecode(c, &a);
3860 error:
3861 assemble_free(&a);
3862 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003863}