blob: 03875a5b38ac77eda76e7c584a4c4de60f6db4fd [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 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114
115 int u_nfblocks;
116 struct fblockinfo u_fblock[CO_MAXBLOCKS];
117
118 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000119 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120 bool u_lineno_set; /* boolean to indicate whether instr
121 has been generated with current lineno */
122};
123
124/* This struct captures the global state of a compilation.
125
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000126The u pointer points to the current compilation unit, while units
127for enclosing blocks are stored in c_stack. The u and c_stack are
128managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129*/
130
131struct compiler {
132 const char *c_filename;
133 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000134 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135 PyCompilerFlags *c_flags;
136
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000137 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000138 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 struct compiler_unit *u; /* compiler state for current block */
141 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143};
144
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145static int compiler_enter_scope(struct compiler *, identifier, void *, int);
146static void compiler_free(struct compiler *);
147static basicblock *compiler_new_block(struct compiler *);
148static int compiler_next_instr(struct compiler *, basicblock *);
149static int compiler_addop(struct compiler *, int);
150static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
151static int compiler_addop_i(struct compiler *, int, int);
152static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153static basicblock *compiler_use_new_block(struct compiler *);
154static int compiler_error(struct compiler *, const char *);
155static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
156
157static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
158static int compiler_visit_stmt(struct compiler *, stmt_ty);
159static int compiler_visit_keyword(struct compiler *, keyword_ty);
160static int compiler_visit_expr(struct compiler *, expr_ty);
161static int compiler_augassign(struct compiler *, stmt_ty);
162static int compiler_visit_slice(struct compiler *, slice_ty,
163 expr_context_ty);
164
165static int compiler_push_fblock(struct compiler *, enum fblocktype,
166 basicblock *);
167static void compiler_pop_fblock(struct compiler *, enum fblocktype,
168 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000169/* Returns true if there is a loop on the fblock stack. */
170static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
172static int inplace_binop(struct compiler *, operator_ty);
173static int expr_constant(expr_ty e);
174
Guido van Rossumc2e20742006-02-27 22:32:47 +0000175static int compiler_with(struct compiler *, stmt_ty);
176
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static PyCodeObject *assemble(struct compiler *, int addNone);
178static PyObject *__doc__;
179
180PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000181_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000182{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183 /* Name mangling: __private becomes _classname__private.
184 This is independent from how the name is used. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000185 const char *p, *name = PyString_AsString(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000186 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187 size_t nlen, plen;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000188 if (privateobj == NULL || !PyString_Check(privateobj) ||
Neal Norwitz84167d02006-08-12 01:45:47 +0000189 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000190 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000192 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000193 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194 nlen = strlen(name);
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000195 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000196
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000197 The only time a name with a dot can occur is when
198 we are compiling an import statement that has a
199 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000200
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000201 TODO(jhylton): Decide whether we want to support
202 mangling of the module name, e.g. __M.X.
203 */
Jeremy Hylton37075c52007-02-27 01:01:59 +0000204 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000205 || strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209 /* Strip leading underscores from class name */
210 while (*p == '_')
211 p++;
212 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000213 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 plen = strlen(p);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000217
218 assert(1 <= PY_SSIZE_T_MAX - nlen);
219 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
220
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000221 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000222 if (!ident)
223 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000225 buffer = PyString_AS_STRING(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 strncpy(buffer+1, p, plen);
228 strcpy(buffer+1+plen, name);
229 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000230}
231
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232static int
233compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000234{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237 c->c_stack = PyList_New(0);
238 if (!c->c_stack)
239 return 0;
240
241 return 1;
242}
243
244PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000245PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000246 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000247{
248 struct compiler c;
249 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000250 PyCompilerFlags local_flags;
251 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000253 if (!__doc__) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000254 __doc__ = PyString_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 if (!__doc__)
256 return NULL;
257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000258
259 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000260 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000262 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263 c.c_future = PyFuture_FromAST(mod, filename);
264 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000265 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000267 local_flags.cf_flags = 0;
268 flags = &local_flags;
269 }
270 merged = c.c_future->ff_features | flags->cf_flags;
271 c.c_future->ff_features = merged;
272 flags->cf_flags = merged;
273 c.c_flags = flags;
274 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000275
276 c.c_st = PySymtable_Build(mod, filename, c.c_future);
277 if (c.c_st == NULL) {
278 if (!PyErr_Occurred())
279 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000280 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000281 }
282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283 co = compiler_mod(&c, mod);
284
Thomas Wouters1175c432006-02-27 22:49:54 +0000285 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000287 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288 return co;
289}
290
291PyCodeObject *
292PyNode_Compile(struct _node *n, const char *filename)
293{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000294 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000295 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000296 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000297 if (!arena)
298 return NULL;
299 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000300 if (mod)
301 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000302 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000303 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000304}
305
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000306static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000308{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309 if (c->c_st)
310 PySymtable_Free(c->c_st);
311 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000312 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000314}
315
Guido van Rossum79f25d91997-04-29 20:08:16 +0000316static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000318{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000319 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000320 PyObject *v, *k;
321 PyObject *dict = PyDict_New();
322 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324 n = PyList_Size(list);
325 for (i = 0; i < n; i++) {
326 v = PyInt_FromLong(i);
327 if (!v) {
328 Py_DECREF(dict);
329 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000330 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000331 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000332 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
334 Py_XDECREF(k);
335 Py_DECREF(v);
336 Py_DECREF(dict);
337 return NULL;
338 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000339 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 return dict;
343}
344
345/* Return new dict containing names from src that match scope(s).
346
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000347src is a symbol table dictionary. If the scope of a name matches
348either scope_type or flag is set, insert it into the new dict. The
349values are integers, starting at offset and increasing by one for
350each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351*/
352
353static PyObject *
354dictbytype(PyObject *src, int scope_type, int flag, int offset)
355{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000356 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357 PyObject *k, *v, *dest = PyDict_New();
358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359 assert(offset >= 0);
360 if (dest == NULL)
361 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
363 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 /* XXX this should probably be a macro in symtable.h */
365 assert(PyInt_Check(v));
366 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
369 PyObject *tuple, *item = PyInt_FromLong(i);
370 if (item == NULL) {
371 Py_DECREF(dest);
372 return NULL;
373 }
374 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000375 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
377 Py_DECREF(item);
378 Py_DECREF(dest);
379 Py_XDECREF(tuple);
380 return NULL;
381 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000383 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 }
386 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000387}
388
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389static void
390compiler_unit_check(struct compiler_unit *u)
391{
392 basicblock *block;
393 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Brett Cannona6c41bc2008-02-07 07:47:31 +0000394 assert((void *)block != (void *)0xcbcbcbcb);
395 assert((void *)block != (void *)0xfbfbfbfb);
396 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000397 if (block->b_instr != NULL) {
398 assert(block->b_ialloc > 0);
399 assert(block->b_iused > 0);
400 assert(block->b_ialloc >= block->b_iused);
401 }
402 else {
403 assert (block->b_iused == 0);
404 assert (block->b_ialloc == 0);
405 }
406 }
407}
408
409static void
410compiler_unit_free(struct compiler_unit *u)
411{
412 basicblock *b, *next;
413
414 compiler_unit_check(u);
415 b = u->u_blocks;
416 while (b != NULL) {
417 if (b->b_instr)
418 PyObject_Free((void *)b->b_instr);
419 next = b->b_list;
420 PyObject_Free((void *)b);
421 b = next;
422 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000423 Py_CLEAR(u->u_ste);
424 Py_CLEAR(u->u_name);
425 Py_CLEAR(u->u_consts);
426 Py_CLEAR(u->u_names);
427 Py_CLEAR(u->u_varnames);
428 Py_CLEAR(u->u_freevars);
429 Py_CLEAR(u->u_cellvars);
430 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000431 PyObject_Free(u);
432}
433
434static int
435compiler_enter_scope(struct compiler *c, identifier name, void *key,
436 int lineno)
437{
438 struct compiler_unit *u;
439
Anthony Baxter7b782b62006-04-11 12:01:56 +0000440 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000441 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000442 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000443 PyErr_NoMemory();
444 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000445 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000446 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447 u->u_argcount = 0;
448 u->u_ste = PySymtable_Lookup(c->c_st, key);
449 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000450 compiler_unit_free(u);
451 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452 }
453 Py_INCREF(name);
454 u->u_name = name;
455 u->u_varnames = list2dict(u->u_ste->ste_varnames);
456 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000457 if (!u->u_varnames || !u->u_cellvars) {
458 compiler_unit_free(u);
459 return 0;
460 }
461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000462 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000463 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000464 if (!u->u_freevars) {
465 compiler_unit_free(u);
466 return 0;
467 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468
469 u->u_blocks = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470 u->u_nfblocks = 0;
471 u->u_firstlineno = lineno;
472 u->u_lineno = 0;
473 u->u_lineno_set = false;
474 u->u_consts = PyDict_New();
475 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000476 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000477 return 0;
478 }
479 u->u_names = PyDict_New();
480 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000481 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000482 return 0;
483 }
484
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000485 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000486
487 /* Push the old compiler_unit on the stack. */
488 if (c->u) {
489 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000490 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
491 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000492 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493 return 0;
494 }
495 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000496 u->u_private = c->u->u_private;
497 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498 }
499 c->u = u;
500
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000501 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000502 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503 return 0;
504
505 return 1;
506}
507
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000508static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509compiler_exit_scope(struct compiler *c)
510{
511 int n;
512 PyObject *wrapper;
513
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000514 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515 compiler_unit_free(c->u);
516 /* Restore c->u to the parent unit. */
517 n = PyList_GET_SIZE(c->c_stack) - 1;
518 if (n >= 0) {
519 wrapper = PyList_GET_ITEM(c->c_stack, n);
520 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000521 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000522 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525 compiler_unit_check(c->u);
526 }
527 else
528 c->u = NULL;
529
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000530}
531
532/* Allocate a new block and return a pointer to it.
533 Returns NULL on error.
534*/
535
536static basicblock *
537compiler_new_block(struct compiler *c)
538{
539 basicblock *b;
540 struct compiler_unit *u;
541
542 u = c->u;
543 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000544 if (b == NULL) {
545 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000547 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000549 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550 b->b_list = u->u_blocks;
551 u->u_blocks = b;
552 return b;
553}
554
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555static basicblock *
556compiler_use_new_block(struct compiler *c)
557{
558 basicblock *block = compiler_new_block(c);
559 if (block == NULL)
560 return NULL;
561 c->u->u_curblock = block;
562 return block;
563}
564
565static basicblock *
566compiler_next_block(struct compiler *c)
567{
568 basicblock *block = compiler_new_block(c);
569 if (block == NULL)
570 return NULL;
571 c->u->u_curblock->b_next = block;
572 c->u->u_curblock = block;
573 return block;
574}
575
576static basicblock *
577compiler_use_next_block(struct compiler *c, basicblock *block)
578{
579 assert(block != NULL);
580 c->u->u_curblock->b_next = block;
581 c->u->u_curblock = block;
582 return block;
583}
584
585/* Returns the offset of the next instruction in the current block's
586 b_instr array. Resizes the b_instr as necessary.
587 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000588*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000589
590static int
591compiler_next_instr(struct compiler *c, basicblock *b)
592{
593 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000594 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000595 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000596 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000597 if (b->b_instr == NULL) {
598 PyErr_NoMemory();
599 return -1;
600 }
601 b->b_ialloc = DEFAULT_BLOCK_SIZE;
602 memset((char *)b->b_instr, 0,
603 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000606 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607 size_t oldsize, newsize;
608 oldsize = b->b_ialloc * sizeof(struct instr);
609 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000610
611 if (oldsize > (PY_SIZE_MAX >> 1)) {
612 PyErr_NoMemory();
613 return -1;
614 }
615
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616 if (newsize == 0) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000621 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000622 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000623 if (tmp == NULL) {
624 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000626 }
627 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
629 }
630 return b->b_iused++;
631}
632
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000633/* Set the i_lineno member of the instruction at offset off if the
634 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000635 already been set. If it has been set, the call has no effect.
636
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000637 The line number is reset in the following cases:
638 - when entering a new scope
639 - on each statement
640 - on each expression that start a new line
641 - before the "except" clause
642 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000643*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000644
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645static void
646compiler_set_lineno(struct compiler *c, int off)
647{
648 basicblock *b;
649 if (c->u->u_lineno_set)
650 return;
651 c->u->u_lineno_set = true;
652 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000653 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654}
655
656static int
657opcode_stack_effect(int opcode, int oparg)
658{
659 switch (opcode) {
660 case POP_TOP:
661 return -1;
662 case ROT_TWO:
663 case ROT_THREE:
664 return 0;
665 case DUP_TOP:
666 return 1;
667 case ROT_FOUR:
668 return 0;
669
670 case UNARY_POSITIVE:
671 case UNARY_NEGATIVE:
672 case UNARY_NOT:
673 case UNARY_CONVERT:
674 case UNARY_INVERT:
675 return 0;
676
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000677 case LIST_APPEND:
Antoine Pitroud0c35152008-12-17 00:38:28 +0000678 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000679
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000680 case BINARY_POWER:
681 case BINARY_MULTIPLY:
682 case BINARY_DIVIDE:
683 case BINARY_MODULO:
684 case BINARY_ADD:
685 case BINARY_SUBTRACT:
686 case BINARY_SUBSCR:
687 case BINARY_FLOOR_DIVIDE:
688 case BINARY_TRUE_DIVIDE:
689 return -1;
690 case INPLACE_FLOOR_DIVIDE:
691 case INPLACE_TRUE_DIVIDE:
692 return -1;
693
694 case SLICE+0:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000695 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696 case SLICE+1:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000697 return -1;
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000698 case SLICE+2:
699 return -1;
700 case SLICE+3:
701 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000702
703 case STORE_SLICE+0:
704 return -2;
705 case STORE_SLICE+1:
706 return -3;
707 case STORE_SLICE+2:
708 return -3;
709 case STORE_SLICE+3:
710 return -4;
711
712 case DELETE_SLICE+0:
713 return -1;
714 case DELETE_SLICE+1:
715 return -2;
716 case DELETE_SLICE+2:
717 return -2;
718 case DELETE_SLICE+3:
719 return -3;
720
721 case INPLACE_ADD:
722 case INPLACE_SUBTRACT:
723 case INPLACE_MULTIPLY:
724 case INPLACE_DIVIDE:
725 case INPLACE_MODULO:
726 return -1;
727 case STORE_SUBSCR:
728 return -3;
Raymond Hettingereffde122007-12-18 18:26:18 +0000729 case STORE_MAP:
730 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000731 case DELETE_SUBSCR:
732 return -2;
733
734 case BINARY_LSHIFT:
735 case BINARY_RSHIFT:
736 case BINARY_AND:
737 case BINARY_XOR:
738 case BINARY_OR:
739 return -1;
740 case INPLACE_POWER:
741 return -1;
742 case GET_ITER:
743 return 0;
744
745 case PRINT_EXPR:
746 return -1;
747 case PRINT_ITEM:
748 return -1;
749 case PRINT_NEWLINE:
750 return 0;
751 case PRINT_ITEM_TO:
752 return -2;
753 case PRINT_NEWLINE_TO:
754 return -1;
755 case INPLACE_LSHIFT:
756 case INPLACE_RSHIFT:
757 case INPLACE_AND:
758 case INPLACE_XOR:
759 case INPLACE_OR:
760 return -1;
761 case BREAK_LOOP:
762 return 0;
Benjamin Peterson1880d8b2009-05-25 13:13:44 +0000763 case SETUP_WITH:
Benjamin Peterson49a6b0e2009-05-25 20:12:57 +0000764 return 4;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000765 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000766 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767 case LOAD_LOCALS:
768 return 1;
769 case RETURN_VALUE:
770 return -1;
771 case IMPORT_STAR:
772 return -1;
773 case EXEC_STMT:
774 return -3;
775 case YIELD_VALUE:
776 return 0;
777
778 case POP_BLOCK:
779 return 0;
780 case END_FINALLY:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000781 return -3; /* or -1 or -2 if no exception occurred or
782 return/break/continue */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783 case BUILD_CLASS:
784 return -2;
785
786 case STORE_NAME:
787 return -1;
788 case DELETE_NAME:
789 return 0;
790 case UNPACK_SEQUENCE:
791 return oparg-1;
792 case FOR_ITER:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000793 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794
795 case STORE_ATTR:
796 return -2;
797 case DELETE_ATTR:
798 return -1;
799 case STORE_GLOBAL:
800 return -1;
801 case DELETE_GLOBAL:
802 return 0;
803 case DUP_TOPX:
804 return oparg;
805 case LOAD_CONST:
806 return 1;
807 case LOAD_NAME:
808 return 1;
809 case BUILD_TUPLE:
810 case BUILD_LIST:
811 return 1-oparg;
812 case BUILD_MAP:
813 return 1;
814 case LOAD_ATTR:
815 return 0;
816 case COMPARE_OP:
817 return -1;
818 case IMPORT_NAME:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000819 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000820 case IMPORT_FROM:
821 return 1;
822
823 case JUMP_FORWARD:
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000824 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
825 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000826 case JUMP_ABSOLUTE:
827 return 0;
828
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000829 case POP_JUMP_IF_FALSE:
830 case POP_JUMP_IF_TRUE:
831 return -1;
832
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833 case LOAD_GLOBAL:
834 return 1;
835
836 case CONTINUE_LOOP:
837 return 0;
838 case SETUP_LOOP:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000839 case SETUP_EXCEPT:
840 case SETUP_FINALLY:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000841 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842
843 case LOAD_FAST:
844 return 1;
845 case STORE_FAST:
846 return -1;
847 case DELETE_FAST:
848 return 0;
849
850 case RAISE_VARARGS:
851 return -oparg;
852#define NARGS(o) (((o) % 256) + 2*((o) / 256))
853 case CALL_FUNCTION:
854 return -NARGS(oparg);
855 case CALL_FUNCTION_VAR:
856 case CALL_FUNCTION_KW:
857 return -NARGS(oparg)-1;
858 case CALL_FUNCTION_VAR_KW:
859 return -NARGS(oparg)-2;
860#undef NARGS
861 case MAKE_FUNCTION:
862 return -oparg;
863 case BUILD_SLICE:
864 if (oparg == 3)
865 return -2;
866 else
867 return -1;
868
869 case MAKE_CLOSURE:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000870 return -oparg-1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871 case LOAD_CLOSURE:
872 return 1;
873 case LOAD_DEREF:
874 return 1;
875 case STORE_DEREF:
876 return -1;
877 default:
878 fprintf(stderr, "opcode = %d\n", opcode);
879 Py_FatalError("opcode_stack_effect()");
880
881 }
882 return 0; /* not reachable */
883}
884
885/* Add an opcode with no argument.
886 Returns 0 on failure, 1 on success.
887*/
888
889static int
890compiler_addop(struct compiler *c, int opcode)
891{
892 basicblock *b;
893 struct instr *i;
894 int off;
895 off = compiler_next_instr(c, c->u->u_curblock);
896 if (off < 0)
897 return 0;
898 b = c->u->u_curblock;
899 i = &b->b_instr[off];
900 i->i_opcode = opcode;
901 i->i_hasarg = 0;
902 if (opcode == RETURN_VALUE)
903 b->b_return = 1;
904 compiler_set_lineno(c, off);
905 return 1;
906}
907
908static int
909compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
910{
911 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912 Py_ssize_t arg;
Mark Dickinson105be772008-01-31 22:17:37 +0000913 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000915 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000916 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
917 if (PyFloat_Check(o)) {
Mark Dickinson105be772008-01-31 22:17:37 +0000918 d = PyFloat_AS_DOUBLE(o);
Mark Dickinson105be772008-01-31 22:17:37 +0000919 /* all we need is to make the tuple different in either the 0.0
920 * or -0.0 case from all others, just to avoid the "coercion".
921 */
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000922 if (d == 0.0 && copysign(1.0, d) < 0.0)
Mark Dickinson105be772008-01-31 22:17:37 +0000923 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
924 else
925 t = PyTuple_Pack(2, o, o->ob_type);
926 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000927#ifndef WITHOUT_COMPLEX
Mark Dickinson105be772008-01-31 22:17:37 +0000928 else if (PyComplex_Check(o)) {
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000929 Py_complex z;
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000930 int real_negzero, imag_negzero;
931 /* For the complex case we must make complex(x, 0.)
932 different from complex(x, -0.) and complex(0., y)
933 different from complex(-0., y), for any x and y.
934 All four complex zeros must be distinguished.*/
Mark Dickinson105be772008-01-31 22:17:37 +0000935 z = PyComplex_AsCComplex(o);
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000936 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
937 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
938 if (real_negzero && imag_negzero) {
939 t = PyTuple_Pack(5, o, o->ob_type,
940 Py_None, Py_None, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000941 }
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000942 else if (imag_negzero) {
943 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000944 }
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000945 else if (real_negzero) {
946 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000947 }
948 else {
949 t = PyTuple_Pack(2, o, o->ob_type);
950 }
951 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000952#endif /* WITHOUT_COMPLEX */
Mark Dickinson105be772008-01-31 22:17:37 +0000953 else {
954 t = PyTuple_Pack(2, o, o->ob_type);
Alex Martellid8672aa2007-08-22 21:14:17 +0000955 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000956 if (t == NULL)
Mark Dickinson105be772008-01-31 22:17:37 +0000957 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000958
959 v = PyDict_GetItem(dict, t);
960 if (!v) {
961 arg = PyDict_Size(dict);
962 v = PyInt_FromLong(arg);
963 if (!v) {
964 Py_DECREF(t);
965 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000966 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000967 if (PyDict_SetItem(dict, t, v) < 0) {
968 Py_DECREF(t);
969 Py_DECREF(v);
970 return -1;
971 }
972 Py_DECREF(v);
973 }
974 else
975 arg = PyInt_AsLong(v);
976 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000977 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978}
979
980static int
981compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
982 PyObject *o)
983{
984 int arg = compiler_add_o(c, dict, o);
985 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987 return compiler_addop_i(c, opcode, arg);
988}
989
990static int
991compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000992 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993{
994 int arg;
995 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
996 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000997 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998 arg = compiler_add_o(c, dict, mangled);
999 Py_DECREF(mangled);
1000 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001001 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001002 return compiler_addop_i(c, opcode, arg);
1003}
1004
1005/* Add an opcode with an integer argument.
1006 Returns 0 on failure, 1 on success.
1007*/
1008
1009static int
1010compiler_addop_i(struct compiler *c, int opcode, int oparg)
1011{
1012 struct instr *i;
1013 int off;
1014 off = compiler_next_instr(c, c->u->u_curblock);
1015 if (off < 0)
1016 return 0;
1017 i = &c->u->u_curblock->b_instr[off];
1018 i->i_opcode = opcode;
1019 i->i_oparg = oparg;
1020 i->i_hasarg = 1;
1021 compiler_set_lineno(c, off);
1022 return 1;
1023}
1024
1025static int
1026compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1027{
1028 struct instr *i;
1029 int off;
1030
1031 assert(b != NULL);
1032 off = compiler_next_instr(c, c->u->u_curblock);
1033 if (off < 0)
1034 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035 i = &c->u->u_curblock->b_instr[off];
1036 i->i_opcode = opcode;
1037 i->i_target = b;
1038 i->i_hasarg = 1;
1039 if (absolute)
1040 i->i_jabs = 1;
1041 else
1042 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001043 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044 return 1;
1045}
1046
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001047/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1048 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049 it as the current block. NEXT_BLOCK() also creates an implicit jump
1050 from the current block to the new block.
1051*/
1052
Neal Norwitzf733a012006-10-29 18:30:10 +00001053/* The returns inside these macros make it impossible to decref objects
1054 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055*/
1056
1057
1058#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001059 if (compiler_use_new_block((C)) == NULL) \
1060 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061}
1062
1063#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001064 if (compiler_next_block((C)) == NULL) \
1065 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066}
1067
1068#define ADDOP(C, OP) { \
1069 if (!compiler_addop((C), (OP))) \
1070 return 0; \
1071}
1072
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001073#define ADDOP_IN_SCOPE(C, OP) { \
1074 if (!compiler_addop((C), (OP))) { \
1075 compiler_exit_scope(c); \
1076 return 0; \
1077 } \
1078}
1079
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080#define ADDOP_O(C, OP, O, TYPE) { \
1081 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1082 return 0; \
1083}
1084
1085#define ADDOP_NAME(C, OP, O, TYPE) { \
1086 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1087 return 0; \
1088}
1089
1090#define ADDOP_I(C, OP, O) { \
1091 if (!compiler_addop_i((C), (OP), (O))) \
1092 return 0; \
1093}
1094
1095#define ADDOP_JABS(C, OP, O) { \
1096 if (!compiler_addop_j((C), (OP), (O), 1)) \
1097 return 0; \
1098}
1099
1100#define ADDOP_JREL(C, OP, O) { \
1101 if (!compiler_addop_j((C), (OP), (O), 0)) \
1102 return 0; \
1103}
1104
1105/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1106 the ASDL name to synthesize the name of the C type and the visit function.
1107*/
1108
1109#define VISIT(C, TYPE, V) {\
1110 if (!compiler_visit_ ## TYPE((C), (V))) \
1111 return 0; \
1112}
1113
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001114#define VISIT_IN_SCOPE(C, TYPE, V) {\
1115 if (!compiler_visit_ ## TYPE((C), (V))) { \
1116 compiler_exit_scope(c); \
1117 return 0; \
1118 } \
1119}
1120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121#define VISIT_SLICE(C, V, CTX) {\
1122 if (!compiler_visit_slice((C), (V), (CTX))) \
1123 return 0; \
1124}
1125
1126#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001127 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001129 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001130 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001131 if (!compiler_visit_ ## TYPE((C), elt)) \
1132 return 0; \
1133 } \
1134}
1135
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001136#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001137 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001138 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001139 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001140 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001141 if (!compiler_visit_ ## TYPE((C), elt)) { \
1142 compiler_exit_scope(c); \
1143 return 0; \
1144 } \
1145 } \
1146}
1147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148static int
1149compiler_isdocstring(stmt_ty s)
1150{
1151 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001152 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 return s->v.Expr.value->kind == Str_kind;
1154}
1155
1156/* Compile a sequence of statements, checking for a docstring. */
1157
1158static int
1159compiler_body(struct compiler *c, asdl_seq *stmts)
1160{
1161 int i = 0;
1162 stmt_ty st;
1163
1164 if (!asdl_seq_LEN(stmts))
1165 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001166 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001167 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1168 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 i = 1;
1170 VISIT(c, expr, st->v.Expr.value);
1171 if (!compiler_nameop(c, __doc__, Store))
1172 return 0;
1173 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001174 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001175 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 return 1;
1177}
1178
1179static PyCodeObject *
1180compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001181{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001182 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001183 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 static PyObject *module;
1185 if (!module) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001186 module = PyString_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187 if (!module)
1188 return NULL;
1189 }
Neal Norwitzed657552006-07-10 00:04:44 +00001190 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1191 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001192 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 switch (mod->kind) {
1194 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001195 if (!compiler_body(c, mod->v.Module.body)) {
1196 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 break;
1200 case Interactive_kind:
1201 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001202 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001203 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 break;
1205 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001206 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001207 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 break;
1209 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001210 PyErr_SetString(PyExc_SystemError,
1211 "suite should not be possible");
1212 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001213 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001214 PyErr_Format(PyExc_SystemError,
1215 "module kind %d should not be possible",
1216 mod->kind);
1217 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219 co = assemble(c, addNone);
1220 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001221 return co;
1222}
1223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224/* The test for LOCAL must come before the test for FREE in order to
1225 handle classes where name is both local and free. The local var is
1226 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001227*/
1228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229static int
1230get_ref_type(struct compiler *c, PyObject *name)
1231{
1232 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001233 if (scope == 0) {
1234 char buf[350];
1235 PyOS_snprintf(buf, sizeof(buf),
1236 "unknown scope for %.100s in %.100s(%s) in %s\n"
Amaury Forgeot d'Arc59ce0422009-01-17 20:18:59 +00001237 "symbols: %s\nlocals: %s\nglobals: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001238 PyString_AS_STRING(name),
1239 PyString_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001240 PyObject_REPR(c->u->u_ste->ste_id),
1241 c->c_filename,
1242 PyObject_REPR(c->u->u_ste->ste_symbols),
1243 PyObject_REPR(c->u->u_varnames),
1244 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001246 Py_FatalError(buf);
1247 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001248
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001249 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252static int
1253compiler_lookup_arg(PyObject *dict, PyObject *name)
1254{
1255 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001256 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001258 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001260 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001262 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 return PyInt_AS_LONG(v);
1264}
1265
1266static int
1267compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1268{
1269 int i, free = PyCode_GetNumFree(co);
1270 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001271 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1272 ADDOP_I(c, MAKE_FUNCTION, args);
1273 return 1;
1274 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275 for (i = 0; i < free; ++i) {
1276 /* Bypass com_addop_varname because it will generate
1277 LOAD_DEREF but LOAD_CLOSURE is needed.
1278 */
1279 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1280 int arg, reftype;
1281
1282 /* Special case: If a class contains a method with a
1283 free variable that has the same name as a method,
1284 the name will be considered free *and* local in the
1285 class. It should be handled by the closure, as
1286 well as by the normal name loookup logic.
1287 */
1288 reftype = get_ref_type(c, name);
1289 if (reftype == CELL)
1290 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1291 else /* (reftype == FREE) */
1292 arg = compiler_lookup_arg(c->u->u_freevars, name);
1293 if (arg == -1) {
1294 printf("lookup %s in %s %d %d\n"
1295 "freevars of %s: %s\n",
1296 PyObject_REPR(name),
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001297 PyString_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298 reftype, arg,
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001299 PyString_AS_STRING(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300 PyObject_REPR(co->co_freevars));
1301 Py_FatalError("compiler_make_closure()");
1302 }
1303 ADDOP_I(c, LOAD_CLOSURE, arg);
1304 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001305 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, MAKE_CLOSURE, args);
1308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
1311static int
1312compiler_decorators(struct compiler *c, asdl_seq* decos)
1313{
1314 int i;
1315
1316 if (!decos)
1317 return 1;
1318
1319 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001320 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321 }
1322 return 1;
1323}
1324
1325static int
1326compiler_arguments(struct compiler *c, arguments_ty args)
1327{
1328 int i;
1329 int n = asdl_seq_LEN(args->args);
1330 /* Correctly handle nested argument lists */
1331 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001332 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 if (arg->kind == Tuple_kind) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001334 PyObject *id = PyString_FromFormat(".%d", i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 if (id == NULL) {
1336 return 0;
1337 }
1338 if (!compiler_nameop(c, id, Load)) {
1339 Py_DECREF(id);
1340 return 0;
1341 }
1342 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001343 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 }
1345 }
1346 return 1;
1347}
1348
1349static int
1350compiler_function(struct compiler *c, stmt_ty s)
1351{
1352 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001353 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 arguments_ty args = s->v.FunctionDef.args;
Christian Heimes5224d282008-02-23 15:01:05 +00001355 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001356 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 int i, n, docstring;
1358
1359 assert(s->kind == FunctionDef_kind);
1360
1361 if (!compiler_decorators(c, decos))
1362 return 0;
1363 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001364 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1366 s->lineno))
1367 return 0;
1368
Anthony Baxter7b782b62006-04-11 12:01:56 +00001369 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001370 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001371 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001372 first_const = st->v.Expr.value->v.Str.s;
1373 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001374 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001375 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001378 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 compiler_arguments(c, args);
1380
1381 c->u->u_argcount = asdl_seq_LEN(args->args);
1382 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001383 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001385 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1386 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387 }
1388 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001389 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390 if (co == NULL)
1391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001393 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001394 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395
1396 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1397 ADDOP_I(c, CALL_FUNCTION, 1);
1398 }
1399
1400 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1401}
1402
1403static int
1404compiler_class(struct compiler *c, stmt_ty s)
1405{
Christian Heimes5224d282008-02-23 15:01:05 +00001406 int n, i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001408 PyObject *str;
Christian Heimes5224d282008-02-23 15:01:05 +00001409 asdl_seq* decos = s->v.ClassDef.decorator_list;
1410
1411 if (!compiler_decorators(c, decos))
1412 return 0;
1413
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414 /* push class name on stack, needed by BUILD_CLASS */
1415 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1416 /* push the tuple of base classes on the stack */
1417 n = asdl_seq_LEN(s->v.ClassDef.bases);
1418 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001419 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420 ADDOP_I(c, BUILD_TUPLE, n);
1421 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1422 s->lineno))
1423 return 0;
Amaury Forgeot d'Arc69b747b2008-03-28 20:30:50 +00001424 Py_XDECREF(c->u->u_private);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001425 c->u->u_private = s->v.ClassDef.name;
1426 Py_INCREF(c->u->u_private);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001427 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428 if (!str || !compiler_nameop(c, str, Load)) {
1429 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001430 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001432 }
1433
1434 Py_DECREF(str);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001435 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436 if (!str || !compiler_nameop(c, str, Store)) {
1437 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001438 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001440 }
1441 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001443 if (!compiler_body(c, s->v.ClassDef.body)) {
1444 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001446 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001448 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1449 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001451 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452 if (co == NULL)
1453 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001455 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001456 Py_DECREF(co);
1457
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458 ADDOP_I(c, CALL_FUNCTION, 0);
1459 ADDOP(c, BUILD_CLASS);
Christian Heimes5224d282008-02-23 15:01:05 +00001460 /* apply decorators */
1461 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1462 ADDOP_I(c, CALL_FUNCTION, 1);
1463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1465 return 0;
1466 return 1;
1467}
1468
1469static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001470compiler_ifexp(struct compiler *c, expr_ty e)
1471{
1472 basicblock *end, *next;
1473
1474 assert(e->kind == IfExp_kind);
1475 end = compiler_new_block(c);
1476 if (end == NULL)
1477 return 0;
1478 next = compiler_new_block(c);
1479 if (next == NULL)
1480 return 0;
1481 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001482 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001483 VISIT(c, expr, e->v.IfExp.body);
1484 ADDOP_JREL(c, JUMP_FORWARD, end);
1485 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001486 VISIT(c, expr, e->v.IfExp.orelse);
1487 compiler_use_next_block(c, end);
1488 return 1;
1489}
1490
1491static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492compiler_lambda(struct compiler *c, expr_ty e)
1493{
1494 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001495 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496 arguments_ty args = e->v.Lambda.args;
1497 assert(e->kind == Lambda_kind);
1498
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001499 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001500 name = PyString_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001501 if (!name)
1502 return 0;
1503 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504
1505 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001506 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1508 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001509
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001510 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511 compiler_arguments(c, args);
1512
1513 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001514 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson8d5934b2008-12-27 18:24:11 +00001515 if (c->u->u_ste->ste_generator) {
1516 ADDOP_IN_SCOPE(c, POP_TOP);
1517 }
1518 else {
1519 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1520 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001522 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523 if (co == NULL)
1524 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001526 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001527 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528
1529 return 1;
1530}
1531
1532static int
1533compiler_print(struct compiler *c, stmt_ty s)
1534{
1535 int i, n;
1536 bool dest;
1537
1538 assert(s->kind == Print_kind);
1539 n = asdl_seq_LEN(s->v.Print.values);
1540 dest = false;
1541 if (s->v.Print.dest) {
1542 VISIT(c, expr, s->v.Print.dest);
1543 dest = true;
1544 }
1545 for (i = 0; i < n; i++) {
1546 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1547 if (dest) {
1548 ADDOP(c, DUP_TOP);
1549 VISIT(c, expr, e);
1550 ADDOP(c, ROT_TWO);
1551 ADDOP(c, PRINT_ITEM_TO);
1552 }
1553 else {
1554 VISIT(c, expr, e);
1555 ADDOP(c, PRINT_ITEM);
1556 }
1557 }
1558 if (s->v.Print.nl) {
1559 if (dest)
1560 ADDOP(c, PRINT_NEWLINE_TO)
1561 else
1562 ADDOP(c, PRINT_NEWLINE)
1563 }
1564 else if (dest)
1565 ADDOP(c, POP_TOP);
1566 return 1;
1567}
1568
1569static int
1570compiler_if(struct compiler *c, stmt_ty s)
1571{
1572 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001573 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001574 assert(s->kind == If_kind);
1575 end = compiler_new_block(c);
1576 if (end == NULL)
1577 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001578
1579 constant = expr_constant(s->v.If.test);
1580 /* constant = 0: "if 0"
1581 * constant = 1: "if 1", "if 2", ...
1582 * constant = -1: rest */
1583 if (constant == 0) {
1584 if (s->v.If.orelse)
1585 VISIT_SEQ(c, stmt, s->v.If.orelse);
1586 } else if (constant == 1) {
1587 VISIT_SEQ(c, stmt, s->v.If.body);
1588 } else {
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001589 if (s->v.If.orelse) {
1590 next = compiler_new_block(c);
1591 if (next == NULL)
1592 return 0;
1593 }
1594 else
1595 next = end;
Georg Brandlddbaa662006-06-04 21:56:52 +00001596 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001597 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Georg Brandlddbaa662006-06-04 21:56:52 +00001598 VISIT_SEQ(c, stmt, s->v.If.body);
1599 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001600 if (s->v.If.orelse) {
1601 compiler_use_next_block(c, next);
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001602 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001603 }
Georg Brandlddbaa662006-06-04 21:56:52 +00001604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001605 compiler_use_next_block(c, end);
1606 return 1;
1607}
1608
1609static int
1610compiler_for(struct compiler *c, stmt_ty s)
1611{
1612 basicblock *start, *cleanup, *end;
1613
1614 start = compiler_new_block(c);
1615 cleanup = compiler_new_block(c);
1616 end = compiler_new_block(c);
1617 if (start == NULL || end == NULL || cleanup == NULL)
1618 return 0;
1619 ADDOP_JREL(c, SETUP_LOOP, end);
1620 if (!compiler_push_fblock(c, LOOP, start))
1621 return 0;
1622 VISIT(c, expr, s->v.For.iter);
1623 ADDOP(c, GET_ITER);
1624 compiler_use_next_block(c, start);
1625 ADDOP_JREL(c, FOR_ITER, cleanup);
1626 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001627 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1629 compiler_use_next_block(c, cleanup);
1630 ADDOP(c, POP_BLOCK);
1631 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001632 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633 compiler_use_next_block(c, end);
1634 return 1;
1635}
1636
1637static int
1638compiler_while(struct compiler *c, stmt_ty s)
1639{
1640 basicblock *loop, *orelse, *end, *anchor = NULL;
1641 int constant = expr_constant(s->v.While.test);
1642
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001643 if (constant == 0) {
1644 if (s->v.While.orelse)
1645 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646 return 1;
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001647 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001648 loop = compiler_new_block(c);
1649 end = compiler_new_block(c);
1650 if (constant == -1) {
1651 anchor = compiler_new_block(c);
1652 if (anchor == NULL)
1653 return 0;
1654 }
1655 if (loop == NULL || end == NULL)
1656 return 0;
1657 if (s->v.While.orelse) {
1658 orelse = compiler_new_block(c);
1659 if (orelse == NULL)
1660 return 0;
1661 }
1662 else
1663 orelse = NULL;
1664
1665 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001666 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667 if (!compiler_push_fblock(c, LOOP, loop))
1668 return 0;
1669 if (constant == -1) {
1670 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001671 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001672 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001673 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1675
1676 /* XXX should the two POP instructions be in a separate block
1677 if there is no else clause ?
1678 */
1679
1680 if (constant == -1) {
1681 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 ADDOP(c, POP_BLOCK);
1683 }
1684 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001685 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001686 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687 compiler_use_next_block(c, end);
1688
1689 return 1;
1690}
1691
1692static int
1693compiler_continue(struct compiler *c)
1694{
1695 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001696 static const char IN_FINALLY_ERROR_MSG[] =
1697 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698 int i;
1699
1700 if (!c->u->u_nfblocks)
1701 return compiler_error(c, LOOP_ERROR_MSG);
1702 i = c->u->u_nfblocks - 1;
1703 switch (c->u->u_fblock[i].fb_type) {
1704 case LOOP:
1705 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1706 break;
1707 case EXCEPT:
1708 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001709 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1710 /* Prevent continue anywhere under a finally
1711 even if hidden in a sub-try or except. */
1712 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1713 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1714 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715 if (i == -1)
1716 return compiler_error(c, LOOP_ERROR_MSG);
1717 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1718 break;
1719 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001720 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001721 }
1722
1723 return 1;
1724}
1725
1726/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1727
1728 SETUP_FINALLY L
1729 <code for body>
1730 POP_BLOCK
1731 LOAD_CONST <None>
1732 L: <code for finalbody>
1733 END_FINALLY
1734
1735 The special instructions use the block stack. Each block
1736 stack entry contains the instruction that created it (here
1737 SETUP_FINALLY), the level of the value stack at the time the
1738 block stack entry was created, and a label (here L).
1739
1740 SETUP_FINALLY:
1741 Pushes the current value stack level and the label
1742 onto the block stack.
1743 POP_BLOCK:
1744 Pops en entry from the block stack, and pops the value
1745 stack until its level is the same as indicated on the
1746 block stack. (The label is ignored.)
1747 END_FINALLY:
1748 Pops a variable number of entries from the *value* stack
1749 and re-raises the exception they specify. The number of
1750 entries popped depends on the (pseudo) exception type.
1751
1752 The block stack is unwound when an exception is raised:
1753 when a SETUP_FINALLY entry is found, the exception is pushed
1754 onto the value stack (and the exception condition is cleared),
1755 and the interpreter jumps to the label gotten from the block
1756 stack.
1757*/
1758
1759static int
1760compiler_try_finally(struct compiler *c, stmt_ty s)
1761{
1762 basicblock *body, *end;
1763 body = compiler_new_block(c);
1764 end = compiler_new_block(c);
1765 if (body == NULL || end == NULL)
1766 return 0;
1767
1768 ADDOP_JREL(c, SETUP_FINALLY, end);
1769 compiler_use_next_block(c, body);
1770 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1771 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001772 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773 ADDOP(c, POP_BLOCK);
1774 compiler_pop_fblock(c, FINALLY_TRY, body);
1775
1776 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1777 compiler_use_next_block(c, end);
1778 if (!compiler_push_fblock(c, FINALLY_END, end))
1779 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001780 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 ADDOP(c, END_FINALLY);
1782 compiler_pop_fblock(c, FINALLY_END, end);
1783
1784 return 1;
1785}
1786
1787/*
1788 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1789 (The contents of the value stack is shown in [], with the top
1790 at the right; 'tb' is trace-back info, 'val' the exception's
1791 associated value, and 'exc' the exception.)
1792
1793 Value stack Label Instruction Argument
1794 [] SETUP_EXCEPT L1
1795 [] <code for S>
1796 [] POP_BLOCK
1797 [] JUMP_FORWARD L0
1798
1799 [tb, val, exc] L1: DUP )
1800 [tb, val, exc, exc] <evaluate E1> )
1801 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001802 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803 [tb, val, exc] POP
1804 [tb, val] <assign to V1> (or POP if no V1)
1805 [tb] POP
1806 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001807 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001809 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810 .............................etc.......................
1811
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001812 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813
1814 [] L0: <next statement>
1815
1816 Of course, parts are not generated if Vi or Ei is not present.
1817*/
1818static int
1819compiler_try_except(struct compiler *c, stmt_ty s)
1820{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001821 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822 int i, n;
1823
1824 body = compiler_new_block(c);
1825 except = compiler_new_block(c);
1826 orelse = compiler_new_block(c);
1827 end = compiler_new_block(c);
1828 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1829 return 0;
1830 ADDOP_JREL(c, SETUP_EXCEPT, except);
1831 compiler_use_next_block(c, body);
1832 if (!compiler_push_fblock(c, EXCEPT, body))
1833 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001834 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001835 ADDOP(c, POP_BLOCK);
1836 compiler_pop_fblock(c, EXCEPT, body);
1837 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1838 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1839 compiler_use_next_block(c, except);
1840 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001841 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 s->v.TryExcept.handlers, i);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001843 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +00001845 c->u->u_lineno_set = false;
1846 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 except = compiler_new_block(c);
1848 if (except == NULL)
1849 return 0;
Georg Brandla48f3ab2008-03-30 06:40:17 +00001850 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851 ADDOP(c, DUP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001852 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001854 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855 }
1856 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001857 if (handler->v.ExceptHandler.name) {
1858 VISIT(c, expr, handler->v.ExceptHandler.name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 }
1860 else {
1861 ADDOP(c, POP_TOP);
1862 }
1863 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001864 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 ADDOP_JREL(c, JUMP_FORWARD, end);
1866 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 }
1868 ADDOP(c, END_FINALLY);
1869 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001870 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871 compiler_use_next_block(c, end);
1872 return 1;
1873}
1874
1875static int
1876compiler_import_as(struct compiler *c, identifier name, identifier asname)
1877{
1878 /* The IMPORT_NAME opcode was already generated. This function
1879 merely needs to bind the result to a name.
1880
1881 If there is a dot in name, we need to split it and emit a
1882 LOAD_ATTR for each name.
1883 */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001884 const char *src = PyString_AS_STRING(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885 const char *dot = strchr(src, '.');
1886 if (dot) {
1887 /* Consume the base module name to get the first attribute */
1888 src = dot + 1;
1889 while (dot) {
1890 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001891 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892 dot = strchr(src, '.');
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001893 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001895 if (!attr)
1896 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001898 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899 src = dot + 1;
1900 }
1901 }
1902 return compiler_nameop(c, asname, Store);
1903}
1904
1905static int
1906compiler_import(struct compiler *c, stmt_ty s)
1907{
1908 /* The Import node stores a module name like a.b.c as a single
1909 string. This is convenient for all cases except
1910 import a.b.c as d
1911 where we need to parse that string to extract the individual
1912 module names.
1913 XXX Perhaps change the representation to make this case simpler?
1914 */
1915 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001916
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001918 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001920 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921
Neal Norwitzcbce2802006-04-03 06:26:32 +00001922 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001923 level = PyInt_FromLong(0);
1924 else
1925 level = PyInt_FromLong(-1);
1926
1927 if (level == NULL)
1928 return 0;
1929
1930 ADDOP_O(c, LOAD_CONST, level, consts);
1931 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1933 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1934
1935 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001936 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001937 if (!r)
1938 return r;
1939 }
1940 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 identifier tmp = alias->name;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001942 const char *base = PyString_AS_STRING(alias->name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943 char *dot = strchr(base, '.');
1944 if (dot)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001945 tmp = PyString_FromStringAndSize(base,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946 dot - base);
1947 r = compiler_nameop(c, tmp, Store);
1948 if (dot) {
1949 Py_DECREF(tmp);
1950 }
1951 if (!r)
1952 return r;
1953 }
1954 }
1955 return 1;
1956}
1957
1958static int
1959compiler_from_import(struct compiler *c, stmt_ty s)
1960{
1961 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962
1963 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001964 PyObject *level;
Benjamin Petersona72be3b2009-06-13 20:23:33 +00001965 static PyObject *empty_string;
1966
1967 if (!empty_string) {
1968 empty_string = PyString_FromString("");
1969 if (!empty_string)
1970 return 0;
1971 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001972
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973 if (!names)
1974 return 0;
1975
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001976 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001977 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001978 level = PyInt_FromLong(-1);
1979 else
1980 level = PyInt_FromLong(s->v.ImportFrom.level);
1981
1982 if (!level) {
1983 Py_DECREF(names);
1984 return 0;
1985 }
1986
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 /* build up the names */
1988 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001989 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 Py_INCREF(alias->name);
1991 PyTuple_SET_ITEM(names, i, alias->name);
1992 }
1993
Benjamin Petersona72be3b2009-06-13 20:23:33 +00001994 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
1995 !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
1996 Py_DECREF(level);
1997 Py_DECREF(names);
1998 return compiler_error(c, "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001999 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000 }
2001
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002002 ADDOP_O(c, LOAD_CONST, level, consts);
2003 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002005 Py_DECREF(names);
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002006 if (s->v.ImportFrom.module) {
2007 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2008 }
2009 else {
2010 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2011 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002013 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 identifier store_name;
2015
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002016 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 assert(n == 1);
2018 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002019 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 }
2021
2022 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2023 store_name = alias->name;
2024 if (alias->asname)
2025 store_name = alias->asname;
2026
2027 if (!compiler_nameop(c, store_name, Store)) {
2028 Py_DECREF(names);
2029 return 0;
2030 }
2031 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002032 /* remove imported module */
2033 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034 return 1;
2035}
2036
2037static int
2038compiler_assert(struct compiler *c, stmt_ty s)
2039{
2040 static PyObject *assertion_error = NULL;
2041 basicblock *end;
2042
2043 if (Py_OptimizeFlag)
2044 return 1;
2045 if (assertion_error == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002046 assertion_error = PyString_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 if (assertion_error == NULL)
2048 return 0;
2049 }
Neal Norwitz400aeda2008-03-15 22:03:18 +00002050 if (s->v.Assert.test->kind == Tuple_kind &&
2051 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2052 const char* msg =
2053 "assertion is always true, perhaps remove parentheses?";
2054 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2055 c->u->u_lineno, NULL, NULL) == -1)
2056 return 0;
2057 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 VISIT(c, expr, s->v.Assert.test);
2059 end = compiler_new_block(c);
2060 if (end == NULL)
2061 return 0;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002062 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2064 if (s->v.Assert.msg) {
2065 VISIT(c, expr, s->v.Assert.msg);
2066 ADDOP_I(c, RAISE_VARARGS, 2);
2067 }
2068 else {
2069 ADDOP_I(c, RAISE_VARARGS, 1);
2070 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002071 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 return 1;
2073}
2074
2075static int
2076compiler_visit_stmt(struct compiler *c, stmt_ty s)
2077{
2078 int i, n;
2079
Neal Norwitzf733a012006-10-29 18:30:10 +00002080 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081 c->u->u_lineno = s->lineno;
2082 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002083
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002085 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002087 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 if (c->u->u_ste->ste_type != FunctionBlock)
2091 return compiler_error(c, "'return' outside function");
2092 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 VISIT(c, expr, s->v.Return.value);
2094 }
2095 else
2096 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2097 ADDOP(c, RETURN_VALUE);
2098 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002100 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002102 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 n = asdl_seq_LEN(s->v.Assign.targets);
2104 VISIT(c, expr, s->v.Assign.value);
2105 for (i = 0; i < n; i++) {
2106 if (i < n - 1)
2107 ADDOP(c, DUP_TOP);
2108 VISIT(c, expr,
2109 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2110 }
2111 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002112 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002114 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002116 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002118 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002120 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002122 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 n = 0;
2124 if (s->v.Raise.type) {
2125 VISIT(c, expr, s->v.Raise.type);
2126 n++;
2127 if (s->v.Raise.inst) {
2128 VISIT(c, expr, s->v.Raise.inst);
2129 n++;
2130 if (s->v.Raise.tback) {
2131 VISIT(c, expr, s->v.Raise.tback);
2132 n++;
2133 }
2134 }
2135 }
2136 ADDOP_I(c, RAISE_VARARGS, n);
2137 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002138 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002140 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002142 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002144 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002146 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002147 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002148 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 VISIT(c, expr, s->v.Exec.body);
2150 if (s->v.Exec.globals) {
2151 VISIT(c, expr, s->v.Exec.globals);
2152 if (s->v.Exec.locals) {
2153 VISIT(c, expr, s->v.Exec.locals);
2154 } else {
2155 ADDOP(c, DUP_TOP);
2156 }
2157 } else {
2158 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2159 ADDOP(c, DUP_TOP);
2160 }
2161 ADDOP(c, EXEC_STMT);
2162 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002163 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002165 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002167 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168 ADDOP(c, PRINT_EXPR);
2169 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002170 else if (s->v.Expr.value->kind != Str_kind &&
2171 s->v.Expr.value->kind != Num_kind) {
2172 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173 ADDOP(c, POP_TOP);
2174 }
2175 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002176 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002178 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002179 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 return compiler_error(c, "'break' outside loop");
2181 ADDOP(c, BREAK_LOOP);
2182 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002183 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002184 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002185 case With_kind:
2186 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002187 }
2188 return 1;
2189}
2190
2191static int
2192unaryop(unaryop_ty op)
2193{
2194 switch (op) {
2195 case Invert:
2196 return UNARY_INVERT;
2197 case Not:
2198 return UNARY_NOT;
2199 case UAdd:
2200 return UNARY_POSITIVE;
2201 case USub:
2202 return UNARY_NEGATIVE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002203 default:
2204 PyErr_Format(PyExc_SystemError,
2205 "unary op %d should not be possible", op);
2206 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002207 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208}
2209
2210static int
2211binop(struct compiler *c, operator_ty op)
2212{
2213 switch (op) {
2214 case Add:
2215 return BINARY_ADD;
2216 case Sub:
2217 return BINARY_SUBTRACT;
2218 case Mult:
2219 return BINARY_MULTIPLY;
2220 case Div:
2221 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2222 return BINARY_TRUE_DIVIDE;
2223 else
2224 return BINARY_DIVIDE;
2225 case Mod:
2226 return BINARY_MODULO;
2227 case Pow:
2228 return BINARY_POWER;
2229 case LShift:
2230 return BINARY_LSHIFT;
2231 case RShift:
2232 return BINARY_RSHIFT;
2233 case BitOr:
2234 return BINARY_OR;
2235 case BitXor:
2236 return BINARY_XOR;
2237 case BitAnd:
2238 return BINARY_AND;
2239 case FloorDiv:
2240 return BINARY_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002241 default:
2242 PyErr_Format(PyExc_SystemError,
2243 "binary op %d should not be possible", op);
2244 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246}
2247
2248static int
2249cmpop(cmpop_ty op)
2250{
2251 switch (op) {
2252 case Eq:
2253 return PyCmp_EQ;
2254 case NotEq:
2255 return PyCmp_NE;
2256 case Lt:
2257 return PyCmp_LT;
2258 case LtE:
2259 return PyCmp_LE;
2260 case Gt:
2261 return PyCmp_GT;
2262 case GtE:
2263 return PyCmp_GE;
2264 case Is:
2265 return PyCmp_IS;
2266 case IsNot:
2267 return PyCmp_IS_NOT;
2268 case In:
2269 return PyCmp_IN;
2270 case NotIn:
2271 return PyCmp_NOT_IN;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002272 default:
2273 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275}
2276
2277static int
2278inplace_binop(struct compiler *c, operator_ty op)
2279{
2280 switch (op) {
2281 case Add:
2282 return INPLACE_ADD;
2283 case Sub:
2284 return INPLACE_SUBTRACT;
2285 case Mult:
2286 return INPLACE_MULTIPLY;
2287 case Div:
2288 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2289 return INPLACE_TRUE_DIVIDE;
2290 else
2291 return INPLACE_DIVIDE;
2292 case Mod:
2293 return INPLACE_MODULO;
2294 case Pow:
2295 return INPLACE_POWER;
2296 case LShift:
2297 return INPLACE_LSHIFT;
2298 case RShift:
2299 return INPLACE_RSHIFT;
2300 case BitOr:
2301 return INPLACE_OR;
2302 case BitXor:
2303 return INPLACE_XOR;
2304 case BitAnd:
2305 return INPLACE_AND;
2306 case FloorDiv:
2307 return INPLACE_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002308 default:
2309 PyErr_Format(PyExc_SystemError,
2310 "inplace binary op %d should not be possible", op);
2311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313}
2314
2315static int
2316compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2317{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002318 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2320
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002321 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002322 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 /* XXX AugStore isn't used anywhere! */
2324
Neal Norwitz0031ff32008-02-25 01:45:37 +00002325 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002326 if (!mangled)
2327 return 0;
2328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 op = 0;
2330 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002331 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332 switch (scope) {
2333 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002334 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 optype = OP_DEREF;
2336 break;
2337 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002338 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339 optype = OP_DEREF;
2340 break;
2341 case LOCAL:
2342 if (c->u->u_ste->ste_type == FunctionBlock)
2343 optype = OP_FAST;
2344 break;
2345 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002346 if (c->u->u_ste->ste_type == FunctionBlock &&
2347 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348 optype = OP_GLOBAL;
2349 break;
2350 case GLOBAL_EXPLICIT:
2351 optype = OP_GLOBAL;
2352 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002353 default:
2354 /* scope can be 0 */
2355 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356 }
2357
2358 /* XXX Leave assert here, but handle __doc__ and the like better */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002359 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360
2361 switch (optype) {
2362 case OP_DEREF:
2363 switch (ctx) {
2364 case Load: op = LOAD_DEREF; break;
2365 case Store: op = STORE_DEREF; break;
2366 case AugLoad:
2367 case AugStore:
2368 break;
2369 case Del:
2370 PyErr_Format(PyExc_SyntaxError,
2371 "can not delete variable '%s' referenced "
2372 "in nested scope",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002373 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002374 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002377 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002378 PyErr_SetString(PyExc_SystemError,
2379 "param invalid for deref variable");
2380 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002381 }
2382 break;
2383 case OP_FAST:
2384 switch (ctx) {
2385 case Load: op = LOAD_FAST; break;
2386 case Store: op = STORE_FAST; break;
2387 case Del: op = DELETE_FAST; break;
2388 case AugLoad:
2389 case AugStore:
2390 break;
2391 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002392 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002393 PyErr_SetString(PyExc_SystemError,
2394 "param invalid for local variable");
2395 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002397 ADDOP_O(c, op, mangled, varnames);
2398 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399 return 1;
2400 case OP_GLOBAL:
2401 switch (ctx) {
2402 case Load: op = LOAD_GLOBAL; break;
2403 case Store: op = STORE_GLOBAL; break;
2404 case Del: op = DELETE_GLOBAL; break;
2405 case AugLoad:
2406 case AugStore:
2407 break;
2408 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002409 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002410 PyErr_SetString(PyExc_SystemError,
2411 "param invalid for global variable");
2412 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413 }
2414 break;
2415 case OP_NAME:
2416 switch (ctx) {
2417 case Load: op = LOAD_NAME; break;
2418 case Store: op = STORE_NAME; break;
2419 case Del: op = DELETE_NAME; break;
2420 case AugLoad:
2421 case AugStore:
2422 break;
2423 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002424 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002425 PyErr_SetString(PyExc_SystemError,
2426 "param invalid for name variable");
2427 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 }
2429 break;
2430 }
2431
2432 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002433 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002434 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002435 if (arg < 0)
2436 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002437 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438}
2439
2440static int
2441compiler_boolop(struct compiler *c, expr_ty e)
2442{
2443 basicblock *end;
2444 int jumpi, i, n;
2445 asdl_seq *s;
2446
2447 assert(e->kind == BoolOp_kind);
2448 if (e->v.BoolOp.op == And)
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002449 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 else
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002451 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002452 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002453 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 return 0;
2455 s = e->v.BoolOp.values;
2456 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002457 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002459 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002460 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002462 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 compiler_use_next_block(c, end);
2464 return 1;
2465}
2466
2467static int
2468compiler_list(struct compiler *c, expr_ty e)
2469{
2470 int n = asdl_seq_LEN(e->v.List.elts);
2471 if (e->v.List.ctx == Store) {
2472 ADDOP_I(c, UNPACK_SEQUENCE, n);
2473 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002474 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 if (e->v.List.ctx == Load) {
2476 ADDOP_I(c, BUILD_LIST, n);
2477 }
2478 return 1;
2479}
2480
2481static int
2482compiler_tuple(struct compiler *c, expr_ty e)
2483{
2484 int n = asdl_seq_LEN(e->v.Tuple.elts);
2485 if (e->v.Tuple.ctx == Store) {
2486 ADDOP_I(c, UNPACK_SEQUENCE, n);
2487 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002488 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 if (e->v.Tuple.ctx == Load) {
2490 ADDOP_I(c, BUILD_TUPLE, n);
2491 }
2492 return 1;
2493}
2494
2495static int
2496compiler_compare(struct compiler *c, expr_ty e)
2497{
2498 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002499 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500
2501 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2502 VISIT(c, expr, e->v.Compare.left);
2503 n = asdl_seq_LEN(e->v.Compare.ops);
2504 assert(n > 0);
2505 if (n > 1) {
2506 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002507 if (cleanup == NULL)
2508 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002509 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002510 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 }
2512 for (i = 1; i < n; i++) {
2513 ADDOP(c, DUP_TOP);
2514 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002516 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002517 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002518 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002521 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002522 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002524 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002526 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 if (n > 1) {
2528 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002529 if (end == NULL)
2530 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 ADDOP_JREL(c, JUMP_FORWARD, end);
2532 compiler_use_next_block(c, cleanup);
2533 ADDOP(c, ROT_TWO);
2534 ADDOP(c, POP_TOP);
2535 compiler_use_next_block(c, end);
2536 }
2537 return 1;
2538}
2539
2540static int
2541compiler_call(struct compiler *c, expr_ty e)
2542{
2543 int n, code = 0;
2544
2545 VISIT(c, expr, e->v.Call.func);
2546 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002547 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002549 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2551 }
2552 if (e->v.Call.starargs) {
2553 VISIT(c, expr, e->v.Call.starargs);
2554 code |= 1;
2555 }
2556 if (e->v.Call.kwargs) {
2557 VISIT(c, expr, e->v.Call.kwargs);
2558 code |= 2;
2559 }
2560 switch (code) {
2561 case 0:
2562 ADDOP_I(c, CALL_FUNCTION, n);
2563 break;
2564 case 1:
2565 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2566 break;
2567 case 2:
2568 ADDOP_I(c, CALL_FUNCTION_KW, n);
2569 break;
2570 case 3:
2571 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2572 break;
2573 }
2574 return 1;
2575}
2576
2577static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002578compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
2579 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002580{
2581 /* generate code for the iterator, then each of the ifs,
2582 and then write to the element */
2583
2584 comprehension_ty l;
2585 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002586 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587
2588 start = compiler_new_block(c);
2589 skip = compiler_new_block(c);
2590 if_cleanup = compiler_new_block(c);
2591 anchor = compiler_new_block(c);
2592
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002593 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2594 anchor == NULL)
2595 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596
Anthony Baxter7b782b62006-04-11 12:01:56 +00002597 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 VISIT(c, expr, l->iter);
2599 ADDOP(c, GET_ITER);
2600 compiler_use_next_block(c, start);
2601 ADDOP_JREL(c, FOR_ITER, anchor);
2602 NEXT_BLOCK(c);
2603 VISIT(c, expr, l->target);
2604
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002605 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 n = asdl_seq_LEN(l->ifs);
2607 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002608 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002610 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 }
2613
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitroud0c35152008-12-17 00:38:28 +00002615 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002618 /* only append after the last for generator */
2619 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002620 VISIT(c, expr, elt);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002621 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002622
2623 compiler_use_next_block(c, skip);
2624 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002625 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2627 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
2629 return 1;
2630}
2631
2632static int
2633compiler_listcomp(struct compiler *c, expr_ty e)
2634{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 assert(e->kind == ListComp_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 ADDOP_I(c, BUILD_LIST, 0);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002637 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2638 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639}
2640
2641static int
2642compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002643 asdl_seq *generators, int gen_index,
2644 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645{
2646 /* generate code for the iterator, then each of the ifs,
2647 and then write to the element */
2648
2649 comprehension_ty ge;
2650 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652
2653 start = compiler_new_block(c);
2654 skip = compiler_new_block(c);
2655 if_cleanup = compiler_new_block(c);
2656 anchor = compiler_new_block(c);
2657 end = compiler_new_block(c);
2658
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660 anchor == NULL || end == NULL)
2661 return 0;
2662
Anthony Baxter7b782b62006-04-11 12:01:56 +00002663 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 ADDOP_JREL(c, SETUP_LOOP, end);
2665 if (!compiler_push_fblock(c, LOOP, start))
2666 return 0;
2667
2668 if (gen_index == 0) {
2669 /* Receive outermost iter as an implicit argument */
2670 c->u->u_argcount = 1;
2671 ADDOP_I(c, LOAD_FAST, 0);
2672 }
2673 else {
2674 /* Sub-iter - calculate on the fly */
2675 VISIT(c, expr, ge->iter);
2676 ADDOP(c, GET_ITER);
2677 }
2678 compiler_use_next_block(c, start);
2679 ADDOP_JREL(c, FOR_ITER, anchor);
2680 NEXT_BLOCK(c);
2681 VISIT(c, expr, ge->target);
2682
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 n = asdl_seq_LEN(ge->ifs);
2685 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002686 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002688 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 NEXT_BLOCK(c);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002690 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002692 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2694 return 0;
2695
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002696 /* only append after the last 'for' generator */
2697 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 VISIT(c, expr, elt);
2699 ADDOP(c, YIELD_VALUE);
2700 ADDOP(c, POP_TOP);
2701
2702 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002703 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002704 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2706 compiler_use_next_block(c, anchor);
2707 ADDOP(c, POP_BLOCK);
2708 compiler_pop_fblock(c, LOOP, start);
2709 compiler_use_next_block(c, end);
2710
2711 return 1;
2712}
2713
2714static int
2715compiler_genexp(struct compiler *c, expr_ty e)
2716{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002717 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 PyCodeObject *co;
2719 expr_ty outermost_iter = ((comprehension_ty)
2720 (asdl_seq_GET(e->v.GeneratorExp.generators,
2721 0)))->iter;
2722
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002723 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002724 name = PyString_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002725 if (!name)
2726 return 0;
2727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728
2729 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2730 return 0;
2731 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2732 e->v.GeneratorExp.elt);
2733 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002734 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 if (co == NULL)
2736 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002738 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002739 Py_DECREF(co);
2740
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741 VISIT(c, expr, outermost_iter);
2742 ADDOP(c, GET_ITER);
2743 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
2745 return 1;
2746}
2747
2748static int
2749compiler_visit_keyword(struct compiler *c, keyword_ty k)
2750{
2751 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2752 VISIT(c, expr, k->value);
2753 return 1;
2754}
2755
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002756/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 whether they are true or false.
2758
2759 Return values: 1 for true, 0 for false, -1 for non-constant.
2760 */
2761
2762static int
2763expr_constant(expr_ty e)
2764{
2765 switch (e->kind) {
2766 case Num_kind:
2767 return PyObject_IsTrue(e->v.Num.n);
2768 case Str_kind:
2769 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002770 case Name_kind:
2771 /* __debug__ is not assignable, so we can optimize
2772 * it away in if and while statements */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002773 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002774 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002775 return ! Py_OptimizeFlag;
2776 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777 default:
2778 return -1;
2779 }
2780}
2781
Guido van Rossumc2e20742006-02-27 22:32:47 +00002782/*
2783 Implements the with statement from PEP 343.
2784
2785 The semantics outlined in that PEP are as follows:
2786
2787 with EXPR as VAR:
2788 BLOCK
2789
2790 It is implemented roughly as:
2791
Guido van Rossumda5b7012006-05-02 19:47:52 +00002792 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002793 exit = context.__exit__ # not calling it
2794 value = context.__enter__()
2795 try:
2796 VAR = value # if VAR present in the syntax
2797 BLOCK
2798 finally:
2799 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002800 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002802 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002803 exit(*exc)
2804 */
2805static int
2806compiler_with(struct compiler *c, stmt_ty s)
2807{
Guido van Rossumc2e20742006-02-27 22:32:47 +00002808 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002809
2810 assert(s->kind == With_kind);
2811
Guido van Rossumc2e20742006-02-27 22:32:47 +00002812 block = compiler_new_block(c);
2813 finally = compiler_new_block(c);
2814 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002816
Guido van Rossumda5b7012006-05-02 19:47:52 +00002817 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002818 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002819 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002820
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002821 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002822 compiler_use_next_block(c, block);
2823 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002824 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002825 }
2826
2827 if (s->v.With.optional_vars) {
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002828 VISIT(c, expr, s->v.With.optional_vars);
2829 }
2830 else {
2831 /* Discard result from context.__enter__() */
2832 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002833 }
2834
2835 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002836 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002837
2838 /* End of try block; start the finally block */
2839 ADDOP(c, POP_BLOCK);
2840 compiler_pop_fblock(c, FINALLY_TRY, block);
2841
2842 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2843 compiler_use_next_block(c, finally);
2844 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002846
Nick Coghlan7af53be2008-03-07 14:13:28 +00002847 /* Finally block starts; context.__exit__ is on the stack under
2848 the exception or return information. Just issue our magic
2849 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002850 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851
2852 /* Finally block ends. */
2853 ADDOP(c, END_FINALLY);
2854 compiler_pop_fblock(c, FINALLY_END, finally);
2855 return 1;
2856}
2857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858static int
2859compiler_visit_expr(struct compiler *c, expr_ty e)
2860{
2861 int i, n;
2862
Neal Norwitzf733a012006-10-29 18:30:10 +00002863 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002864 set a new line number for the next instruction.
2865 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866 if (e->lineno > c->u->u_lineno) {
2867 c->u->u_lineno = e->lineno;
2868 c->u->u_lineno_set = false;
2869 }
2870 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002871 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002873 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874 VISIT(c, expr, e->v.BinOp.left);
2875 VISIT(c, expr, e->v.BinOp.right);
2876 ADDOP(c, binop(c, e->v.BinOp.op));
2877 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002878 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879 VISIT(c, expr, e->v.UnaryOp.operand);
2880 ADDOP(c, unaryop(e->v.UnaryOp.op));
2881 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002882 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002884 case IfExp_kind:
2885 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002886 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettinger70fcfd02007-12-19 22:14:34 +00002888 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002890 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002891 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00002892 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002893 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00002894 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895 }
2896 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002897 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002899 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002900 return compiler_genexp(c, e);
2901 case Yield_kind:
2902 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002903 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904 if (e->v.Yield.value) {
2905 VISIT(c, expr, e->v.Yield.value);
2906 }
2907 else {
2908 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2909 }
2910 ADDOP(c, YIELD_VALUE);
2911 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002912 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002913 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002914 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002916 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002917 VISIT(c, expr, e->v.Repr.value);
2918 ADDOP(c, UNARY_CONVERT);
2919 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002920 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2922 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002923 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2925 break;
2926 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002927 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928 if (e->v.Attribute.ctx != AugStore)
2929 VISIT(c, expr, e->v.Attribute.value);
2930 switch (e->v.Attribute.ctx) {
2931 case AugLoad:
2932 ADDOP(c, DUP_TOP);
2933 /* Fall through to load */
2934 case Load:
2935 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2936 break;
2937 case AugStore:
2938 ADDOP(c, ROT_TWO);
2939 /* Fall through to save */
2940 case Store:
2941 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2942 break;
2943 case Del:
2944 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2945 break;
2946 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002947 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002948 PyErr_SetString(PyExc_SystemError,
2949 "param invalid in attribute expression");
2950 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 }
2952 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002953 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 switch (e->v.Subscript.ctx) {
2955 case AugLoad:
2956 VISIT(c, expr, e->v.Subscript.value);
2957 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2958 break;
2959 case Load:
2960 VISIT(c, expr, e->v.Subscript.value);
2961 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2962 break;
2963 case AugStore:
2964 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2965 break;
2966 case Store:
2967 VISIT(c, expr, e->v.Subscript.value);
2968 VISIT_SLICE(c, e->v.Subscript.slice, Store);
2969 break;
2970 case Del:
2971 VISIT(c, expr, e->v.Subscript.value);
2972 VISIT_SLICE(c, e->v.Subscript.slice, Del);
2973 break;
2974 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002975 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002976 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002977 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00002978 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979 }
2980 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
2983 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002984 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002986 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987 return compiler_tuple(c, e);
2988 }
2989 return 1;
2990}
2991
2992static int
2993compiler_augassign(struct compiler *c, stmt_ty s)
2994{
2995 expr_ty e = s->v.AugAssign.target;
2996 expr_ty auge;
2997
2998 assert(s->kind == AugAssign_kind);
2999
3000 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003001 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003002 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003003 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003004 if (auge == NULL)
3005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006 VISIT(c, expr, auge);
3007 VISIT(c, expr, s->v.AugAssign.value);
3008 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3009 auge->v.Attribute.ctx = AugStore;
3010 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011 break;
3012 case Subscript_kind:
3013 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003014 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003015 if (auge == NULL)
3016 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 VISIT(c, expr, auge);
3018 VISIT(c, expr, s->v.AugAssign.value);
3019 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003020 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003022 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003024 if (!compiler_nameop(c, e->v.Name.id, Load))
3025 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003026 VISIT(c, expr, s->v.AugAssign.value);
3027 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3028 return compiler_nameop(c, e->v.Name.id, Store);
3029 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003030 PyErr_Format(PyExc_SystemError,
3031 "invalid node type (%d) for augmented assignment",
3032 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034 }
3035 return 1;
3036}
3037
3038static int
3039compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3040{
3041 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003042 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3043 PyErr_SetString(PyExc_SystemError,
3044 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003046 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 f = &c->u->u_fblock[c->u->u_nfblocks++];
3048 f->fb_type = t;
3049 f->fb_block = b;
3050 return 1;
3051}
3052
3053static void
3054compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3055{
3056 struct compiler_unit *u = c->u;
3057 assert(u->u_nfblocks > 0);
3058 u->u_nfblocks--;
3059 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3060 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3061}
3062
Jeremy Hylton82271f12006-10-04 02:24:52 +00003063static int
3064compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003065 int i;
3066 struct compiler_unit *u = c->u;
3067 for (i = 0; i < u->u_nfblocks; ++i) {
3068 if (u->u_fblock[i].fb_type == LOOP)
3069 return 1;
3070 }
3071 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003072}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073/* Raises a SyntaxError and returns 0.
3074 If something goes wrong, a different exception may be raised.
3075*/
3076
3077static int
3078compiler_error(struct compiler *c, const char *errstr)
3079{
3080 PyObject *loc;
3081 PyObject *u = NULL, *v = NULL;
3082
3083 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3084 if (!loc) {
3085 Py_INCREF(Py_None);
3086 loc = Py_None;
3087 }
3088 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3089 Py_None, loc);
3090 if (!u)
3091 goto exit;
3092 v = Py_BuildValue("(zO)", errstr, u);
3093 if (!v)
3094 goto exit;
3095 PyErr_SetObject(PyExc_SyntaxError, v);
3096 exit:
3097 Py_DECREF(loc);
3098 Py_XDECREF(u);
3099 Py_XDECREF(v);
3100 return 0;
3101}
3102
3103static int
3104compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003105 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003107 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003109 /* XXX this code is duplicated */
3110 switch (ctx) {
3111 case AugLoad: /* fall through to Load */
3112 case Load: op = BINARY_SUBSCR; break;
3113 case AugStore:/* fall through to Store */
3114 case Store: op = STORE_SUBSCR; break;
3115 case Del: op = DELETE_SUBSCR; break;
3116 case Param:
3117 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003118 "invalid %s kind %d in subscript\n",
3119 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003120 return 0;
3121 }
3122 if (ctx == AugLoad) {
3123 ADDOP_I(c, DUP_TOPX, 2);
3124 }
3125 else if (ctx == AugStore) {
3126 ADDOP(c, ROT_THREE);
3127 }
3128 ADDOP(c, op);
3129 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130}
3131
3132static int
3133compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3134{
3135 int n = 2;
3136 assert(s->kind == Slice_kind);
3137
3138 /* only handles the cases where BUILD_SLICE is emitted */
3139 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003140 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141 }
3142 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003143 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 }
3149 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151 }
3152
3153 if (s->v.Slice.step) {
3154 n++;
3155 VISIT(c, expr, s->v.Slice.step);
3156 }
3157 ADDOP_I(c, BUILD_SLICE, n);
3158 return 1;
3159}
3160
3161static int
3162compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3163{
3164 int op = 0, slice_offset = 0, stack_count = 0;
3165
3166 assert(s->v.Slice.step == NULL);
3167 if (s->v.Slice.lower) {
3168 slice_offset++;
3169 stack_count++;
3170 if (ctx != AugStore)
3171 VISIT(c, expr, s->v.Slice.lower);
3172 }
3173 if (s->v.Slice.upper) {
3174 slice_offset += 2;
3175 stack_count++;
3176 if (ctx != AugStore)
3177 VISIT(c, expr, s->v.Slice.upper);
3178 }
3179
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003180 if (ctx == AugLoad) {
3181 switch (stack_count) {
3182 case 0: ADDOP(c, DUP_TOP); break;
3183 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3184 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3185 }
3186 }
3187 else if (ctx == AugStore) {
3188 switch (stack_count) {
3189 case 0: ADDOP(c, ROT_TWO); break;
3190 case 1: ADDOP(c, ROT_THREE); break;
3191 case 2: ADDOP(c, ROT_FOUR); break;
3192 }
3193 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194
3195 switch (ctx) {
3196 case AugLoad: /* fall through to Load */
3197 case Load: op = SLICE; break;
3198 case AugStore:/* fall through to Store */
3199 case Store: op = STORE_SLICE; break;
3200 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003201 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003202 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003203 PyErr_SetString(PyExc_SystemError,
3204 "param invalid in simple slice");
3205 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 }
3207
3208 ADDOP(c, op + slice_offset);
3209 return 1;
3210}
3211
3212static int
3213compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3214 expr_context_ty ctx)
3215{
3216 switch (s->kind) {
3217 case Ellipsis_kind:
3218 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3219 break;
3220 case Slice_kind:
3221 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 case Index_kind:
3223 VISIT(c, expr, s->v.Index.value);
3224 break;
3225 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003226 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003227 PyErr_SetString(PyExc_SystemError,
3228 "extended slice invalid in nested slice");
3229 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 }
3231 return 1;
3232}
3233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234static int
3235compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3236{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003237 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003239 case Index_kind:
3240 kindname = "index";
3241 if (ctx != AugStore) {
3242 VISIT(c, expr, s->v.Index.value);
3243 }
3244 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003246 kindname = "ellipsis";
3247 if (ctx != AugStore) {
3248 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3249 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 break;
3251 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003252 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253 if (!s->v.Slice.step)
3254 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003255 if (ctx != AugStore) {
3256 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257 return 0;
3258 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003259 break;
3260 case ExtSlice_kind:
3261 kindname = "extended slice";
3262 if (ctx != AugStore) {
3263 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3264 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003265 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003266 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003267 if (!compiler_visit_nested_slice(c, sub, ctx))
3268 return 0;
3269 }
3270 ADDOP_I(c, BUILD_TUPLE, n);
3271 }
3272 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003273 default:
3274 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003275 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003276 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003278 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279}
3280
Neal Norwitzf733a012006-10-29 18:30:10 +00003281
3282/* End of the compiler section, beginning of the assembler section */
3283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284/* do depth-first search of basic block graph, starting with block.
3285 post records the block indices in post-order.
3286
3287 XXX must handle implicit jumps from one block to next
3288*/
3289
Neal Norwitzf733a012006-10-29 18:30:10 +00003290struct assembler {
3291 PyObject *a_bytecode; /* string containing bytecode */
3292 int a_offset; /* offset into bytecode */
3293 int a_nblocks; /* number of reachable blocks */
3294 basicblock **a_postorder; /* list of blocks in dfs postorder */
3295 PyObject *a_lnotab; /* string containing lnotab */
3296 int a_lnotab_off; /* offset into lnotab */
3297 int a_lineno; /* last lineno of emitted instruction */
3298 int a_lineno_off; /* bytecode offset of last lineno */
3299};
3300
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301static void
3302dfs(struct compiler *c, basicblock *b, struct assembler *a)
3303{
3304 int i;
3305 struct instr *instr = NULL;
3306
3307 if (b->b_seen)
3308 return;
3309 b->b_seen = 1;
3310 if (b->b_next != NULL)
3311 dfs(c, b->b_next, a);
3312 for (i = 0; i < b->b_iused; i++) {
3313 instr = &b->b_instr[i];
3314 if (instr->i_jrel || instr->i_jabs)
3315 dfs(c, instr->i_target, a);
3316 }
3317 a->a_postorder[a->a_nblocks++] = b;
3318}
3319
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003320static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3322{
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +00003323 int i, target_depth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 struct instr *instr;
3325 if (b->b_seen || b->b_startdepth >= depth)
3326 return maxdepth;
3327 b->b_seen = 1;
3328 b->b_startdepth = depth;
3329 for (i = 0; i < b->b_iused; i++) {
3330 instr = &b->b_instr[i];
3331 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3332 if (depth > maxdepth)
3333 maxdepth = depth;
3334 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3335 if (instr->i_jrel || instr->i_jabs) {
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +00003336 target_depth = depth;
3337 if (instr->i_opcode == FOR_ITER) {
3338 target_depth = depth-2;
3339 } else if (instr->i_opcode == SETUP_FINALLY ||
3340 instr->i_opcode == SETUP_EXCEPT) {
3341 target_depth = depth+3;
3342 if (target_depth > maxdepth)
3343 maxdepth = target_depth;
3344 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345 maxdepth = stackdepth_walk(c, instr->i_target,
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +00003346 target_depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347 if (instr->i_opcode == JUMP_ABSOLUTE ||
3348 instr->i_opcode == JUMP_FORWARD) {
3349 goto out; /* remaining code is dead */
3350 }
3351 }
3352 }
3353 if (b->b_next)
3354 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3355out:
3356 b->b_seen = 0;
3357 return maxdepth;
3358}
3359
3360/* Find the flow path that needs the largest stack. We assume that
3361 * cycles in the flow graph have no net effect on the stack depth.
3362 */
3363static int
3364stackdepth(struct compiler *c)
3365{
3366 basicblock *b, *entryblock;
3367 entryblock = NULL;
3368 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3369 b->b_seen = 0;
3370 b->b_startdepth = INT_MIN;
3371 entryblock = b;
3372 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003373 if (!entryblock)
3374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375 return stackdepth_walk(c, entryblock, 0, 0);
3376}
3377
3378static int
3379assemble_init(struct assembler *a, int nblocks, int firstlineno)
3380{
3381 memset(a, 0, sizeof(struct assembler));
3382 a->a_lineno = firstlineno;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003383 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 if (!a->a_bytecode)
3385 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003386 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387 if (!a->a_lnotab)
3388 return 0;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003389 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3390 PyErr_NoMemory();
3391 return 0;
3392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003394 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003395 if (!a->a_postorder) {
3396 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003398 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399 return 1;
3400}
3401
3402static void
3403assemble_free(struct assembler *a)
3404{
3405 Py_XDECREF(a->a_bytecode);
3406 Py_XDECREF(a->a_lnotab);
3407 if (a->a_postorder)
3408 PyObject_Free(a->a_postorder);
3409}
3410
3411/* Return the size of a basic block in bytes. */
3412
3413static int
3414instrsize(struct instr *instr)
3415{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003416 if (!instr->i_hasarg)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003417 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003418 if (instr->i_oparg > 0xffff)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003419 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3420 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421}
3422
3423static int
3424blocksize(basicblock *b)
3425{
3426 int i;
3427 int size = 0;
3428
3429 for (i = 0; i < b->b_iused; i++)
3430 size += instrsize(&b->b_instr[i]);
3431 return size;
3432}
3433
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003434/* Appends a pair to the end of the line number table, a_lnotab, representing
3435 the instruction's bytecode offset and line number. See
3436 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003437
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003438static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003440{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441 int d_bytecode, d_lineno;
3442 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003443 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444
3445 d_bytecode = a->a_offset - a->a_lineno_off;
3446 d_lineno = i->i_lineno - a->a_lineno;
3447
3448 assert(d_bytecode >= 0);
3449 assert(d_lineno >= 0);
3450
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003451 if(d_bytecode == 0 && d_lineno == 0)
3452 return 1;
3453
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003455 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003457 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003459 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003461 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003463 else {
3464 PyErr_NoMemory();
3465 return 0;
3466 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003467 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003468 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003469 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003470 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003471 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003472 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473 *lnotab++ = 255;
3474 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003475 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003476 d_bytecode -= ncodes * 255;
3477 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003478 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479 assert(d_bytecode <= 255);
3480 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003481 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003483 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003485 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003486 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003487 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003489 else {
3490 PyErr_NoMemory();
3491 return 0;
3492 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003493 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003495 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003496 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003497 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003499 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003501 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003503 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003504 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505 d_lineno -= ncodes * 255;
3506 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003507 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003508
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003509 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510 if (a->a_lnotab_off + 2 >= len) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003511 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003512 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003513 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003514 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003515 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003516
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517 a->a_lnotab_off += 2;
3518 if (d_bytecode) {
3519 *lnotab++ = d_bytecode;
3520 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003521 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003522 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523 *lnotab++ = 0;
3524 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003525 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526 a->a_lineno = i->i_lineno;
3527 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003528 return 1;
3529}
3530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531/* assemble_emit()
3532 Extend the bytecode with a new instruction.
3533 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003534*/
3535
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003536static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003538{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003539 int size, arg = 0, ext = 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003540 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 char *code;
3542
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003543 size = instrsize(i);
3544 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003546 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003547 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003549 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 if (a->a_offset + size >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003551 if (len > PY_SSIZE_T_MAX / 2)
3552 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003553 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003554 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003555 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003556 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003558 if (size == 6) {
3559 assert(i->i_hasarg);
3560 *code++ = (char)EXTENDED_ARG;
3561 *code++ = ext & 0xff;
3562 *code++ = ext >> 8;
3563 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003564 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003566 if (i->i_hasarg) {
3567 assert(size == 3 || size == 6);
3568 *code++ = arg & 0xff;
3569 *code++ = arg >> 8;
3570 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003572}
3573
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003574static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003576{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 basicblock *b;
Benjamin Petersoncef97822009-11-20 02:15:50 +00003578 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003579 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003580
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581 /* Compute the size of each block and fixup jump args.
3582 Replace block pointer with position in bytecode. */
Benjamin Petersoncef97822009-11-20 02:15:50 +00003583 do {
3584 totsize = 0;
3585 for (i = a->a_nblocks - 1; i >= 0; i--) {
3586 b = a->a_postorder[i];
3587 bsize = blocksize(b);
3588 b->b_offset = totsize;
3589 totsize += bsize;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003590 }
Benjamin Petersoncef97822009-11-20 02:15:50 +00003591 last_extended_arg_count = extended_arg_count;
3592 extended_arg_count = 0;
3593 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3594 bsize = b->b_offset;
3595 for (i = 0; i < b->b_iused; i++) {
3596 struct instr *instr = &b->b_instr[i];
3597 /* Relative jumps are computed relative to
3598 the instruction pointer after fetching
3599 the jump instruction.
3600 */
3601 bsize += instrsize(instr);
3602 if (instr->i_jabs)
3603 instr->i_oparg = instr->i_target->b_offset;
3604 else if (instr->i_jrel) {
3605 int delta = instr->i_target->b_offset - bsize;
3606 instr->i_oparg = delta;
3607 }
3608 else
3609 continue;
3610 if (instr->i_oparg > 0xffff)
3611 extended_arg_count++;
3612 }
3613 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003614
3615 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003616 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003617 with a better solution.
3618
Neal Norwitzf1d50682005-10-23 23:00:41 +00003619 The issue is that in the first loop blocksize() is called
3620 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003621 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003622 i_oparg is calculated in the second loop above.
3623
3624 So we loop until we stop seeing new EXTENDED_ARGs.
3625 The only EXTENDED_ARGs that could be popping up are
3626 ones in jump instructions. So this should converge
3627 fairly quickly.
3628 */
Benjamin Petersoncef97822009-11-20 02:15:50 +00003629 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003630}
3631
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003632static PyObject *
3633dict_keys_inorder(PyObject *dict, int offset)
3634{
3635 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003636 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003637
3638 tuple = PyTuple_New(size);
3639 if (tuple == NULL)
3640 return NULL;
3641 while (PyDict_Next(dict, &pos, &k, &v)) {
3642 i = PyInt_AS_LONG(v);
Benjamin Petersonda9327f2009-01-31 23:43:25 +00003643 /* The keys of the dictionary are tuples. (see compiler_add_o)
3644 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003645 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003646 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003647 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003648 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003649 PyTuple_SET_ITEM(tuple, i - offset, k);
3650 }
3651 return tuple;
3652}
3653
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003654static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003656{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 PySTEntryObject *ste = c->u->u_ste;
3658 int flags = 0, n;
3659 if (ste->ste_type != ModuleBlock)
3660 flags |= CO_NEWLOCALS;
3661 if (ste->ste_type == FunctionBlock) {
3662 if (!ste->ste_unoptimized)
3663 flags |= CO_OPTIMIZED;
3664 if (ste->ste_nested)
3665 flags |= CO_NESTED;
3666 if (ste->ste_generator)
3667 flags |= CO_GENERATOR;
Benjamin Peterson12554cb2009-01-31 23:54:38 +00003668 if (ste->ste_varargs)
3669 flags |= CO_VARARGS;
3670 if (ste->ste_varkeywords)
3671 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003672 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003673
3674 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003675 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677 n = PyDict_Size(c->u->u_freevars);
3678 if (n < 0)
3679 return -1;
3680 if (n == 0) {
3681 n = PyDict_Size(c->u->u_cellvars);
3682 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003683 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684 if (n == 0) {
3685 flags |= CO_NOFREE;
3686 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003687 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003688
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003689 return flags;
3690}
3691
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003692static PyCodeObject *
3693makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003694{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 PyObject *tmp;
3696 PyCodeObject *co = NULL;
3697 PyObject *consts = NULL;
3698 PyObject *names = NULL;
3699 PyObject *varnames = NULL;
3700 PyObject *filename = NULL;
3701 PyObject *name = NULL;
3702 PyObject *freevars = NULL;
3703 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003704 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003705 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003706
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003707 tmp = dict_keys_inorder(c->u->u_consts, 0);
3708 if (!tmp)
3709 goto error;
3710 consts = PySequence_List(tmp); /* optimize_code requires a list */
3711 Py_DECREF(tmp);
3712
3713 names = dict_keys_inorder(c->u->u_names, 0);
3714 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3715 if (!consts || !names || !varnames)
3716 goto error;
3717
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003718 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3719 if (!cellvars)
3720 goto error;
3721 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3722 if (!freevars)
3723 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003724 filename = PyString_FromString(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725 if (!filename)
3726 goto error;
3727
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003728 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729 flags = compute_code_flags(c);
3730 if (flags < 0)
3731 goto error;
3732
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003733 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734 if (!bytecode)
3735 goto error;
3736
3737 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3738 if (!tmp)
3739 goto error;
3740 Py_DECREF(consts);
3741 consts = tmp;
3742
3743 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3744 bytecode, consts, names, varnames,
3745 freevars, cellvars,
3746 filename, c->u->u_name,
3747 c->u->u_firstlineno,
3748 a->a_lnotab);
3749 error:
3750 Py_XDECREF(consts);
3751 Py_XDECREF(names);
3752 Py_XDECREF(varnames);
3753 Py_XDECREF(filename);
3754 Py_XDECREF(name);
3755 Py_XDECREF(freevars);
3756 Py_XDECREF(cellvars);
3757 Py_XDECREF(bytecode);
3758 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003759}
3760
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003761
3762/* For debugging purposes only */
3763#if 0
3764static void
3765dump_instr(const struct instr *i)
3766{
3767 const char *jrel = i->i_jrel ? "jrel " : "";
3768 const char *jabs = i->i_jabs ? "jabs " : "";
3769 char arg[128];
3770
3771 *arg = '\0';
3772 if (i->i_hasarg)
3773 sprintf(arg, "arg: %d ", i->i_oparg);
3774
3775 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3776 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3777}
3778
3779static void
3780dump_basicblock(const basicblock *b)
3781{
3782 const char *seen = b->b_seen ? "seen " : "";
3783 const char *b_return = b->b_return ? "return " : "";
3784 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3785 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3786 if (b->b_instr) {
3787 int i;
3788 for (i = 0; i < b->b_iused; i++) {
3789 fprintf(stderr, " [%02d] ", i);
3790 dump_instr(b->b_instr + i);
3791 }
3792 }
3793}
3794#endif
3795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796static PyCodeObject *
3797assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003798{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799 basicblock *b, *entryblock;
3800 struct assembler a;
3801 int i, j, nblocks;
3802 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003803
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 /* Make sure every block that falls off the end returns None.
3805 XXX NEXT_BLOCK() isn't quite right, because if the last
3806 block ends with a jump or return b_next shouldn't set.
3807 */
3808 if (!c->u->u_curblock->b_return) {
3809 NEXT_BLOCK(c);
3810 if (addNone)
3811 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3812 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003813 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003814
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 nblocks = 0;
3816 entryblock = NULL;
3817 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3818 nblocks++;
3819 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003820 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003821
Neal Norwitzed657552006-07-10 00:04:44 +00003822 /* Set firstlineno if it wasn't explicitly set. */
3823 if (!c->u->u_firstlineno) {
3824 if (entryblock && entryblock->b_instr)
3825 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3826 else
3827 c->u->u_firstlineno = 1;
3828 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3830 goto error;
3831 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003832
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003834 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836 /* Emit code in reverse postorder from dfs. */
3837 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003838 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003839 for (j = 0; j < b->b_iused; j++)
3840 if (!assemble_emit(&a, &b->b_instr[j]))
3841 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003842 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003843
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003844 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003845 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003846 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849 co = makecode(c, &a);
3850 error:
3851 assemble_free(&a);
3852 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003853}