blob: 8c8530670b6e80ddd70d822a65dca73e0343d677 [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
Guido van Rossumc2e20742006-02-27 22:32:47 +0000538/* Allocate a new "anonymous" local variable.
539 Used by list comprehensions and with statements.
540*/
541
542static PyObject *
543compiler_new_tmpname(struct compiler *c)
544{
545 char tmpname[256];
546 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000547 return PyString_FromString(tmpname);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000548}
549
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550/* Allocate a new block and return a pointer to it.
551 Returns NULL on error.
552*/
553
554static basicblock *
555compiler_new_block(struct compiler *c)
556{
557 basicblock *b;
558 struct compiler_unit *u;
559
560 u = c->u;
561 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000562 if (b == NULL) {
563 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000565 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000567 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000568 b->b_list = u->u_blocks;
569 u->u_blocks = b;
570 return b;
571}
572
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573static basicblock *
574compiler_use_new_block(struct compiler *c)
575{
576 basicblock *block = compiler_new_block(c);
577 if (block == NULL)
578 return NULL;
579 c->u->u_curblock = block;
580 return block;
581}
582
583static basicblock *
584compiler_next_block(struct compiler *c)
585{
586 basicblock *block = compiler_new_block(c);
587 if (block == NULL)
588 return NULL;
589 c->u->u_curblock->b_next = block;
590 c->u->u_curblock = block;
591 return block;
592}
593
594static basicblock *
595compiler_use_next_block(struct compiler *c, basicblock *block)
596{
597 assert(block != NULL);
598 c->u->u_curblock->b_next = block;
599 c->u->u_curblock = block;
600 return block;
601}
602
603/* Returns the offset of the next instruction in the current block's
604 b_instr array. Resizes the b_instr as necessary.
605 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000606*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
608static int
609compiler_next_instr(struct compiler *c, basicblock *b)
610{
611 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000612 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000613 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000614 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615 if (b->b_instr == NULL) {
616 PyErr_NoMemory();
617 return -1;
618 }
619 b->b_ialloc = DEFAULT_BLOCK_SIZE;
620 memset((char *)b->b_instr, 0,
621 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000624 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 size_t oldsize, newsize;
626 oldsize = b->b_ialloc * sizeof(struct instr);
627 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000628
629 if (oldsize > (PY_SIZE_MAX >> 1)) {
630 PyErr_NoMemory();
631 return -1;
632 }
633
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634 if (newsize == 0) {
635 PyErr_NoMemory();
636 return -1;
637 }
638 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000639 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000640 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000641 if (tmp == NULL) {
642 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000644 }
645 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
647 }
648 return b->b_iused++;
649}
650
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000651/* Set the i_lineno member of the instruction at offset off if the
652 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000653 already been set. If it has been set, the call has no effect.
654
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000655 The line number is reset in the following cases:
656 - when entering a new scope
657 - on each statement
658 - on each expression that start a new line
659 - before the "except" clause
660 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000661*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663static void
664compiler_set_lineno(struct compiler *c, int off)
665{
666 basicblock *b;
667 if (c->u->u_lineno_set)
668 return;
669 c->u->u_lineno_set = true;
670 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000671 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672}
673
674static int
675opcode_stack_effect(int opcode, int oparg)
676{
677 switch (opcode) {
678 case POP_TOP:
679 return -1;
680 case ROT_TWO:
681 case ROT_THREE:
682 return 0;
683 case DUP_TOP:
684 return 1;
685 case ROT_FOUR:
686 return 0;
687
688 case UNARY_POSITIVE:
689 case UNARY_NEGATIVE:
690 case UNARY_NOT:
691 case UNARY_CONVERT:
692 case UNARY_INVERT:
693 return 0;
694
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000695 case LIST_APPEND:
Antoine Pitroud0c35152008-12-17 00:38:28 +0000696 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000698 case BINARY_POWER:
699 case BINARY_MULTIPLY:
700 case BINARY_DIVIDE:
701 case BINARY_MODULO:
702 case BINARY_ADD:
703 case BINARY_SUBTRACT:
704 case BINARY_SUBSCR:
705 case BINARY_FLOOR_DIVIDE:
706 case BINARY_TRUE_DIVIDE:
707 return -1;
708 case INPLACE_FLOOR_DIVIDE:
709 case INPLACE_TRUE_DIVIDE:
710 return -1;
711
712 case SLICE+0:
713 return 1;
714 case SLICE+1:
715 return 0;
716 case SLICE+2:
717 return 0;
718 case SLICE+3:
719 return -1;
720
721 case STORE_SLICE+0:
722 return -2;
723 case STORE_SLICE+1:
724 return -3;
725 case STORE_SLICE+2:
726 return -3;
727 case STORE_SLICE+3:
728 return -4;
729
730 case DELETE_SLICE+0:
731 return -1;
732 case DELETE_SLICE+1:
733 return -2;
734 case DELETE_SLICE+2:
735 return -2;
736 case DELETE_SLICE+3:
737 return -3;
738
739 case INPLACE_ADD:
740 case INPLACE_SUBTRACT:
741 case INPLACE_MULTIPLY:
742 case INPLACE_DIVIDE:
743 case INPLACE_MODULO:
744 return -1;
745 case STORE_SUBSCR:
746 return -3;
Raymond Hettingereffde122007-12-18 18:26:18 +0000747 case STORE_MAP:
748 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749 case DELETE_SUBSCR:
750 return -2;
751
752 case BINARY_LSHIFT:
753 case BINARY_RSHIFT:
754 case BINARY_AND:
755 case BINARY_XOR:
756 case BINARY_OR:
757 return -1;
758 case INPLACE_POWER:
759 return -1;
760 case GET_ITER:
761 return 0;
762
763 case PRINT_EXPR:
764 return -1;
765 case PRINT_ITEM:
766 return -1;
767 case PRINT_NEWLINE:
768 return 0;
769 case PRINT_ITEM_TO:
770 return -2;
771 case PRINT_NEWLINE_TO:
772 return -1;
773 case INPLACE_LSHIFT:
774 case INPLACE_RSHIFT:
775 case INPLACE_AND:
776 case INPLACE_XOR:
777 case INPLACE_OR:
778 return -1;
779 case BREAK_LOOP:
780 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000781 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000782 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783 case LOAD_LOCALS:
784 return 1;
785 case RETURN_VALUE:
786 return -1;
787 case IMPORT_STAR:
788 return -1;
789 case EXEC_STMT:
790 return -3;
791 case YIELD_VALUE:
792 return 0;
793
794 case POP_BLOCK:
795 return 0;
796 case END_FINALLY:
797 return -1; /* or -2 or -3 if exception occurred */
798 case BUILD_CLASS:
799 return -2;
800
801 case STORE_NAME:
802 return -1;
803 case DELETE_NAME:
804 return 0;
805 case UNPACK_SEQUENCE:
806 return oparg-1;
807 case FOR_ITER:
808 return 1;
809
810 case STORE_ATTR:
811 return -2;
812 case DELETE_ATTR:
813 return -1;
814 case STORE_GLOBAL:
815 return -1;
816 case DELETE_GLOBAL:
817 return 0;
818 case DUP_TOPX:
819 return oparg;
820 case LOAD_CONST:
821 return 1;
822 case LOAD_NAME:
823 return 1;
824 case BUILD_TUPLE:
825 case BUILD_LIST:
826 return 1-oparg;
827 case BUILD_MAP:
828 return 1;
829 case LOAD_ATTR:
830 return 0;
831 case COMPARE_OP:
832 return -1;
833 case IMPORT_NAME:
834 return 0;
835 case IMPORT_FROM:
836 return 1;
837
838 case JUMP_FORWARD:
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000839 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
840 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841 case JUMP_ABSOLUTE:
842 return 0;
843
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000844 case POP_JUMP_IF_FALSE:
845 case POP_JUMP_IF_TRUE:
846 return -1;
847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848 case LOAD_GLOBAL:
849 return 1;
850
851 case CONTINUE_LOOP:
852 return 0;
853 case SETUP_LOOP:
854 return 0;
855 case SETUP_EXCEPT:
856 case SETUP_FINALLY:
857 return 3; /* actually pushed by an exception */
858
859 case LOAD_FAST:
860 return 1;
861 case STORE_FAST:
862 return -1;
863 case DELETE_FAST:
864 return 0;
865
866 case RAISE_VARARGS:
867 return -oparg;
868#define NARGS(o) (((o) % 256) + 2*((o) / 256))
869 case CALL_FUNCTION:
870 return -NARGS(oparg);
871 case CALL_FUNCTION_VAR:
872 case CALL_FUNCTION_KW:
873 return -NARGS(oparg)-1;
874 case CALL_FUNCTION_VAR_KW:
875 return -NARGS(oparg)-2;
876#undef NARGS
877 case MAKE_FUNCTION:
878 return -oparg;
879 case BUILD_SLICE:
880 if (oparg == 3)
881 return -2;
882 else
883 return -1;
884
885 case MAKE_CLOSURE:
886 return -oparg;
887 case LOAD_CLOSURE:
888 return 1;
889 case LOAD_DEREF:
890 return 1;
891 case STORE_DEREF:
892 return -1;
893 default:
894 fprintf(stderr, "opcode = %d\n", opcode);
895 Py_FatalError("opcode_stack_effect()");
896
897 }
898 return 0; /* not reachable */
899}
900
901/* Add an opcode with no argument.
902 Returns 0 on failure, 1 on success.
903*/
904
905static int
906compiler_addop(struct compiler *c, int opcode)
907{
908 basicblock *b;
909 struct instr *i;
910 int off;
911 off = compiler_next_instr(c, c->u->u_curblock);
912 if (off < 0)
913 return 0;
914 b = c->u->u_curblock;
915 i = &b->b_instr[off];
916 i->i_opcode = opcode;
917 i->i_hasarg = 0;
918 if (opcode == RETURN_VALUE)
919 b->b_return = 1;
920 compiler_set_lineno(c, off);
921 return 1;
922}
923
924static int
925compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
926{
927 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000928 Py_ssize_t arg;
Mark Dickinson105be772008-01-31 22:17:37 +0000929 unsigned char *p, *q;
930 Py_complex z;
931 double d;
932 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000934 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000935 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
936 if (PyFloat_Check(o)) {
Mark Dickinson105be772008-01-31 22:17:37 +0000937 d = PyFloat_AS_DOUBLE(o);
938 p = (unsigned char*) &d;
939 /* all we need is to make the tuple different in either the 0.0
940 * or -0.0 case from all others, just to avoid the "coercion".
941 */
942 if (*p==0 && p[sizeof(double)-1]==0)
943 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
944 else
945 t = PyTuple_Pack(2, o, o->ob_type);
946 }
947 else if (PyComplex_Check(o)) {
948 /* complex case is even messier: we need to make complex(x,
949 0.) different from complex(x, -0.) and complex(0., y)
950 different from complex(-0., y), for any x and y. In
951 particular, all four complex zeros should be
952 distinguished.*/
953 z = PyComplex_AsCComplex(o);
954 p = (unsigned char*) &(z.real);
955 q = (unsigned char*) &(z.imag);
956 /* all that matters here is that on IEEE platforms
957 real_part_zero will be true if z.real == 0., and false if
958 z.real == -0. In fact, real_part_zero will also be true
959 for some other rarely occurring nonzero floats, but this
960 doesn't matter. Similar comments apply to
961 imag_part_zero. */
962 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
963 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
964 if (real_part_zero && imag_part_zero) {
965 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
966 }
967 else if (real_part_zero && !imag_part_zero) {
968 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
969 }
970 else if (!real_part_zero && imag_part_zero) {
971 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
972 }
973 else {
974 t = PyTuple_Pack(2, o, o->ob_type);
975 }
976 }
977 else {
978 t = PyTuple_Pack(2, o, o->ob_type);
Alex Martellid8672aa2007-08-22 21:14:17 +0000979 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 if (t == NULL)
Mark Dickinson105be772008-01-31 22:17:37 +0000981 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000982
983 v = PyDict_GetItem(dict, t);
984 if (!v) {
985 arg = PyDict_Size(dict);
986 v = PyInt_FromLong(arg);
987 if (!v) {
988 Py_DECREF(t);
989 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000990 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991 if (PyDict_SetItem(dict, t, v) < 0) {
992 Py_DECREF(t);
993 Py_DECREF(v);
994 return -1;
995 }
996 Py_DECREF(v);
997 }
998 else
999 arg = PyInt_AsLong(v);
1000 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001001 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001002}
1003
1004static int
1005compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1006 PyObject *o)
1007{
1008 int arg = compiler_add_o(c, dict, o);
1009 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001010 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011 return compiler_addop_i(c, opcode, arg);
1012}
1013
1014static int
1015compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001016 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017{
1018 int arg;
1019 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1020 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001021 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022 arg = compiler_add_o(c, dict, mangled);
1023 Py_DECREF(mangled);
1024 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001025 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026 return compiler_addop_i(c, opcode, arg);
1027}
1028
1029/* Add an opcode with an integer argument.
1030 Returns 0 on failure, 1 on success.
1031*/
1032
1033static int
1034compiler_addop_i(struct compiler *c, int opcode, int oparg)
1035{
1036 struct instr *i;
1037 int off;
1038 off = compiler_next_instr(c, c->u->u_curblock);
1039 if (off < 0)
1040 return 0;
1041 i = &c->u->u_curblock->b_instr[off];
1042 i->i_opcode = opcode;
1043 i->i_oparg = oparg;
1044 i->i_hasarg = 1;
1045 compiler_set_lineno(c, off);
1046 return 1;
1047}
1048
1049static int
1050compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1051{
1052 struct instr *i;
1053 int off;
1054
1055 assert(b != NULL);
1056 off = compiler_next_instr(c, c->u->u_curblock);
1057 if (off < 0)
1058 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059 i = &c->u->u_curblock->b_instr[off];
1060 i->i_opcode = opcode;
1061 i->i_target = b;
1062 i->i_hasarg = 1;
1063 if (absolute)
1064 i->i_jabs = 1;
1065 else
1066 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001067 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068 return 1;
1069}
1070
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001071/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1072 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073 it as the current block. NEXT_BLOCK() also creates an implicit jump
1074 from the current block to the new block.
1075*/
1076
Neal Norwitzf733a012006-10-29 18:30:10 +00001077/* The returns inside these macros make it impossible to decref objects
1078 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079*/
1080
1081
1082#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001083 if (compiler_use_new_block((C)) == NULL) \
1084 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085}
1086
1087#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001088 if (compiler_next_block((C)) == NULL) \
1089 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001090}
1091
1092#define ADDOP(C, OP) { \
1093 if (!compiler_addop((C), (OP))) \
1094 return 0; \
1095}
1096
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001097#define ADDOP_IN_SCOPE(C, OP) { \
1098 if (!compiler_addop((C), (OP))) { \
1099 compiler_exit_scope(c); \
1100 return 0; \
1101 } \
1102}
1103
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104#define ADDOP_O(C, OP, O, TYPE) { \
1105 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1106 return 0; \
1107}
1108
1109#define ADDOP_NAME(C, OP, O, TYPE) { \
1110 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1111 return 0; \
1112}
1113
1114#define ADDOP_I(C, OP, O) { \
1115 if (!compiler_addop_i((C), (OP), (O))) \
1116 return 0; \
1117}
1118
1119#define ADDOP_JABS(C, OP, O) { \
1120 if (!compiler_addop_j((C), (OP), (O), 1)) \
1121 return 0; \
1122}
1123
1124#define ADDOP_JREL(C, OP, O) { \
1125 if (!compiler_addop_j((C), (OP), (O), 0)) \
1126 return 0; \
1127}
1128
1129/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1130 the ASDL name to synthesize the name of the C type and the visit function.
1131*/
1132
1133#define VISIT(C, TYPE, V) {\
1134 if (!compiler_visit_ ## TYPE((C), (V))) \
1135 return 0; \
1136}
1137
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001138#define VISIT_IN_SCOPE(C, TYPE, V) {\
1139 if (!compiler_visit_ ## TYPE((C), (V))) { \
1140 compiler_exit_scope(c); \
1141 return 0; \
1142 } \
1143}
1144
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145#define VISIT_SLICE(C, V, CTX) {\
1146 if (!compiler_visit_slice((C), (V), (CTX))) \
1147 return 0; \
1148}
1149
1150#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001151 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +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 return 0; \
1157 } \
1158}
1159
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001160#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001161 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001162 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001163 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001164 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001165 if (!compiler_visit_ ## TYPE((C), elt)) { \
1166 compiler_exit_scope(c); \
1167 return 0; \
1168 } \
1169 } \
1170}
1171
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172static int
1173compiler_isdocstring(stmt_ty s)
1174{
1175 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001176 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 return s->v.Expr.value->kind == Str_kind;
1178}
1179
1180/* Compile a sequence of statements, checking for a docstring. */
1181
1182static int
1183compiler_body(struct compiler *c, asdl_seq *stmts)
1184{
1185 int i = 0;
1186 stmt_ty st;
1187
1188 if (!asdl_seq_LEN(stmts))
1189 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001190 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001191 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1192 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 i = 1;
1194 VISIT(c, expr, st->v.Expr.value);
1195 if (!compiler_nameop(c, __doc__, Store))
1196 return 0;
1197 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001198 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001199 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 return 1;
1201}
1202
1203static PyCodeObject *
1204compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001205{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001206 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001207 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 static PyObject *module;
1209 if (!module) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001210 module = PyString_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 if (!module)
1212 return NULL;
1213 }
Neal Norwitzed657552006-07-10 00:04:44 +00001214 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1215 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001216 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217 switch (mod->kind) {
1218 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001219 if (!compiler_body(c, mod->v.Module.body)) {
1220 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001222 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223 break;
1224 case Interactive_kind:
1225 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001226 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001227 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228 break;
1229 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001230 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001231 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001232 break;
1233 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001234 PyErr_SetString(PyExc_SystemError,
1235 "suite should not be possible");
1236 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001237 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001238 PyErr_Format(PyExc_SystemError,
1239 "module kind %d should not be possible",
1240 mod->kind);
1241 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243 co = assemble(c, addNone);
1244 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001245 return co;
1246}
1247
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001248/* The test for LOCAL must come before the test for FREE in order to
1249 handle classes where name is both local and free. The local var is
1250 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001251*/
1252
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253static int
1254get_ref_type(struct compiler *c, PyObject *name)
1255{
1256 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001257 if (scope == 0) {
1258 char buf[350];
1259 PyOS_snprintf(buf, sizeof(buf),
1260 "unknown scope for %.100s in %.100s(%s) in %s\n"
Amaury Forgeot d'Arc59ce0422009-01-17 20:18:59 +00001261 "symbols: %s\nlocals: %s\nglobals: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001262 PyString_AS_STRING(name),
1263 PyString_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001264 PyObject_REPR(c->u->u_ste->ste_id),
1265 c->c_filename,
1266 PyObject_REPR(c->u->u_ste->ste_symbols),
1267 PyObject_REPR(c->u->u_varnames),
1268 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001270 Py_FatalError(buf);
1271 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001272
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001273 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274}
1275
1276static int
1277compiler_lookup_arg(PyObject *dict, PyObject *name)
1278{
1279 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001280 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001282 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001284 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001286 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287 return PyInt_AS_LONG(v);
1288}
1289
1290static int
1291compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1292{
1293 int i, free = PyCode_GetNumFree(co);
1294 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001295 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1296 ADDOP_I(c, MAKE_FUNCTION, args);
1297 return 1;
1298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299 for (i = 0; i < free; ++i) {
1300 /* Bypass com_addop_varname because it will generate
1301 LOAD_DEREF but LOAD_CLOSURE is needed.
1302 */
1303 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1304 int arg, reftype;
1305
1306 /* Special case: If a class contains a method with a
1307 free variable that has the same name as a method,
1308 the name will be considered free *and* local in the
1309 class. It should be handled by the closure, as
1310 well as by the normal name loookup logic.
1311 */
1312 reftype = get_ref_type(c, name);
1313 if (reftype == CELL)
1314 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1315 else /* (reftype == FREE) */
1316 arg = compiler_lookup_arg(c->u->u_freevars, name);
1317 if (arg == -1) {
1318 printf("lookup %s in %s %d %d\n"
1319 "freevars of %s: %s\n",
1320 PyObject_REPR(name),
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001321 PyString_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322 reftype, arg,
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001323 PyString_AS_STRING(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324 PyObject_REPR(co->co_freevars));
1325 Py_FatalError("compiler_make_closure()");
1326 }
1327 ADDOP_I(c, LOAD_CLOSURE, arg);
1328 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001329 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001331 ADDOP_I(c, MAKE_CLOSURE, args);
1332 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333}
1334
1335static int
1336compiler_decorators(struct compiler *c, asdl_seq* decos)
1337{
1338 int i;
1339
1340 if (!decos)
1341 return 1;
1342
1343 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001344 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 }
1346 return 1;
1347}
1348
1349static int
1350compiler_arguments(struct compiler *c, arguments_ty args)
1351{
1352 int i;
1353 int n = asdl_seq_LEN(args->args);
1354 /* Correctly handle nested argument lists */
1355 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001356 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 if (arg->kind == Tuple_kind) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001358 PyObject *id = PyString_FromFormat(".%d", i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 if (id == NULL) {
1360 return 0;
1361 }
1362 if (!compiler_nameop(c, id, Load)) {
1363 Py_DECREF(id);
1364 return 0;
1365 }
1366 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001367 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 }
1369 }
1370 return 1;
1371}
1372
1373static int
1374compiler_function(struct compiler *c, stmt_ty s)
1375{
1376 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001377 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378 arguments_ty args = s->v.FunctionDef.args;
Christian Heimes5224d282008-02-23 15:01:05 +00001379 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001380 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381 int i, n, docstring;
1382
1383 assert(s->kind == FunctionDef_kind);
1384
1385 if (!compiler_decorators(c, decos))
1386 return 0;
1387 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001388 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1390 s->lineno))
1391 return 0;
1392
Anthony Baxter7b782b62006-04-11 12:01:56 +00001393 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001394 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001395 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001396 first_const = st->v.Expr.value->v.Str.s;
1397 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001398 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001399 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001400 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001402 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001403 compiler_arguments(c, args);
1404
1405 c->u->u_argcount = asdl_seq_LEN(args->args);
1406 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001407 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001409 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1410 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411 }
1412 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001413 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414 if (co == NULL)
1415 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001417 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001418 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419
1420 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1421 ADDOP_I(c, CALL_FUNCTION, 1);
1422 }
1423
1424 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1425}
1426
1427static int
1428compiler_class(struct compiler *c, stmt_ty s)
1429{
Christian Heimes5224d282008-02-23 15:01:05 +00001430 int n, i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001432 PyObject *str;
Christian Heimes5224d282008-02-23 15:01:05 +00001433 asdl_seq* decos = s->v.ClassDef.decorator_list;
1434
1435 if (!compiler_decorators(c, decos))
1436 return 0;
1437
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438 /* push class name on stack, needed by BUILD_CLASS */
1439 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1440 /* push the tuple of base classes on the stack */
1441 n = asdl_seq_LEN(s->v.ClassDef.bases);
1442 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001443 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444 ADDOP_I(c, BUILD_TUPLE, n);
1445 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1446 s->lineno))
1447 return 0;
Amaury Forgeot d'Arc69b747b2008-03-28 20:30:50 +00001448 Py_XDECREF(c->u->u_private);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001449 c->u->u_private = s->v.ClassDef.name;
1450 Py_INCREF(c->u->u_private);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001451 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452 if (!str || !compiler_nameop(c, str, Load)) {
1453 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001454 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001456 }
1457
1458 Py_DECREF(str);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001459 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460 if (!str || !compiler_nameop(c, str, Store)) {
1461 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001462 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001464 }
1465 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001467 if (!compiler_body(c, s->v.ClassDef.body)) {
1468 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001470 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001472 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1473 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001475 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 if (co == NULL)
1477 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001479 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001480 Py_DECREF(co);
1481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482 ADDOP_I(c, CALL_FUNCTION, 0);
1483 ADDOP(c, BUILD_CLASS);
Christian Heimes5224d282008-02-23 15:01:05 +00001484 /* apply decorators */
1485 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1486 ADDOP_I(c, CALL_FUNCTION, 1);
1487 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1489 return 0;
1490 return 1;
1491}
1492
1493static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001494compiler_ifexp(struct compiler *c, expr_ty e)
1495{
1496 basicblock *end, *next;
1497
1498 assert(e->kind == IfExp_kind);
1499 end = compiler_new_block(c);
1500 if (end == NULL)
1501 return 0;
1502 next = compiler_new_block(c);
1503 if (next == NULL)
1504 return 0;
1505 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001506 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001507 VISIT(c, expr, e->v.IfExp.body);
1508 ADDOP_JREL(c, JUMP_FORWARD, end);
1509 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001510 VISIT(c, expr, e->v.IfExp.orelse);
1511 compiler_use_next_block(c, end);
1512 return 1;
1513}
1514
1515static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516compiler_lambda(struct compiler *c, expr_ty e)
1517{
1518 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001519 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520 arguments_ty args = e->v.Lambda.args;
1521 assert(e->kind == Lambda_kind);
1522
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001523 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001524 name = PyString_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001525 if (!name)
1526 return 0;
1527 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528
1529 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001530 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1532 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001533
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001534 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535 compiler_arguments(c, args);
1536
1537 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001538 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson8d5934b2008-12-27 18:24:11 +00001539 if (c->u->u_ste->ste_generator) {
1540 ADDOP_IN_SCOPE(c, POP_TOP);
1541 }
1542 else {
1543 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1544 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001546 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547 if (co == NULL)
1548 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001549
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001550 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001551 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552
1553 return 1;
1554}
1555
1556static int
1557compiler_print(struct compiler *c, stmt_ty s)
1558{
1559 int i, n;
1560 bool dest;
1561
1562 assert(s->kind == Print_kind);
1563 n = asdl_seq_LEN(s->v.Print.values);
1564 dest = false;
1565 if (s->v.Print.dest) {
1566 VISIT(c, expr, s->v.Print.dest);
1567 dest = true;
1568 }
1569 for (i = 0; i < n; i++) {
1570 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1571 if (dest) {
1572 ADDOP(c, DUP_TOP);
1573 VISIT(c, expr, e);
1574 ADDOP(c, ROT_TWO);
1575 ADDOP(c, PRINT_ITEM_TO);
1576 }
1577 else {
1578 VISIT(c, expr, e);
1579 ADDOP(c, PRINT_ITEM);
1580 }
1581 }
1582 if (s->v.Print.nl) {
1583 if (dest)
1584 ADDOP(c, PRINT_NEWLINE_TO)
1585 else
1586 ADDOP(c, PRINT_NEWLINE)
1587 }
1588 else if (dest)
1589 ADDOP(c, POP_TOP);
1590 return 1;
1591}
1592
1593static int
1594compiler_if(struct compiler *c, stmt_ty s)
1595{
1596 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001597 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001598 assert(s->kind == If_kind);
1599 end = compiler_new_block(c);
1600 if (end == NULL)
1601 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001602
1603 constant = expr_constant(s->v.If.test);
1604 /* constant = 0: "if 0"
1605 * constant = 1: "if 1", "if 2", ...
1606 * constant = -1: rest */
1607 if (constant == 0) {
1608 if (s->v.If.orelse)
1609 VISIT_SEQ(c, stmt, s->v.If.orelse);
1610 } else if (constant == 1) {
1611 VISIT_SEQ(c, stmt, s->v.If.body);
1612 } else {
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001613 if (s->v.If.orelse) {
1614 next = compiler_new_block(c);
1615 if (next == NULL)
1616 return 0;
1617 }
1618 else
1619 next = end;
Georg Brandlddbaa662006-06-04 21:56:52 +00001620 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001621 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Georg Brandlddbaa662006-06-04 21:56:52 +00001622 VISIT_SEQ(c, stmt, s->v.If.body);
1623 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001624 if (s->v.If.orelse) {
1625 compiler_use_next_block(c, next);
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001626 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001627 }
Georg Brandlddbaa662006-06-04 21:56:52 +00001628 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001629 compiler_use_next_block(c, end);
1630 return 1;
1631}
1632
1633static int
1634compiler_for(struct compiler *c, stmt_ty s)
1635{
1636 basicblock *start, *cleanup, *end;
1637
1638 start = compiler_new_block(c);
1639 cleanup = compiler_new_block(c);
1640 end = compiler_new_block(c);
1641 if (start == NULL || end == NULL || cleanup == NULL)
1642 return 0;
1643 ADDOP_JREL(c, SETUP_LOOP, end);
1644 if (!compiler_push_fblock(c, LOOP, start))
1645 return 0;
1646 VISIT(c, expr, s->v.For.iter);
1647 ADDOP(c, GET_ITER);
1648 compiler_use_next_block(c, start);
1649 ADDOP_JREL(c, FOR_ITER, cleanup);
1650 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001651 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1653 compiler_use_next_block(c, cleanup);
1654 ADDOP(c, POP_BLOCK);
1655 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001656 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657 compiler_use_next_block(c, end);
1658 return 1;
1659}
1660
1661static int
1662compiler_while(struct compiler *c, stmt_ty s)
1663{
1664 basicblock *loop, *orelse, *end, *anchor = NULL;
1665 int constant = expr_constant(s->v.While.test);
1666
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001667 if (constant == 0) {
1668 if (s->v.While.orelse)
1669 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670 return 1;
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001671 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001672 loop = compiler_new_block(c);
1673 end = compiler_new_block(c);
1674 if (constant == -1) {
1675 anchor = compiler_new_block(c);
1676 if (anchor == NULL)
1677 return 0;
1678 }
1679 if (loop == NULL || end == NULL)
1680 return 0;
1681 if (s->v.While.orelse) {
1682 orelse = compiler_new_block(c);
1683 if (orelse == NULL)
1684 return 0;
1685 }
1686 else
1687 orelse = NULL;
1688
1689 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001690 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691 if (!compiler_push_fblock(c, LOOP, loop))
1692 return 0;
1693 if (constant == -1) {
1694 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001695 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001697 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1699
1700 /* XXX should the two POP instructions be in a separate block
1701 if there is no else clause ?
1702 */
1703
1704 if (constant == -1) {
1705 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 ADDOP(c, POP_BLOCK);
1707 }
1708 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001709 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001710 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001711 compiler_use_next_block(c, end);
1712
1713 return 1;
1714}
1715
1716static int
1717compiler_continue(struct compiler *c)
1718{
1719 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001720 static const char IN_FINALLY_ERROR_MSG[] =
1721 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722 int i;
1723
1724 if (!c->u->u_nfblocks)
1725 return compiler_error(c, LOOP_ERROR_MSG);
1726 i = c->u->u_nfblocks - 1;
1727 switch (c->u->u_fblock[i].fb_type) {
1728 case LOOP:
1729 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1730 break;
1731 case EXCEPT:
1732 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001733 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1734 /* Prevent continue anywhere under a finally
1735 even if hidden in a sub-try or except. */
1736 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1737 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1738 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001739 if (i == -1)
1740 return compiler_error(c, LOOP_ERROR_MSG);
1741 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1742 break;
1743 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001744 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001745 }
1746
1747 return 1;
1748}
1749
1750/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1751
1752 SETUP_FINALLY L
1753 <code for body>
1754 POP_BLOCK
1755 LOAD_CONST <None>
1756 L: <code for finalbody>
1757 END_FINALLY
1758
1759 The special instructions use the block stack. Each block
1760 stack entry contains the instruction that created it (here
1761 SETUP_FINALLY), the level of the value stack at the time the
1762 block stack entry was created, and a label (here L).
1763
1764 SETUP_FINALLY:
1765 Pushes the current value stack level and the label
1766 onto the block stack.
1767 POP_BLOCK:
1768 Pops en entry from the block stack, and pops the value
1769 stack until its level is the same as indicated on the
1770 block stack. (The label is ignored.)
1771 END_FINALLY:
1772 Pops a variable number of entries from the *value* stack
1773 and re-raises the exception they specify. The number of
1774 entries popped depends on the (pseudo) exception type.
1775
1776 The block stack is unwound when an exception is raised:
1777 when a SETUP_FINALLY entry is found, the exception is pushed
1778 onto the value stack (and the exception condition is cleared),
1779 and the interpreter jumps to the label gotten from the block
1780 stack.
1781*/
1782
1783static int
1784compiler_try_finally(struct compiler *c, stmt_ty s)
1785{
1786 basicblock *body, *end;
1787 body = compiler_new_block(c);
1788 end = compiler_new_block(c);
1789 if (body == NULL || end == NULL)
1790 return 0;
1791
1792 ADDOP_JREL(c, SETUP_FINALLY, end);
1793 compiler_use_next_block(c, body);
1794 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1795 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001796 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 ADDOP(c, POP_BLOCK);
1798 compiler_pop_fblock(c, FINALLY_TRY, body);
1799
1800 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1801 compiler_use_next_block(c, end);
1802 if (!compiler_push_fblock(c, FINALLY_END, end))
1803 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001804 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805 ADDOP(c, END_FINALLY);
1806 compiler_pop_fblock(c, FINALLY_END, end);
1807
1808 return 1;
1809}
1810
1811/*
1812 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1813 (The contents of the value stack is shown in [], with the top
1814 at the right; 'tb' is trace-back info, 'val' the exception's
1815 associated value, and 'exc' the exception.)
1816
1817 Value stack Label Instruction Argument
1818 [] SETUP_EXCEPT L1
1819 [] <code for S>
1820 [] POP_BLOCK
1821 [] JUMP_FORWARD L0
1822
1823 [tb, val, exc] L1: DUP )
1824 [tb, val, exc, exc] <evaluate E1> )
1825 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001826 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 [tb, val, exc] POP
1828 [tb, val] <assign to V1> (or POP if no V1)
1829 [tb] POP
1830 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001831 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001833 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 .............................etc.......................
1835
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001836 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837
1838 [] L0: <next statement>
1839
1840 Of course, parts are not generated if Vi or Ei is not present.
1841*/
1842static int
1843compiler_try_except(struct compiler *c, stmt_ty s)
1844{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001845 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846 int i, n;
1847
1848 body = compiler_new_block(c);
1849 except = compiler_new_block(c);
1850 orelse = compiler_new_block(c);
1851 end = compiler_new_block(c);
1852 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1853 return 0;
1854 ADDOP_JREL(c, SETUP_EXCEPT, except);
1855 compiler_use_next_block(c, body);
1856 if (!compiler_push_fblock(c, EXCEPT, body))
1857 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001858 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 ADDOP(c, POP_BLOCK);
1860 compiler_pop_fblock(c, EXCEPT, body);
1861 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1862 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1863 compiler_use_next_block(c, except);
1864 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001865 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866 s->v.TryExcept.handlers, i);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001867 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +00001869 c->u->u_lineno_set = false;
1870 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871 except = compiler_new_block(c);
1872 if (except == NULL)
1873 return 0;
Georg Brandla48f3ab2008-03-30 06:40:17 +00001874 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875 ADDOP(c, DUP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001876 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001878 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 }
1880 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001881 if (handler->v.ExceptHandler.name) {
1882 VISIT(c, expr, handler->v.ExceptHandler.name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883 }
1884 else {
1885 ADDOP(c, POP_TOP);
1886 }
1887 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001888 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889 ADDOP_JREL(c, JUMP_FORWARD, end);
1890 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891 }
1892 ADDOP(c, END_FINALLY);
1893 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001894 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895 compiler_use_next_block(c, end);
1896 return 1;
1897}
1898
1899static int
1900compiler_import_as(struct compiler *c, identifier name, identifier asname)
1901{
1902 /* The IMPORT_NAME opcode was already generated. This function
1903 merely needs to bind the result to a name.
1904
1905 If there is a dot in name, we need to split it and emit a
1906 LOAD_ATTR for each name.
1907 */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001908 const char *src = PyString_AS_STRING(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909 const char *dot = strchr(src, '.');
1910 if (dot) {
1911 /* Consume the base module name to get the first attribute */
1912 src = dot + 1;
1913 while (dot) {
1914 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001915 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 dot = strchr(src, '.');
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001917 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001919 if (!attr)
1920 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001922 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923 src = dot + 1;
1924 }
1925 }
1926 return compiler_nameop(c, asname, Store);
1927}
1928
1929static int
1930compiler_import(struct compiler *c, stmt_ty s)
1931{
1932 /* The Import node stores a module name like a.b.c as a single
1933 string. This is convenient for all cases except
1934 import a.b.c as d
1935 where we need to parse that string to extract the individual
1936 module names.
1937 XXX Perhaps change the representation to make this case simpler?
1938 */
1939 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001940
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001942 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001944 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945
Neal Norwitzcbce2802006-04-03 06:26:32 +00001946 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001947 level = PyInt_FromLong(0);
1948 else
1949 level = PyInt_FromLong(-1);
1950
1951 if (level == NULL)
1952 return 0;
1953
1954 ADDOP_O(c, LOAD_CONST, level, consts);
1955 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1957 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1958
1959 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001960 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001961 if (!r)
1962 return r;
1963 }
1964 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965 identifier tmp = alias->name;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001966 const char *base = PyString_AS_STRING(alias->name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 char *dot = strchr(base, '.');
1968 if (dot)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001969 tmp = PyString_FromStringAndSize(base,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970 dot - base);
1971 r = compiler_nameop(c, tmp, Store);
1972 if (dot) {
1973 Py_DECREF(tmp);
1974 }
1975 if (!r)
1976 return r;
1977 }
1978 }
1979 return 1;
1980}
1981
1982static int
1983compiler_from_import(struct compiler *c, stmt_ty s)
1984{
1985 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986
1987 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001988 PyObject *level;
1989
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 if (!names)
1991 return 0;
1992
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001993 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001994 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001995 level = PyInt_FromLong(-1);
1996 else
1997 level = PyInt_FromLong(s->v.ImportFrom.level);
1998
1999 if (!level) {
2000 Py_DECREF(names);
2001 return 0;
2002 }
2003
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 /* build up the names */
2005 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002006 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 Py_INCREF(alias->name);
2008 PyTuple_SET_ITEM(names, i, alias->name);
2009 }
2010
2011 if (s->lineno > c->c_future->ff_lineno) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002012 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002014 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 Py_DECREF(names);
2016 return compiler_error(c,
2017 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002018 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019
2020 }
2021 }
2022
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002023 ADDOP_O(c, LOAD_CONST, level, consts);
2024 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002026 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2028 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002029 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030 identifier store_name;
2031
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002032 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 assert(n == 1);
2034 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002035 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036 }
2037
2038 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2039 store_name = alias->name;
2040 if (alias->asname)
2041 store_name = alias->asname;
2042
2043 if (!compiler_nameop(c, store_name, Store)) {
2044 Py_DECREF(names);
2045 return 0;
2046 }
2047 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002048 /* remove imported module */
2049 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 return 1;
2051}
2052
2053static int
2054compiler_assert(struct compiler *c, stmt_ty s)
2055{
2056 static PyObject *assertion_error = NULL;
2057 basicblock *end;
2058
2059 if (Py_OptimizeFlag)
2060 return 1;
2061 if (assertion_error == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002062 assertion_error = PyString_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 if (assertion_error == NULL)
2064 return 0;
2065 }
Neal Norwitz400aeda2008-03-15 22:03:18 +00002066 if (s->v.Assert.test->kind == Tuple_kind &&
2067 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2068 const char* msg =
2069 "assertion is always true, perhaps remove parentheses?";
2070 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2071 c->u->u_lineno, NULL, NULL) == -1)
2072 return 0;
2073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 VISIT(c, expr, s->v.Assert.test);
2075 end = compiler_new_block(c);
2076 if (end == NULL)
2077 return 0;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002078 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2080 if (s->v.Assert.msg) {
2081 VISIT(c, expr, s->v.Assert.msg);
2082 ADDOP_I(c, RAISE_VARARGS, 2);
2083 }
2084 else {
2085 ADDOP_I(c, RAISE_VARARGS, 1);
2086 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002087 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 return 1;
2089}
2090
2091static int
2092compiler_visit_stmt(struct compiler *c, stmt_ty s)
2093{
2094 int i, n;
2095
Neal Norwitzf733a012006-10-29 18:30:10 +00002096 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 c->u->u_lineno = s->lineno;
2098 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002099
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002101 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 if (c->u->u_ste->ste_type != FunctionBlock)
2107 return compiler_error(c, "'return' outside function");
2108 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002109 VISIT(c, expr, s->v.Return.value);
2110 }
2111 else
2112 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2113 ADDOP(c, RETURN_VALUE);
2114 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002115 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002116 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002118 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119 n = asdl_seq_LEN(s->v.Assign.targets);
2120 VISIT(c, expr, s->v.Assign.value);
2121 for (i = 0; i < n; i++) {
2122 if (i < n - 1)
2123 ADDOP(c, DUP_TOP);
2124 VISIT(c, expr,
2125 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2126 }
2127 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002128 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002130 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002132 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002134 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002136 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002138 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139 n = 0;
2140 if (s->v.Raise.type) {
2141 VISIT(c, expr, s->v.Raise.type);
2142 n++;
2143 if (s->v.Raise.inst) {
2144 VISIT(c, expr, s->v.Raise.inst);
2145 n++;
2146 if (s->v.Raise.tback) {
2147 VISIT(c, expr, s->v.Raise.tback);
2148 n++;
2149 }
2150 }
2151 }
2152 ADDOP_I(c, RAISE_VARARGS, n);
2153 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002154 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002156 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002158 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002160 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002162 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002164 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165 VISIT(c, expr, s->v.Exec.body);
2166 if (s->v.Exec.globals) {
2167 VISIT(c, expr, s->v.Exec.globals);
2168 if (s->v.Exec.locals) {
2169 VISIT(c, expr, s->v.Exec.locals);
2170 } else {
2171 ADDOP(c, DUP_TOP);
2172 }
2173 } else {
2174 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2175 ADDOP(c, DUP_TOP);
2176 }
2177 ADDOP(c, EXEC_STMT);
2178 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002179 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002181 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002183 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002184 ADDOP(c, PRINT_EXPR);
2185 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002186 else if (s->v.Expr.value->kind != Str_kind &&
2187 s->v.Expr.value->kind != Num_kind) {
2188 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189 ADDOP(c, POP_TOP);
2190 }
2191 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002192 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002194 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002195 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 return compiler_error(c, "'break' outside loop");
2197 ADDOP(c, BREAK_LOOP);
2198 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002199 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002201 case With_kind:
2202 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203 }
2204 return 1;
2205}
2206
2207static int
2208unaryop(unaryop_ty op)
2209{
2210 switch (op) {
2211 case Invert:
2212 return UNARY_INVERT;
2213 case Not:
2214 return UNARY_NOT;
2215 case UAdd:
2216 return UNARY_POSITIVE;
2217 case USub:
2218 return UNARY_NEGATIVE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002219 default:
2220 PyErr_Format(PyExc_SystemError,
2221 "unary op %d should not be possible", op);
2222 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224}
2225
2226static int
2227binop(struct compiler *c, operator_ty op)
2228{
2229 switch (op) {
2230 case Add:
2231 return BINARY_ADD;
2232 case Sub:
2233 return BINARY_SUBTRACT;
2234 case Mult:
2235 return BINARY_MULTIPLY;
2236 case Div:
2237 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2238 return BINARY_TRUE_DIVIDE;
2239 else
2240 return BINARY_DIVIDE;
2241 case Mod:
2242 return BINARY_MODULO;
2243 case Pow:
2244 return BINARY_POWER;
2245 case LShift:
2246 return BINARY_LSHIFT;
2247 case RShift:
2248 return BINARY_RSHIFT;
2249 case BitOr:
2250 return BINARY_OR;
2251 case BitXor:
2252 return BINARY_XOR;
2253 case BitAnd:
2254 return BINARY_AND;
2255 case FloorDiv:
2256 return BINARY_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002257 default:
2258 PyErr_Format(PyExc_SystemError,
2259 "binary op %d should not be possible", op);
2260 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262}
2263
2264static int
2265cmpop(cmpop_ty op)
2266{
2267 switch (op) {
2268 case Eq:
2269 return PyCmp_EQ;
2270 case NotEq:
2271 return PyCmp_NE;
2272 case Lt:
2273 return PyCmp_LT;
2274 case LtE:
2275 return PyCmp_LE;
2276 case Gt:
2277 return PyCmp_GT;
2278 case GtE:
2279 return PyCmp_GE;
2280 case Is:
2281 return PyCmp_IS;
2282 case IsNot:
2283 return PyCmp_IS_NOT;
2284 case In:
2285 return PyCmp_IN;
2286 case NotIn:
2287 return PyCmp_NOT_IN;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002288 default:
2289 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291}
2292
2293static int
2294inplace_binop(struct compiler *c, operator_ty op)
2295{
2296 switch (op) {
2297 case Add:
2298 return INPLACE_ADD;
2299 case Sub:
2300 return INPLACE_SUBTRACT;
2301 case Mult:
2302 return INPLACE_MULTIPLY;
2303 case Div:
2304 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2305 return INPLACE_TRUE_DIVIDE;
2306 else
2307 return INPLACE_DIVIDE;
2308 case Mod:
2309 return INPLACE_MODULO;
2310 case Pow:
2311 return INPLACE_POWER;
2312 case LShift:
2313 return INPLACE_LSHIFT;
2314 case RShift:
2315 return INPLACE_RSHIFT;
2316 case BitOr:
2317 return INPLACE_OR;
2318 case BitXor:
2319 return INPLACE_XOR;
2320 case BitAnd:
2321 return INPLACE_AND;
2322 case FloorDiv:
2323 return INPLACE_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002324 default:
2325 PyErr_Format(PyExc_SystemError,
2326 "inplace binary op %d should not be possible", op);
2327 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329}
2330
2331static int
2332compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2333{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002334 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2336
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002337 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002338 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339 /* XXX AugStore isn't used anywhere! */
2340
Neal Norwitz0031ff32008-02-25 01:45:37 +00002341 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002342 if (!mangled)
2343 return 0;
2344
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 op = 0;
2346 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002347 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348 switch (scope) {
2349 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002350 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351 optype = OP_DEREF;
2352 break;
2353 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002354 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 optype = OP_DEREF;
2356 break;
2357 case LOCAL:
2358 if (c->u->u_ste->ste_type == FunctionBlock)
2359 optype = OP_FAST;
2360 break;
2361 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002362 if (c->u->u_ste->ste_type == FunctionBlock &&
2363 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364 optype = OP_GLOBAL;
2365 break;
2366 case GLOBAL_EXPLICIT:
2367 optype = OP_GLOBAL;
2368 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002369 default:
2370 /* scope can be 0 */
2371 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372 }
2373
2374 /* XXX Leave assert here, but handle __doc__ and the like better */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002375 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376
2377 switch (optype) {
2378 case OP_DEREF:
2379 switch (ctx) {
2380 case Load: op = LOAD_DEREF; break;
2381 case Store: op = STORE_DEREF; break;
2382 case AugLoad:
2383 case AugStore:
2384 break;
2385 case Del:
2386 PyErr_Format(PyExc_SyntaxError,
2387 "can not delete variable '%s' referenced "
2388 "in nested scope",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002389 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002390 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002393 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002394 PyErr_SetString(PyExc_SystemError,
2395 "param invalid for deref variable");
2396 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397 }
2398 break;
2399 case OP_FAST:
2400 switch (ctx) {
2401 case Load: op = LOAD_FAST; break;
2402 case Store: op = STORE_FAST; break;
2403 case Del: op = DELETE_FAST; break;
2404 case AugLoad:
2405 case AugStore:
2406 break;
2407 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002408 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002409 PyErr_SetString(PyExc_SystemError,
2410 "param invalid for local variable");
2411 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002413 ADDOP_O(c, op, mangled, varnames);
2414 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415 return 1;
2416 case OP_GLOBAL:
2417 switch (ctx) {
2418 case Load: op = LOAD_GLOBAL; break;
2419 case Store: op = STORE_GLOBAL; break;
2420 case Del: op = DELETE_GLOBAL; break;
2421 case AugLoad:
2422 case AugStore:
2423 break;
2424 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002425 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002426 PyErr_SetString(PyExc_SystemError,
2427 "param invalid for global variable");
2428 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002429 }
2430 break;
2431 case OP_NAME:
2432 switch (ctx) {
2433 case Load: op = LOAD_NAME; break;
2434 case Store: op = STORE_NAME; break;
2435 case Del: op = DELETE_NAME; break;
2436 case AugLoad:
2437 case AugStore:
2438 break;
2439 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002440 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002441 PyErr_SetString(PyExc_SystemError,
2442 "param invalid for name variable");
2443 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 }
2445 break;
2446 }
2447
2448 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002449 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002450 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002451 if (arg < 0)
2452 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002453 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454}
2455
2456static int
2457compiler_boolop(struct compiler *c, expr_ty e)
2458{
2459 basicblock *end;
2460 int jumpi, i, n;
2461 asdl_seq *s;
2462
2463 assert(e->kind == BoolOp_kind);
2464 if (e->v.BoolOp.op == And)
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002465 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 else
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002467 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002469 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 return 0;
2471 s = e->v.BoolOp.values;
2472 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002473 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002475 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002476 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002478 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479 compiler_use_next_block(c, end);
2480 return 1;
2481}
2482
2483static int
2484compiler_list(struct compiler *c, expr_ty e)
2485{
2486 int n = asdl_seq_LEN(e->v.List.elts);
2487 if (e->v.List.ctx == Store) {
2488 ADDOP_I(c, UNPACK_SEQUENCE, n);
2489 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002490 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 if (e->v.List.ctx == Load) {
2492 ADDOP_I(c, BUILD_LIST, n);
2493 }
2494 return 1;
2495}
2496
2497static int
2498compiler_tuple(struct compiler *c, expr_ty e)
2499{
2500 int n = asdl_seq_LEN(e->v.Tuple.elts);
2501 if (e->v.Tuple.ctx == Store) {
2502 ADDOP_I(c, UNPACK_SEQUENCE, n);
2503 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002504 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505 if (e->v.Tuple.ctx == Load) {
2506 ADDOP_I(c, BUILD_TUPLE, n);
2507 }
2508 return 1;
2509}
2510
2511static int
2512compiler_compare(struct compiler *c, expr_ty e)
2513{
2514 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002515 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516
2517 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2518 VISIT(c, expr, e->v.Compare.left);
2519 n = asdl_seq_LEN(e->v.Compare.ops);
2520 assert(n > 0);
2521 if (n > 1) {
2522 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002523 if (cleanup == NULL)
2524 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002525 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002526 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 }
2528 for (i = 1; i < n; i++) {
2529 ADDOP(c, DUP_TOP);
2530 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002532 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002533 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002534 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002537 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002538 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002540 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002542 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 if (n > 1) {
2544 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002545 if (end == NULL)
2546 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547 ADDOP_JREL(c, JUMP_FORWARD, end);
2548 compiler_use_next_block(c, cleanup);
2549 ADDOP(c, ROT_TWO);
2550 ADDOP(c, POP_TOP);
2551 compiler_use_next_block(c, end);
2552 }
2553 return 1;
2554}
2555
2556static int
2557compiler_call(struct compiler *c, expr_ty e)
2558{
2559 int n, code = 0;
2560
2561 VISIT(c, expr, e->v.Call.func);
2562 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002563 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002565 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002566 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2567 }
2568 if (e->v.Call.starargs) {
2569 VISIT(c, expr, e->v.Call.starargs);
2570 code |= 1;
2571 }
2572 if (e->v.Call.kwargs) {
2573 VISIT(c, expr, e->v.Call.kwargs);
2574 code |= 2;
2575 }
2576 switch (code) {
2577 case 0:
2578 ADDOP_I(c, CALL_FUNCTION, n);
2579 break;
2580 case 1:
2581 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2582 break;
2583 case 2:
2584 ADDOP_I(c, CALL_FUNCTION_KW, n);
2585 break;
2586 case 3:
2587 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2588 break;
2589 }
2590 return 1;
2591}
2592
2593static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002594compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
2595 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596{
2597 /* generate code for the iterator, then each of the ifs,
2598 and then write to the element */
2599
2600 comprehension_ty l;
2601 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002602 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603
2604 start = compiler_new_block(c);
2605 skip = compiler_new_block(c);
2606 if_cleanup = compiler_new_block(c);
2607 anchor = compiler_new_block(c);
2608
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002609 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2610 anchor == NULL)
2611 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612
Anthony Baxter7b782b62006-04-11 12:01:56 +00002613 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 VISIT(c, expr, l->iter);
2615 ADDOP(c, GET_ITER);
2616 compiler_use_next_block(c, start);
2617 ADDOP_JREL(c, FOR_ITER, anchor);
2618 NEXT_BLOCK(c);
2619 VISIT(c, expr, l->target);
2620
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002621 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622 n = asdl_seq_LEN(l->ifs);
2623 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002624 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002626 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628 }
2629
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002630 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitroud0c35152008-12-17 00:38:28 +00002631 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 /* only append after the last for generator */
2635 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636 VISIT(c, expr, elt);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002637 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002638
2639 compiler_use_next_block(c, skip);
2640 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002641 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2643 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644
2645 return 1;
2646}
2647
2648static int
2649compiler_listcomp(struct compiler *c, expr_ty e)
2650{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651 assert(e->kind == ListComp_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 ADDOP_I(c, BUILD_LIST, 0);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002653 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2654 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655}
2656
2657static int
2658compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 asdl_seq *generators, int gen_index,
2660 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661{
2662 /* generate code for the iterator, then each of the ifs,
2663 and then write to the element */
2664
2665 comprehension_ty ge;
2666 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668
2669 start = compiler_new_block(c);
2670 skip = compiler_new_block(c);
2671 if_cleanup = compiler_new_block(c);
2672 anchor = compiler_new_block(c);
2673 end = compiler_new_block(c);
2674
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 anchor == NULL || end == NULL)
2677 return 0;
2678
Anthony Baxter7b782b62006-04-11 12:01:56 +00002679 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 ADDOP_JREL(c, SETUP_LOOP, end);
2681 if (!compiler_push_fblock(c, LOOP, start))
2682 return 0;
2683
2684 if (gen_index == 0) {
2685 /* Receive outermost iter as an implicit argument */
2686 c->u->u_argcount = 1;
2687 ADDOP_I(c, LOAD_FAST, 0);
2688 }
2689 else {
2690 /* Sub-iter - calculate on the fly */
2691 VISIT(c, expr, ge->iter);
2692 ADDOP(c, GET_ITER);
2693 }
2694 compiler_use_next_block(c, start);
2695 ADDOP_JREL(c, FOR_ITER, anchor);
2696 NEXT_BLOCK(c);
2697 VISIT(c, expr, ge->target);
2698
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002699 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 n = asdl_seq_LEN(ge->ifs);
2701 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002702 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002704 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 NEXT_BLOCK(c);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002706 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2710 return 0;
2711
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 /* only append after the last 'for' generator */
2713 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 VISIT(c, expr, elt);
2715 ADDOP(c, YIELD_VALUE);
2716 ADDOP(c, POP_TOP);
2717
2718 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002720 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2722 compiler_use_next_block(c, anchor);
2723 ADDOP(c, POP_BLOCK);
2724 compiler_pop_fblock(c, LOOP, start);
2725 compiler_use_next_block(c, end);
2726
2727 return 1;
2728}
2729
2730static int
2731compiler_genexp(struct compiler *c, expr_ty e)
2732{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002733 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734 PyCodeObject *co;
2735 expr_ty outermost_iter = ((comprehension_ty)
2736 (asdl_seq_GET(e->v.GeneratorExp.generators,
2737 0)))->iter;
2738
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002739 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002740 name = PyString_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002741 if (!name)
2742 return 0;
2743 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
2745 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2746 return 0;
2747 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2748 e->v.GeneratorExp.elt);
2749 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002750 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751 if (co == NULL)
2752 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002754 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002755 Py_DECREF(co);
2756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 VISIT(c, expr, outermost_iter);
2758 ADDOP(c, GET_ITER);
2759 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760
2761 return 1;
2762}
2763
2764static int
2765compiler_visit_keyword(struct compiler *c, keyword_ty k)
2766{
2767 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2768 VISIT(c, expr, k->value);
2769 return 1;
2770}
2771
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002772/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773 whether they are true or false.
2774
2775 Return values: 1 for true, 0 for false, -1 for non-constant.
2776 */
2777
2778static int
2779expr_constant(expr_ty e)
2780{
2781 switch (e->kind) {
2782 case Num_kind:
2783 return PyObject_IsTrue(e->v.Num.n);
2784 case Str_kind:
2785 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002786 case Name_kind:
2787 /* __debug__ is not assignable, so we can optimize
2788 * it away in if and while statements */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002789 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002790 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002791 return ! Py_OptimizeFlag;
2792 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002793 default:
2794 return -1;
2795 }
2796}
2797
Guido van Rossumc2e20742006-02-27 22:32:47 +00002798/*
2799 Implements the with statement from PEP 343.
2800
2801 The semantics outlined in that PEP are as follows:
2802
2803 with EXPR as VAR:
2804 BLOCK
2805
2806 It is implemented roughly as:
2807
Guido van Rossumda5b7012006-05-02 19:47:52 +00002808 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002809 exit = context.__exit__ # not calling it
2810 value = context.__enter__()
2811 try:
2812 VAR = value # if VAR present in the syntax
2813 BLOCK
2814 finally:
2815 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002817 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002818 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002819 exit(*exc)
2820 */
2821static int
2822compiler_with(struct compiler *c, stmt_ty s)
2823{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002824 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002825 basicblock *block, *finally;
Nick Coghlan7af53be2008-03-07 14:13:28 +00002826 identifier tmpvalue = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002827
2828 assert(s->kind == With_kind);
2829
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830 if (!enter_attr) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002831 enter_attr = PyString_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002832 if (!enter_attr)
2833 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834 }
2835 if (!exit_attr) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002836 exit_attr = PyString_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002837 if (!exit_attr)
2838 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002839 }
2840
2841 block = compiler_new_block(c);
2842 finally = compiler_new_block(c);
2843 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002844 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002845
Guido van Rossumc2e20742006-02-27 22:32:47 +00002846 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002848 We need to do this rather than preserving it on the stack
2849 because SETUP_FINALLY remembers the stack level.
2850 We need to do the assignment *inside* the try/finally
2851 so that context.__exit__() is called when the assignment
2852 fails. But we need to call context.__enter__() *before*
2853 the try/finally so that if it fails we won't call
2854 context.__exit__().
2855 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002856 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002857 if (tmpvalue == NULL)
2858 return 0;
2859 PyArena_AddPyObject(c->c_arena, tmpvalue);
2860 }
2861
Guido van Rossumda5b7012006-05-02 19:47:52 +00002862 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002863 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002864
Nick Coghlan7af53be2008-03-07 14:13:28 +00002865 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002866 ADDOP(c, DUP_TOP);
2867 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Nick Coghlan7af53be2008-03-07 14:13:28 +00002868 ADDOP(c, ROT_TWO);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869
2870 /* Call context.__enter__() */
2871 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2872 ADDOP_I(c, CALL_FUNCTION, 0);
2873
2874 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002875 /* Store it in tmpvalue */
2876 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002877 return 0;
2878 }
2879 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002880 /* Discard result from context.__enter__() */
2881 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002882 }
2883
2884 /* Start the try block */
2885 ADDOP_JREL(c, SETUP_FINALLY, finally);
2886
2887 compiler_use_next_block(c, block);
2888 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002889 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002890 }
2891
2892 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002893 /* Bind saved result of context.__enter__() to VAR */
2894 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002895 !compiler_nameop(c, tmpvalue, Del))
2896 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002897 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002898 }
2899
2900 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002901 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002902
2903 /* End of try block; start the finally block */
2904 ADDOP(c, POP_BLOCK);
2905 compiler_pop_fblock(c, FINALLY_TRY, block);
2906
2907 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2908 compiler_use_next_block(c, finally);
2909 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002910 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002911
Nick Coghlan7af53be2008-03-07 14:13:28 +00002912 /* Finally block starts; context.__exit__ is on the stack under
2913 the exception or return information. Just issue our magic
2914 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002915 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002916
2917 /* Finally block ends. */
2918 ADDOP(c, END_FINALLY);
2919 compiler_pop_fblock(c, FINALLY_END, finally);
2920 return 1;
2921}
2922
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923static int
2924compiler_visit_expr(struct compiler *c, expr_ty e)
2925{
2926 int i, n;
2927
Neal Norwitzf733a012006-10-29 18:30:10 +00002928 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002929 set a new line number for the next instruction.
2930 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 if (e->lineno > c->u->u_lineno) {
2932 c->u->u_lineno = e->lineno;
2933 c->u->u_lineno_set = false;
2934 }
2935 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002936 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002938 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 VISIT(c, expr, e->v.BinOp.left);
2940 VISIT(c, expr, e->v.BinOp.right);
2941 ADDOP(c, binop(c, e->v.BinOp.op));
2942 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002943 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 VISIT(c, expr, e->v.UnaryOp.operand);
2945 ADDOP(c, unaryop(e->v.UnaryOp.op));
2946 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002947 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002949 case IfExp_kind:
2950 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002951 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettinger70fcfd02007-12-19 22:14:34 +00002953 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002955 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002956 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00002957 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002958 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00002959 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 }
2961 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002962 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002964 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965 return compiler_genexp(c, e);
2966 case Yield_kind:
2967 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002968 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969 if (e->v.Yield.value) {
2970 VISIT(c, expr, e->v.Yield.value);
2971 }
2972 else {
2973 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2974 }
2975 ADDOP(c, YIELD_VALUE);
2976 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002977 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002979 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 VISIT(c, expr, e->v.Repr.value);
2983 ADDOP(c, UNARY_CONVERT);
2984 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002985 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2987 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002988 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2990 break;
2991 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002992 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993 if (e->v.Attribute.ctx != AugStore)
2994 VISIT(c, expr, e->v.Attribute.value);
2995 switch (e->v.Attribute.ctx) {
2996 case AugLoad:
2997 ADDOP(c, DUP_TOP);
2998 /* Fall through to load */
2999 case Load:
3000 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3001 break;
3002 case AugStore:
3003 ADDOP(c, ROT_TWO);
3004 /* Fall through to save */
3005 case Store:
3006 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3007 break;
3008 case Del:
3009 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3010 break;
3011 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003012 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003013 PyErr_SetString(PyExc_SystemError,
3014 "param invalid in attribute expression");
3015 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 }
3017 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003018 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 switch (e->v.Subscript.ctx) {
3020 case AugLoad:
3021 VISIT(c, expr, e->v.Subscript.value);
3022 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3023 break;
3024 case Load:
3025 VISIT(c, expr, e->v.Subscript.value);
3026 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3027 break;
3028 case AugStore:
3029 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3030 break;
3031 case Store:
3032 VISIT(c, expr, e->v.Subscript.value);
3033 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3034 break;
3035 case Del:
3036 VISIT(c, expr, e->v.Subscript.value);
3037 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3038 break;
3039 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003040 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003041 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003042 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 }
3045 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003046 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3048 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003049 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003051 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052 return compiler_tuple(c, e);
3053 }
3054 return 1;
3055}
3056
3057static int
3058compiler_augassign(struct compiler *c, stmt_ty s)
3059{
3060 expr_ty e = s->v.AugAssign.target;
3061 expr_ty auge;
3062
3063 assert(s->kind == AugAssign_kind);
3064
3065 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003066 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003068 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003069 if (auge == NULL)
3070 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 VISIT(c, expr, auge);
3072 VISIT(c, expr, s->v.AugAssign.value);
3073 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3074 auge->v.Attribute.ctx = AugStore;
3075 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076 break;
3077 case Subscript_kind:
3078 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003079 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003080 if (auge == NULL)
3081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082 VISIT(c, expr, auge);
3083 VISIT(c, expr, s->v.AugAssign.value);
3084 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003085 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003087 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003089 if (!compiler_nameop(c, e->v.Name.id, Load))
3090 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 VISIT(c, expr, s->v.AugAssign.value);
3092 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3093 return compiler_nameop(c, e->v.Name.id, Store);
3094 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003095 PyErr_Format(PyExc_SystemError,
3096 "invalid node type (%d) for augmented assignment",
3097 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003098 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003099 }
3100 return 1;
3101}
3102
3103static int
3104compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3105{
3106 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003107 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3108 PyErr_SetString(PyExc_SystemError,
3109 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003111 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112 f = &c->u->u_fblock[c->u->u_nfblocks++];
3113 f->fb_type = t;
3114 f->fb_block = b;
3115 return 1;
3116}
3117
3118static void
3119compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3120{
3121 struct compiler_unit *u = c->u;
3122 assert(u->u_nfblocks > 0);
3123 u->u_nfblocks--;
3124 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3125 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3126}
3127
Jeremy Hylton82271f12006-10-04 02:24:52 +00003128static int
3129compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003130 int i;
3131 struct compiler_unit *u = c->u;
3132 for (i = 0; i < u->u_nfblocks; ++i) {
3133 if (u->u_fblock[i].fb_type == LOOP)
3134 return 1;
3135 }
3136 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003137}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138/* Raises a SyntaxError and returns 0.
3139 If something goes wrong, a different exception may be raised.
3140*/
3141
3142static int
3143compiler_error(struct compiler *c, const char *errstr)
3144{
3145 PyObject *loc;
3146 PyObject *u = NULL, *v = NULL;
3147
3148 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3149 if (!loc) {
3150 Py_INCREF(Py_None);
3151 loc = Py_None;
3152 }
3153 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3154 Py_None, loc);
3155 if (!u)
3156 goto exit;
3157 v = Py_BuildValue("(zO)", errstr, u);
3158 if (!v)
3159 goto exit;
3160 PyErr_SetObject(PyExc_SyntaxError, v);
3161 exit:
3162 Py_DECREF(loc);
3163 Py_XDECREF(u);
3164 Py_XDECREF(v);
3165 return 0;
3166}
3167
3168static int
3169compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003170 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003172 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003174 /* XXX this code is duplicated */
3175 switch (ctx) {
3176 case AugLoad: /* fall through to Load */
3177 case Load: op = BINARY_SUBSCR; break;
3178 case AugStore:/* fall through to Store */
3179 case Store: op = STORE_SUBSCR; break;
3180 case Del: op = DELETE_SUBSCR; break;
3181 case Param:
3182 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003183 "invalid %s kind %d in subscript\n",
3184 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003185 return 0;
3186 }
3187 if (ctx == AugLoad) {
3188 ADDOP_I(c, DUP_TOPX, 2);
3189 }
3190 else if (ctx == AugStore) {
3191 ADDOP(c, ROT_THREE);
3192 }
3193 ADDOP(c, op);
3194 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195}
3196
3197static int
3198compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3199{
3200 int n = 2;
3201 assert(s->kind == Slice_kind);
3202
3203 /* only handles the cases where BUILD_SLICE is emitted */
3204 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 }
3207 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003208 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003212 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213 }
3214 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003215 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216 }
3217
3218 if (s->v.Slice.step) {
3219 n++;
3220 VISIT(c, expr, s->v.Slice.step);
3221 }
3222 ADDOP_I(c, BUILD_SLICE, n);
3223 return 1;
3224}
3225
3226static int
3227compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3228{
3229 int op = 0, slice_offset = 0, stack_count = 0;
3230
3231 assert(s->v.Slice.step == NULL);
3232 if (s->v.Slice.lower) {
3233 slice_offset++;
3234 stack_count++;
3235 if (ctx != AugStore)
3236 VISIT(c, expr, s->v.Slice.lower);
3237 }
3238 if (s->v.Slice.upper) {
3239 slice_offset += 2;
3240 stack_count++;
3241 if (ctx != AugStore)
3242 VISIT(c, expr, s->v.Slice.upper);
3243 }
3244
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003245 if (ctx == AugLoad) {
3246 switch (stack_count) {
3247 case 0: ADDOP(c, DUP_TOP); break;
3248 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3249 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3250 }
3251 }
3252 else if (ctx == AugStore) {
3253 switch (stack_count) {
3254 case 0: ADDOP(c, ROT_TWO); break;
3255 case 1: ADDOP(c, ROT_THREE); break;
3256 case 2: ADDOP(c, ROT_FOUR); break;
3257 }
3258 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259
3260 switch (ctx) {
3261 case AugLoad: /* fall through to Load */
3262 case Load: op = SLICE; break;
3263 case AugStore:/* fall through to Store */
3264 case Store: op = STORE_SLICE; break;
3265 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003266 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003267 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003268 PyErr_SetString(PyExc_SystemError,
3269 "param invalid in simple slice");
3270 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271 }
3272
3273 ADDOP(c, op + slice_offset);
3274 return 1;
3275}
3276
3277static int
3278compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3279 expr_context_ty ctx)
3280{
3281 switch (s->kind) {
3282 case Ellipsis_kind:
3283 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3284 break;
3285 case Slice_kind:
3286 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 case Index_kind:
3288 VISIT(c, expr, s->v.Index.value);
3289 break;
3290 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003291 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003292 PyErr_SetString(PyExc_SystemError,
3293 "extended slice invalid in nested slice");
3294 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295 }
3296 return 1;
3297}
3298
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299static int
3300compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3301{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003302 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003304 case Index_kind:
3305 kindname = "index";
3306 if (ctx != AugStore) {
3307 VISIT(c, expr, s->v.Index.value);
3308 }
3309 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003311 kindname = "ellipsis";
3312 if (ctx != AugStore) {
3313 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3314 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315 break;
3316 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003317 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318 if (!s->v.Slice.step)
3319 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003320 if (ctx != AugStore) {
3321 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 return 0;
3323 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003324 break;
3325 case ExtSlice_kind:
3326 kindname = "extended slice";
3327 if (ctx != AugStore) {
3328 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3329 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003330 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003331 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003332 if (!compiler_visit_nested_slice(c, sub, ctx))
3333 return 0;
3334 }
3335 ADDOP_I(c, BUILD_TUPLE, n);
3336 }
3337 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003338 default:
3339 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003340 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003343 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344}
3345
Neal Norwitzf733a012006-10-29 18:30:10 +00003346
3347/* End of the compiler section, beginning of the assembler section */
3348
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349/* do depth-first search of basic block graph, starting with block.
3350 post records the block indices in post-order.
3351
3352 XXX must handle implicit jumps from one block to next
3353*/
3354
Neal Norwitzf733a012006-10-29 18:30:10 +00003355struct assembler {
3356 PyObject *a_bytecode; /* string containing bytecode */
3357 int a_offset; /* offset into bytecode */
3358 int a_nblocks; /* number of reachable blocks */
3359 basicblock **a_postorder; /* list of blocks in dfs postorder */
3360 PyObject *a_lnotab; /* string containing lnotab */
3361 int a_lnotab_off; /* offset into lnotab */
3362 int a_lineno; /* last lineno of emitted instruction */
3363 int a_lineno_off; /* bytecode offset of last lineno */
3364};
3365
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366static void
3367dfs(struct compiler *c, basicblock *b, struct assembler *a)
3368{
3369 int i;
3370 struct instr *instr = NULL;
3371
3372 if (b->b_seen)
3373 return;
3374 b->b_seen = 1;
3375 if (b->b_next != NULL)
3376 dfs(c, b->b_next, a);
3377 for (i = 0; i < b->b_iused; i++) {
3378 instr = &b->b_instr[i];
3379 if (instr->i_jrel || instr->i_jabs)
3380 dfs(c, instr->i_target, a);
3381 }
3382 a->a_postorder[a->a_nblocks++] = b;
3383}
3384
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003385static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3387{
3388 int i;
3389 struct instr *instr;
3390 if (b->b_seen || b->b_startdepth >= depth)
3391 return maxdepth;
3392 b->b_seen = 1;
3393 b->b_startdepth = depth;
3394 for (i = 0; i < b->b_iused; i++) {
3395 instr = &b->b_instr[i];
3396 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3397 if (depth > maxdepth)
3398 maxdepth = depth;
3399 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3400 if (instr->i_jrel || instr->i_jabs) {
3401 maxdepth = stackdepth_walk(c, instr->i_target,
3402 depth, maxdepth);
3403 if (instr->i_opcode == JUMP_ABSOLUTE ||
3404 instr->i_opcode == JUMP_FORWARD) {
3405 goto out; /* remaining code is dead */
3406 }
3407 }
3408 }
3409 if (b->b_next)
3410 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3411out:
3412 b->b_seen = 0;
3413 return maxdepth;
3414}
3415
3416/* Find the flow path that needs the largest stack. We assume that
3417 * cycles in the flow graph have no net effect on the stack depth.
3418 */
3419static int
3420stackdepth(struct compiler *c)
3421{
3422 basicblock *b, *entryblock;
3423 entryblock = NULL;
3424 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3425 b->b_seen = 0;
3426 b->b_startdepth = INT_MIN;
3427 entryblock = b;
3428 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003429 if (!entryblock)
3430 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431 return stackdepth_walk(c, entryblock, 0, 0);
3432}
3433
3434static int
3435assemble_init(struct assembler *a, int nblocks, int firstlineno)
3436{
3437 memset(a, 0, sizeof(struct assembler));
3438 a->a_lineno = firstlineno;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003439 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440 if (!a->a_bytecode)
3441 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003442 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443 if (!a->a_lnotab)
3444 return 0;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003445 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3446 PyErr_NoMemory();
3447 return 0;
3448 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003449 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003450 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003451 if (!a->a_postorder) {
3452 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003454 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455 return 1;
3456}
3457
3458static void
3459assemble_free(struct assembler *a)
3460{
3461 Py_XDECREF(a->a_bytecode);
3462 Py_XDECREF(a->a_lnotab);
3463 if (a->a_postorder)
3464 PyObject_Free(a->a_postorder);
3465}
3466
3467/* Return the size of a basic block in bytes. */
3468
3469static int
3470instrsize(struct instr *instr)
3471{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003472 if (!instr->i_hasarg)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003473 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003474 if (instr->i_oparg > 0xffff)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003475 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3476 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477}
3478
3479static int
3480blocksize(basicblock *b)
3481{
3482 int i;
3483 int size = 0;
3484
3485 for (i = 0; i < b->b_iused; i++)
3486 size += instrsize(&b->b_instr[i]);
3487 return size;
3488}
3489
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003490/* Appends a pair to the end of the line number table, a_lnotab, representing
3491 the instruction's bytecode offset and line number. See
3492 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003493
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003494static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003496{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497 int d_bytecode, d_lineno;
3498 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003499 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500
3501 d_bytecode = a->a_offset - a->a_lineno_off;
3502 d_lineno = i->i_lineno - a->a_lineno;
3503
3504 assert(d_bytecode >= 0);
3505 assert(d_lineno >= 0);
3506
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003507 if(d_bytecode == 0 && d_lineno == 0)
3508 return 1;
3509
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003511 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003513 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003515 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003517 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003519 else {
3520 PyErr_NoMemory();
3521 return 0;
3522 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003523 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003525 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003526 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003527 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003528 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 *lnotab++ = 255;
3530 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 d_bytecode -= ncodes * 255;
3533 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535 assert(d_bytecode <= 255);
3536 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003537 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003539 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003541 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003543 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003545 else {
3546 PyErr_NoMemory();
3547 return 0;
3548 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003549 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003551 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003552 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003553 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003555 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003557 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003559 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003560 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 d_lineno -= ncodes * 255;
3562 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003563 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003564
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003565 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 if (a->a_lnotab_off + 2 >= len) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003567 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003568 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003569 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003570 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003571 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003572
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 a->a_lnotab_off += 2;
3574 if (d_bytecode) {
3575 *lnotab++ = d_bytecode;
3576 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003577 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003578 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579 *lnotab++ = 0;
3580 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003581 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582 a->a_lineno = i->i_lineno;
3583 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003584 return 1;
3585}
3586
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587/* assemble_emit()
3588 Extend the bytecode with a new instruction.
3589 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003590*/
3591
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003592static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003594{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003595 int size, arg = 0, ext = 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003596 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 char *code;
3598
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003599 size = instrsize(i);
3600 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003602 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003605 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 if (a->a_offset + size >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003607 if (len > PY_SSIZE_T_MAX / 2)
3608 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003609 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003610 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003611 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003612 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003614 if (size == 6) {
3615 assert(i->i_hasarg);
3616 *code++ = (char)EXTENDED_ARG;
3617 *code++ = ext & 0xff;
3618 *code++ = ext >> 8;
3619 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003622 if (i->i_hasarg) {
3623 assert(size == 3 || size == 6);
3624 *code++ = arg & 0xff;
3625 *code++ = arg >> 8;
3626 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003628}
3629
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003630static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003632{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003634 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003635 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003636
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637 /* Compute the size of each block and fixup jump args.
3638 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003639start:
3640 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003642 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643 bsize = blocksize(b);
3644 b->b_offset = totsize;
3645 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003646 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003647 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3649 bsize = b->b_offset;
3650 for (i = 0; i < b->b_iused; i++) {
3651 struct instr *instr = &b->b_instr[i];
3652 /* Relative jumps are computed relative to
3653 the instruction pointer after fetching
3654 the jump instruction.
3655 */
3656 bsize += instrsize(instr);
3657 if (instr->i_jabs)
3658 instr->i_oparg = instr->i_target->b_offset;
3659 else if (instr->i_jrel) {
3660 int delta = instr->i_target->b_offset - bsize;
3661 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003662 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003663 else
3664 continue;
3665 if (instr->i_oparg > 0xffff)
3666 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003667 }
3668 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003669
3670 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003671 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003672 with a better solution.
3673
3674 In the meantime, should the goto be dropped in favor
3675 of a loop?
3676
3677 The issue is that in the first loop blocksize() is called
3678 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003679 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003680 i_oparg is calculated in the second loop above.
3681
3682 So we loop until we stop seeing new EXTENDED_ARGs.
3683 The only EXTENDED_ARGs that could be popping up are
3684 ones in jump instructions. So this should converge
3685 fairly quickly.
3686 */
3687 if (last_extended_arg_count != extended_arg_count) {
3688 last_extended_arg_count = extended_arg_count;
3689 goto start;
3690 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003691}
3692
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003693static PyObject *
3694dict_keys_inorder(PyObject *dict, int offset)
3695{
3696 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003697 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003698
3699 tuple = PyTuple_New(size);
3700 if (tuple == NULL)
3701 return NULL;
3702 while (PyDict_Next(dict, &pos, &k, &v)) {
3703 i = PyInt_AS_LONG(v);
Benjamin Petersonda9327f2009-01-31 23:43:25 +00003704 /* The keys of the dictionary are tuples. (see compiler_add_o)
3705 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003706 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003707 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003708 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003709 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003710 PyTuple_SET_ITEM(tuple, i - offset, k);
3711 }
3712 return tuple;
3713}
3714
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003715static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003717{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718 PySTEntryObject *ste = c->u->u_ste;
3719 int flags = 0, n;
3720 if (ste->ste_type != ModuleBlock)
3721 flags |= CO_NEWLOCALS;
3722 if (ste->ste_type == FunctionBlock) {
3723 if (!ste->ste_unoptimized)
3724 flags |= CO_OPTIMIZED;
3725 if (ste->ste_nested)
3726 flags |= CO_NESTED;
3727 if (ste->ste_generator)
3728 flags |= CO_GENERATOR;
Benjamin Peterson12554cb2009-01-31 23:54:38 +00003729 if (ste->ste_varargs)
3730 flags |= CO_VARARGS;
3731 if (ste->ste_varkeywords)
3732 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003733 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003734
3735 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003736 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003737
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 n = PyDict_Size(c->u->u_freevars);
3739 if (n < 0)
3740 return -1;
3741 if (n == 0) {
3742 n = PyDict_Size(c->u->u_cellvars);
3743 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003744 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745 if (n == 0) {
3746 flags |= CO_NOFREE;
3747 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003748 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003749
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003750 return flags;
3751}
3752
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753static PyCodeObject *
3754makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003755{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756 PyObject *tmp;
3757 PyCodeObject *co = NULL;
3758 PyObject *consts = NULL;
3759 PyObject *names = NULL;
3760 PyObject *varnames = NULL;
3761 PyObject *filename = NULL;
3762 PyObject *name = NULL;
3763 PyObject *freevars = NULL;
3764 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003765 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768 tmp = dict_keys_inorder(c->u->u_consts, 0);
3769 if (!tmp)
3770 goto error;
3771 consts = PySequence_List(tmp); /* optimize_code requires a list */
3772 Py_DECREF(tmp);
3773
3774 names = dict_keys_inorder(c->u->u_names, 0);
3775 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3776 if (!consts || !names || !varnames)
3777 goto error;
3778
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003779 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3780 if (!cellvars)
3781 goto error;
3782 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3783 if (!freevars)
3784 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003785 filename = PyString_FromString(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 if (!filename)
3787 goto error;
3788
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003789 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790 flags = compute_code_flags(c);
3791 if (flags < 0)
3792 goto error;
3793
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003794 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795 if (!bytecode)
3796 goto error;
3797
3798 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3799 if (!tmp)
3800 goto error;
3801 Py_DECREF(consts);
3802 consts = tmp;
3803
3804 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3805 bytecode, consts, names, varnames,
3806 freevars, cellvars,
3807 filename, c->u->u_name,
3808 c->u->u_firstlineno,
3809 a->a_lnotab);
3810 error:
3811 Py_XDECREF(consts);
3812 Py_XDECREF(names);
3813 Py_XDECREF(varnames);
3814 Py_XDECREF(filename);
3815 Py_XDECREF(name);
3816 Py_XDECREF(freevars);
3817 Py_XDECREF(cellvars);
3818 Py_XDECREF(bytecode);
3819 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003820}
3821
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003822
3823/* For debugging purposes only */
3824#if 0
3825static void
3826dump_instr(const struct instr *i)
3827{
3828 const char *jrel = i->i_jrel ? "jrel " : "";
3829 const char *jabs = i->i_jabs ? "jabs " : "";
3830 char arg[128];
3831
3832 *arg = '\0';
3833 if (i->i_hasarg)
3834 sprintf(arg, "arg: %d ", i->i_oparg);
3835
3836 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3837 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3838}
3839
3840static void
3841dump_basicblock(const basicblock *b)
3842{
3843 const char *seen = b->b_seen ? "seen " : "";
3844 const char *b_return = b->b_return ? "return " : "";
3845 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3846 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3847 if (b->b_instr) {
3848 int i;
3849 for (i = 0; i < b->b_iused; i++) {
3850 fprintf(stderr, " [%02d] ", i);
3851 dump_instr(b->b_instr + i);
3852 }
3853 }
3854}
3855#endif
3856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857static PyCodeObject *
3858assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003859{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003860 basicblock *b, *entryblock;
3861 struct assembler a;
3862 int i, j, nblocks;
3863 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003864
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 /* Make sure every block that falls off the end returns None.
3866 XXX NEXT_BLOCK() isn't quite right, because if the last
3867 block ends with a jump or return b_next shouldn't set.
3868 */
3869 if (!c->u->u_curblock->b_return) {
3870 NEXT_BLOCK(c);
3871 if (addNone)
3872 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3873 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003874 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 nblocks = 0;
3877 entryblock = NULL;
3878 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3879 nblocks++;
3880 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003881 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003882
Neal Norwitzed657552006-07-10 00:04:44 +00003883 /* Set firstlineno if it wasn't explicitly set. */
3884 if (!c->u->u_firstlineno) {
3885 if (entryblock && entryblock->b_instr)
3886 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3887 else
3888 c->u->u_firstlineno = 1;
3889 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3891 goto error;
3892 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003893
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003895 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003896
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897 /* Emit code in reverse postorder from dfs. */
3898 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003899 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 for (j = 0; j < b->b_iused; j++)
3901 if (!assemble_emit(&a, &b->b_instr[j]))
3902 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003903 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003904
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003905 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003907 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003909
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 co = makecode(c, &a);
3911 error:
3912 assemble_free(&a);
3913 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003914}