blob: 29cd95055365954cfd80712638c1b81c22f447f9 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Neal Norwitzf733a012006-10-29 18:30:10 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hylton819de6c2007-02-27 16:13:23 +000011 * this file.
Neal Norwitzf733a012006-10-29 18:30:10 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Neal Norwitzf733a012006-10-29 18:30:10 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000042struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000043 unsigned i_jabs : 1;
44 unsigned i_jrel : 1;
45 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000067 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000068 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000069 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000070 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000073 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
83enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
84
85struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000087 basicblock *fb_block;
88};
89
90/* The following items change on entry and exit of code blocks.
91 They must be saved and restored when returning to a block.
92*/
93struct compiler_unit {
94 PySTEntryObject *u_ste;
95
96 PyObject *u_name;
97 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +000098 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099 the argument for opcodes that refer to those collections.
100 */
101 PyObject *u_consts; /* all constants */
102 PyObject *u_names; /* all names */
103 PyObject *u_varnames; /* local variables */
104 PyObject *u_cellvars; /* cell variables */
105 PyObject *u_freevars; /* free variables */
106
107 PyObject *u_private; /* for private name mangling */
108
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000109 int u_argcount; /* number of arguments for block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000110 /* Pointer to the most recently allocated block. By following b_list
111 members, you can reach all early allocated blocks. */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000112 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113 basicblock *u_curblock; /* pointer to current block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000114 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000115
116 int u_nfblocks;
117 struct fblockinfo u_fblock[CO_MAXBLOCKS];
118
119 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000120 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 bool u_lineno_set; /* boolean to indicate whether instr
122 has been generated with current lineno */
123};
124
125/* This struct captures the global state of a compilation.
126
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000127The u pointer points to the current compilation unit, while units
128for enclosing blocks are stored in c_stack. The u and c_stack are
129managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130*/
131
132struct compiler {
133 const char *c_filename;
134 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136 PyCompilerFlags *c_flags;
137
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000138 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000139 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 struct compiler_unit *u; /* compiler state for current block */
142 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144};
145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146static int compiler_enter_scope(struct compiler *, identifier, void *, int);
147static void compiler_free(struct compiler *);
148static basicblock *compiler_new_block(struct compiler *);
149static int compiler_next_instr(struct compiler *, basicblock *);
150static int compiler_addop(struct compiler *, int);
151static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
152static int compiler_addop_i(struct compiler *, int, int);
153static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000154static basicblock *compiler_use_new_block(struct compiler *);
155static int compiler_error(struct compiler *, const char *);
156static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
157
158static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
159static int compiler_visit_stmt(struct compiler *, stmt_ty);
160static int compiler_visit_keyword(struct compiler *, keyword_ty);
161static int compiler_visit_expr(struct compiler *, expr_ty);
162static int compiler_augassign(struct compiler *, stmt_ty);
163static int compiler_visit_slice(struct compiler *, slice_ty,
164 expr_context_ty);
165
166static int compiler_push_fblock(struct compiler *, enum fblocktype,
167 basicblock *);
168static void compiler_pop_fblock(struct compiler *, enum fblocktype,
169 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000170/* Returns true if there is a loop on the fblock stack. */
171static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000172
173static int inplace_binop(struct compiler *, operator_ty);
174static int expr_constant(expr_ty e);
175
Guido van Rossumc2e20742006-02-27 22:32:47 +0000176static int compiler_with(struct compiler *, stmt_ty);
177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178static PyCodeObject *assemble(struct compiler *, int addNone);
179static PyObject *__doc__;
180
181PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000182_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000183{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184 /* Name mangling: __private becomes _classname__private.
185 This is independent from how the name is used. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000186 const char *p, *name = PyString_AsString(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000187 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188 size_t nlen, plen;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000189 if (privateobj == NULL || !PyString_Check(privateobj) ||
Neal Norwitz84167d02006-08-12 01:45:47 +0000190 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000191 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000193 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000194 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195 nlen = strlen(name);
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000196 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000197
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000198 The only time a name with a dot can occur is when
199 we are compiling an import statement that has a
200 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000201
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000202 TODO(jhylton): Decide whether we want to support
203 mangling of the module name, e.g. __M.X.
204 */
Jeremy Hylton37075c52007-02-27 01:01:59 +0000205 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000206 || strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000207 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000209 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 /* Strip leading underscores from class name */
211 while (*p == '_')
212 p++;
213 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000214 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000216 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000217 plen = strlen(p);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000218
219 assert(1 <= PY_SSIZE_T_MAX - nlen);
220 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
221
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000222 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 if (!ident)
224 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000226 buffer = PyString_AS_STRING(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000227 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228 strncpy(buffer+1, p, plen);
229 strcpy(buffer+1+plen, name);
230 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000231}
232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233static int
234compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000235{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000236 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000238 c->c_stack = PyList_New(0);
239 if (!c->c_stack)
240 return 0;
241
242 return 1;
243}
244
245PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000246PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000247 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000248{
249 struct compiler c;
250 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 PyCompilerFlags local_flags;
252 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000254 if (!__doc__) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000255 __doc__ = PyString_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000256 if (!__doc__)
257 return NULL;
258 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259
260 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000261 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000262 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000263 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264 c.c_future = PyFuture_FromAST(mod, filename);
265 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000266 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000268 local_flags.cf_flags = 0;
269 flags = &local_flags;
270 }
271 merged = c.c_future->ff_features | flags->cf_flags;
272 c.c_future->ff_features = merged;
273 flags->cf_flags = merged;
274 c.c_flags = flags;
275 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000276
277 c.c_st = PySymtable_Build(mod, filename, c.c_future);
278 if (c.c_st == NULL) {
279 if (!PyErr_Occurred())
280 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000281 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000282 }
283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284 co = compiler_mod(&c, mod);
285
Thomas Wouters1175c432006-02-27 22:49:54 +0000286 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000288 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289 return co;
290}
291
292PyCodeObject *
293PyNode_Compile(struct _node *n, const char *filename)
294{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000295 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000296 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000297 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000298 if (!arena)
299 return NULL;
300 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000301 if (mod)
302 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000303 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000304 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000305}
306
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000307static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000309{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310 if (c->c_st)
311 PySymtable_Free(c->c_st);
312 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000313 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000315}
316
Guido van Rossum79f25d91997-04-29 20:08:16 +0000317static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000319{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000320 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000321 PyObject *v, *k;
322 PyObject *dict = PyDict_New();
323 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 n = PyList_Size(list);
326 for (i = 0; i < n; i++) {
327 v = PyInt_FromLong(i);
328 if (!v) {
329 Py_DECREF(dict);
330 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000331 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000332 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000333 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
335 Py_XDECREF(k);
336 Py_DECREF(v);
337 Py_DECREF(dict);
338 return NULL;
339 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000340 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 return dict;
344}
345
346/* Return new dict containing names from src that match scope(s).
347
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000348src is a symbol table dictionary. If the scope of a name matches
349either scope_type or flag is set, insert it into the new dict. The
350values are integers, starting at offset and increasing by one for
351each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352*/
353
354static PyObject *
355dictbytype(PyObject *src, int scope_type, int flag, int offset)
356{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000357 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 PyObject *k, *v, *dest = PyDict_New();
359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360 assert(offset >= 0);
361 if (dest == NULL)
362 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
364 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000365 /* XXX this should probably be a macro in symtable.h */
366 assert(PyInt_Check(v));
367 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
370 PyObject *tuple, *item = PyInt_FromLong(i);
371 if (item == NULL) {
372 Py_DECREF(dest);
373 return NULL;
374 }
375 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000376 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
378 Py_DECREF(item);
379 Py_DECREF(dest);
380 Py_XDECREF(tuple);
381 return NULL;
382 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000386 }
387 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000388}
389
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390static void
391compiler_unit_check(struct compiler_unit *u)
392{
393 basicblock *block;
394 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Brett Cannona6c41bc2008-02-07 07:47:31 +0000395 assert((void *)block != (void *)0xcbcbcbcb);
396 assert((void *)block != (void *)0xfbfbfbfb);
397 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398 if (block->b_instr != NULL) {
399 assert(block->b_ialloc > 0);
400 assert(block->b_iused > 0);
401 assert(block->b_ialloc >= block->b_iused);
402 }
403 else {
404 assert (block->b_iused == 0);
405 assert (block->b_ialloc == 0);
406 }
407 }
408}
409
410static void
411compiler_unit_free(struct compiler_unit *u)
412{
413 basicblock *b, *next;
414
415 compiler_unit_check(u);
416 b = u->u_blocks;
417 while (b != NULL) {
418 if (b->b_instr)
419 PyObject_Free((void *)b->b_instr);
420 next = b->b_list;
421 PyObject_Free((void *)b);
422 b = next;
423 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000424 Py_CLEAR(u->u_ste);
425 Py_CLEAR(u->u_name);
426 Py_CLEAR(u->u_consts);
427 Py_CLEAR(u->u_names);
428 Py_CLEAR(u->u_varnames);
429 Py_CLEAR(u->u_freevars);
430 Py_CLEAR(u->u_cellvars);
431 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000432 PyObject_Free(u);
433}
434
435static int
436compiler_enter_scope(struct compiler *c, identifier name, void *key,
437 int lineno)
438{
439 struct compiler_unit *u;
440
Anthony Baxter7b782b62006-04-11 12:01:56 +0000441 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000442 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000443 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444 PyErr_NoMemory();
445 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000446 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000447 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448 u->u_argcount = 0;
449 u->u_ste = PySymtable_Lookup(c->c_st, key);
450 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000451 compiler_unit_free(u);
452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453 }
454 Py_INCREF(name);
455 u->u_name = name;
456 u->u_varnames = list2dict(u->u_ste->ste_varnames);
457 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000458 if (!u->u_varnames || !u->u_cellvars) {
459 compiler_unit_free(u);
460 return 0;
461 }
462
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000465 if (!u->u_freevars) {
466 compiler_unit_free(u);
467 return 0;
468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469
470 u->u_blocks = NULL;
471 u->u_tmpname = 0;
472 u->u_nfblocks = 0;
473 u->u_firstlineno = lineno;
474 u->u_lineno = 0;
475 u->u_lineno_set = false;
476 u->u_consts = PyDict_New();
477 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000478 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000479 return 0;
480 }
481 u->u_names = PyDict_New();
482 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000483 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484 return 0;
485 }
486
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000487 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000488
489 /* Push the old compiler_unit on the stack. */
490 if (c->u) {
491 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000492 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
493 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000494 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000495 return 0;
496 }
497 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 u->u_private = c->u->u_private;
499 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500 }
501 c->u = u;
502
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000503 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000504 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000505 return 0;
506
507 return 1;
508}
509
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000510static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511compiler_exit_scope(struct compiler *c)
512{
513 int n;
514 PyObject *wrapper;
515
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000516 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 compiler_unit_free(c->u);
518 /* Restore c->u to the parent unit. */
519 n = PyList_GET_SIZE(c->c_stack) - 1;
520 if (n >= 0) {
521 wrapper = PyList_GET_ITEM(c->c_stack, n);
522 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000523 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000526 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 compiler_unit_check(c->u);
528 }
529 else
530 c->u = NULL;
531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532}
533
534/* Allocate a new block and return a pointer to it.
535 Returns NULL on error.
536*/
537
538static basicblock *
539compiler_new_block(struct compiler *c)
540{
541 basicblock *b;
542 struct compiler_unit *u;
543
544 u = c->u;
545 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000546 if (b == NULL) {
547 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000549 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000551 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552 b->b_list = u->u_blocks;
553 u->u_blocks = b;
554 return b;
555}
556
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000557static basicblock *
558compiler_use_new_block(struct compiler *c)
559{
560 basicblock *block = compiler_new_block(c);
561 if (block == NULL)
562 return NULL;
563 c->u->u_curblock = block;
564 return block;
565}
566
567static basicblock *
568compiler_next_block(struct compiler *c)
569{
570 basicblock *block = compiler_new_block(c);
571 if (block == NULL)
572 return NULL;
573 c->u->u_curblock->b_next = block;
574 c->u->u_curblock = block;
575 return block;
576}
577
578static basicblock *
579compiler_use_next_block(struct compiler *c, basicblock *block)
580{
581 assert(block != NULL);
582 c->u->u_curblock->b_next = block;
583 c->u->u_curblock = block;
584 return block;
585}
586
587/* Returns the offset of the next instruction in the current block's
588 b_instr array. Resizes the b_instr as necessary.
589 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000590*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000591
592static int
593compiler_next_instr(struct compiler *c, basicblock *b)
594{
595 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000596 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000597 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000598 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599 if (b->b_instr == NULL) {
600 PyErr_NoMemory();
601 return -1;
602 }
603 b->b_ialloc = DEFAULT_BLOCK_SIZE;
604 memset((char *)b->b_instr, 0,
605 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000606 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000608 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609 size_t oldsize, newsize;
610 oldsize = b->b_ialloc * sizeof(struct instr);
611 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000612
613 if (oldsize > (PY_SIZE_MAX >> 1)) {
614 PyErr_NoMemory();
615 return -1;
616 }
617
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618 if (newsize == 0) {
619 PyErr_NoMemory();
620 return -1;
621 }
622 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000623 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000624 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000625 if (tmp == NULL) {
626 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000627 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000628 }
629 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000630 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
631 }
632 return b->b_iused++;
633}
634
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000635/* Set the i_lineno member of the instruction at offset off if the
636 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000637 already been set. If it has been set, the call has no effect.
638
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000639 The line number is reset in the following cases:
640 - when entering a new scope
641 - on each statement
642 - on each expression that start a new line
643 - before the "except" clause
644 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000645*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000646
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647static void
648compiler_set_lineno(struct compiler *c, int off)
649{
650 basicblock *b;
651 if (c->u->u_lineno_set)
652 return;
653 c->u->u_lineno_set = true;
654 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000655 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656}
657
658static int
659opcode_stack_effect(int opcode, int oparg)
660{
661 switch (opcode) {
662 case POP_TOP:
663 return -1;
664 case ROT_TWO:
665 case ROT_THREE:
666 return 0;
667 case DUP_TOP:
668 return 1;
669 case ROT_FOUR:
670 return 0;
671
672 case UNARY_POSITIVE:
673 case UNARY_NEGATIVE:
674 case UNARY_NOT:
675 case UNARY_CONVERT:
676 case UNARY_INVERT:
677 return 0;
678
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000679 case LIST_APPEND:
Antoine Pitroud0c35152008-12-17 00:38:28 +0000680 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000681
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000682 case BINARY_POWER:
683 case BINARY_MULTIPLY:
684 case BINARY_DIVIDE:
685 case BINARY_MODULO:
686 case BINARY_ADD:
687 case BINARY_SUBTRACT:
688 case BINARY_SUBSCR:
689 case BINARY_FLOOR_DIVIDE:
690 case BINARY_TRUE_DIVIDE:
691 return -1;
692 case INPLACE_FLOOR_DIVIDE:
693 case INPLACE_TRUE_DIVIDE:
694 return -1;
695
696 case SLICE+0:
697 return 1;
698 case SLICE+1:
699 return 0;
700 case SLICE+2:
701 return 0;
702 case SLICE+3:
703 return -1;
704
705 case STORE_SLICE+0:
706 return -2;
707 case STORE_SLICE+1:
708 return -3;
709 case STORE_SLICE+2:
710 return -3;
711 case STORE_SLICE+3:
712 return -4;
713
714 case DELETE_SLICE+0:
715 return -1;
716 case DELETE_SLICE+1:
717 return -2;
718 case DELETE_SLICE+2:
719 return -2;
720 case DELETE_SLICE+3:
721 return -3;
722
723 case INPLACE_ADD:
724 case INPLACE_SUBTRACT:
725 case INPLACE_MULTIPLY:
726 case INPLACE_DIVIDE:
727 case INPLACE_MODULO:
728 return -1;
729 case STORE_SUBSCR:
730 return -3;
Raymond Hettingereffde122007-12-18 18:26:18 +0000731 case STORE_MAP:
732 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733 case DELETE_SUBSCR:
734 return -2;
735
736 case BINARY_LSHIFT:
737 case BINARY_RSHIFT:
738 case BINARY_AND:
739 case BINARY_XOR:
740 case BINARY_OR:
741 return -1;
742 case INPLACE_POWER:
743 return -1;
744 case GET_ITER:
745 return 0;
746
747 case PRINT_EXPR:
748 return -1;
749 case PRINT_ITEM:
750 return -1;
751 case PRINT_NEWLINE:
752 return 0;
753 case PRINT_ITEM_TO:
754 return -2;
755 case PRINT_NEWLINE_TO:
756 return -1;
757 case INPLACE_LSHIFT:
758 case INPLACE_RSHIFT:
759 case INPLACE_AND:
760 case INPLACE_XOR:
761 case INPLACE_OR:
762 return -1;
763 case BREAK_LOOP:
764 return 0;
Benjamin Peterson1880d8b2009-05-25 13:13:44 +0000765 case SETUP_WITH:
Benjamin Peterson49a6b0e2009-05-25 20:12:57 +0000766 return 4;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000767 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000768 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769 case LOAD_LOCALS:
770 return 1;
771 case RETURN_VALUE:
772 return -1;
773 case IMPORT_STAR:
774 return -1;
775 case EXEC_STMT:
776 return -3;
777 case YIELD_VALUE:
778 return 0;
779
780 case POP_BLOCK:
781 return 0;
782 case END_FINALLY:
783 return -1; /* or -2 or -3 if exception occurred */
784 case BUILD_CLASS:
785 return -2;
786
787 case STORE_NAME:
788 return -1;
789 case DELETE_NAME:
790 return 0;
791 case UNPACK_SEQUENCE:
792 return oparg-1;
793 case FOR_ITER:
794 return 1;
795
796 case STORE_ATTR:
797 return -2;
798 case DELETE_ATTR:
799 return -1;
800 case STORE_GLOBAL:
801 return -1;
802 case DELETE_GLOBAL:
803 return 0;
804 case DUP_TOPX:
805 return oparg;
806 case LOAD_CONST:
807 return 1;
808 case LOAD_NAME:
809 return 1;
810 case BUILD_TUPLE:
811 case BUILD_LIST:
812 return 1-oparg;
813 case BUILD_MAP:
814 return 1;
815 case LOAD_ATTR:
816 return 0;
817 case COMPARE_OP:
818 return -1;
819 case IMPORT_NAME:
820 return 0;
821 case IMPORT_FROM:
822 return 1;
823
824 case JUMP_FORWARD:
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000825 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
826 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827 case JUMP_ABSOLUTE:
828 return 0;
829
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000830 case POP_JUMP_IF_FALSE:
831 case POP_JUMP_IF_TRUE:
832 return -1;
833
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000834 case LOAD_GLOBAL:
835 return 1;
836
837 case CONTINUE_LOOP:
838 return 0;
839 case SETUP_LOOP:
840 return 0;
841 case SETUP_EXCEPT:
842 case SETUP_FINALLY:
843 return 3; /* actually pushed by an exception */
844
845 case LOAD_FAST:
846 return 1;
847 case STORE_FAST:
848 return -1;
849 case DELETE_FAST:
850 return 0;
851
852 case RAISE_VARARGS:
853 return -oparg;
854#define NARGS(o) (((o) % 256) + 2*((o) / 256))
855 case CALL_FUNCTION:
856 return -NARGS(oparg);
857 case CALL_FUNCTION_VAR:
858 case CALL_FUNCTION_KW:
859 return -NARGS(oparg)-1;
860 case CALL_FUNCTION_VAR_KW:
861 return -NARGS(oparg)-2;
862#undef NARGS
863 case MAKE_FUNCTION:
864 return -oparg;
865 case BUILD_SLICE:
866 if (oparg == 3)
867 return -2;
868 else
869 return -1;
870
871 case MAKE_CLOSURE:
872 return -oparg;
873 case LOAD_CLOSURE:
874 return 1;
875 case LOAD_DEREF:
876 return 1;
877 case STORE_DEREF:
878 return -1;
879 default:
880 fprintf(stderr, "opcode = %d\n", opcode);
881 Py_FatalError("opcode_stack_effect()");
882
883 }
884 return 0; /* not reachable */
885}
886
887/* Add an opcode with no argument.
888 Returns 0 on failure, 1 on success.
889*/
890
891static int
892compiler_addop(struct compiler *c, int opcode)
893{
894 basicblock *b;
895 struct instr *i;
896 int off;
897 off = compiler_next_instr(c, c->u->u_curblock);
898 if (off < 0)
899 return 0;
900 b = c->u->u_curblock;
901 i = &b->b_instr[off];
902 i->i_opcode = opcode;
903 i->i_hasarg = 0;
904 if (opcode == RETURN_VALUE)
905 b->b_return = 1;
906 compiler_set_lineno(c, off);
907 return 1;
908}
909
910static int
911compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
912{
913 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000914 Py_ssize_t arg;
Mark Dickinson105be772008-01-31 22:17:37 +0000915 unsigned char *p, *q;
916 Py_complex z;
917 double d;
918 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000920 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000921 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
922 if (PyFloat_Check(o)) {
Mark Dickinson105be772008-01-31 22:17:37 +0000923 d = PyFloat_AS_DOUBLE(o);
924 p = (unsigned char*) &d;
925 /* all we need is to make the tuple different in either the 0.0
926 * or -0.0 case from all others, just to avoid the "coercion".
927 */
928 if (*p==0 && p[sizeof(double)-1]==0)
929 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
930 else
931 t = PyTuple_Pack(2, o, o->ob_type);
932 }
933 else if (PyComplex_Check(o)) {
934 /* complex case is even messier: we need to make complex(x,
935 0.) different from complex(x, -0.) and complex(0., y)
936 different from complex(-0., y), for any x and y. In
937 particular, all four complex zeros should be
938 distinguished.*/
939 z = PyComplex_AsCComplex(o);
940 p = (unsigned char*) &(z.real);
941 q = (unsigned char*) &(z.imag);
942 /* all that matters here is that on IEEE platforms
943 real_part_zero will be true if z.real == 0., and false if
944 z.real == -0. In fact, real_part_zero will also be true
945 for some other rarely occurring nonzero floats, but this
946 doesn't matter. Similar comments apply to
947 imag_part_zero. */
948 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
949 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
950 if (real_part_zero && imag_part_zero) {
951 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
952 }
953 else if (real_part_zero && !imag_part_zero) {
954 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
955 }
956 else if (!real_part_zero && imag_part_zero) {
957 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
958 }
959 else {
960 t = PyTuple_Pack(2, o, o->ob_type);
961 }
962 }
963 else {
964 t = PyTuple_Pack(2, o, o->ob_type);
Alex Martellid8672aa2007-08-22 21:14:17 +0000965 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000966 if (t == NULL)
Mark Dickinson105be772008-01-31 22:17:37 +0000967 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968
969 v = PyDict_GetItem(dict, t);
970 if (!v) {
971 arg = PyDict_Size(dict);
972 v = PyInt_FromLong(arg);
973 if (!v) {
974 Py_DECREF(t);
975 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000976 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977 if (PyDict_SetItem(dict, t, v) < 0) {
978 Py_DECREF(t);
979 Py_DECREF(v);
980 return -1;
981 }
982 Py_DECREF(v);
983 }
984 else
985 arg = PyInt_AsLong(v);
986 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000987 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988}
989
990static int
991compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
992 PyObject *o)
993{
994 int arg = compiler_add_o(c, dict, o);
995 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997 return compiler_addop_i(c, opcode, arg);
998}
999
1000static int
1001compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003{
1004 int arg;
1005 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1006 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001007 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008 arg = compiler_add_o(c, dict, mangled);
1009 Py_DECREF(mangled);
1010 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001011 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001012 return compiler_addop_i(c, opcode, arg);
1013}
1014
1015/* Add an opcode with an integer argument.
1016 Returns 0 on failure, 1 on success.
1017*/
1018
1019static int
1020compiler_addop_i(struct compiler *c, int opcode, int oparg)
1021{
1022 struct instr *i;
1023 int off;
1024 off = compiler_next_instr(c, c->u->u_curblock);
1025 if (off < 0)
1026 return 0;
1027 i = &c->u->u_curblock->b_instr[off];
1028 i->i_opcode = opcode;
1029 i->i_oparg = oparg;
1030 i->i_hasarg = 1;
1031 compiler_set_lineno(c, off);
1032 return 1;
1033}
1034
1035static int
1036compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1037{
1038 struct instr *i;
1039 int off;
1040
1041 assert(b != NULL);
1042 off = compiler_next_instr(c, c->u->u_curblock);
1043 if (off < 0)
1044 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045 i = &c->u->u_curblock->b_instr[off];
1046 i->i_opcode = opcode;
1047 i->i_target = b;
1048 i->i_hasarg = 1;
1049 if (absolute)
1050 i->i_jabs = 1;
1051 else
1052 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001053 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054 return 1;
1055}
1056
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001057/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1058 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059 it as the current block. NEXT_BLOCK() also creates an implicit jump
1060 from the current block to the new block.
1061*/
1062
Neal Norwitzf733a012006-10-29 18:30:10 +00001063/* The returns inside these macros make it impossible to decref objects
1064 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065*/
1066
1067
1068#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001069 if (compiler_use_new_block((C)) == NULL) \
1070 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
1073#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001074 if (compiler_next_block((C)) == NULL) \
1075 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076}
1077
1078#define ADDOP(C, OP) { \
1079 if (!compiler_addop((C), (OP))) \
1080 return 0; \
1081}
1082
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001083#define ADDOP_IN_SCOPE(C, OP) { \
1084 if (!compiler_addop((C), (OP))) { \
1085 compiler_exit_scope(c); \
1086 return 0; \
1087 } \
1088}
1089
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001090#define ADDOP_O(C, OP, O, TYPE) { \
1091 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1092 return 0; \
1093}
1094
1095#define ADDOP_NAME(C, OP, O, TYPE) { \
1096 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1097 return 0; \
1098}
1099
1100#define ADDOP_I(C, OP, O) { \
1101 if (!compiler_addop_i((C), (OP), (O))) \
1102 return 0; \
1103}
1104
1105#define ADDOP_JABS(C, OP, O) { \
1106 if (!compiler_addop_j((C), (OP), (O), 1)) \
1107 return 0; \
1108}
1109
1110#define ADDOP_JREL(C, OP, O) { \
1111 if (!compiler_addop_j((C), (OP), (O), 0)) \
1112 return 0; \
1113}
1114
1115/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1116 the ASDL name to synthesize the name of the C type and the visit function.
1117*/
1118
1119#define VISIT(C, TYPE, V) {\
1120 if (!compiler_visit_ ## TYPE((C), (V))) \
1121 return 0; \
1122}
1123
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001124#define VISIT_IN_SCOPE(C, TYPE, V) {\
1125 if (!compiler_visit_ ## TYPE((C), (V))) { \
1126 compiler_exit_scope(c); \
1127 return 0; \
1128 } \
1129}
1130
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131#define VISIT_SLICE(C, V, CTX) {\
1132 if (!compiler_visit_slice((C), (V), (CTX))) \
1133 return 0; \
1134}
1135
1136#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001137 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +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 return 0; \
1143 } \
1144}
1145
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001146#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001147 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001148 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001149 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001150 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001151 if (!compiler_visit_ ## TYPE((C), elt)) { \
1152 compiler_exit_scope(c); \
1153 return 0; \
1154 } \
1155 } \
1156}
1157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158static int
1159compiler_isdocstring(stmt_ty s)
1160{
1161 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001162 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163 return s->v.Expr.value->kind == Str_kind;
1164}
1165
1166/* Compile a sequence of statements, checking for a docstring. */
1167
1168static int
1169compiler_body(struct compiler *c, asdl_seq *stmts)
1170{
1171 int i = 0;
1172 stmt_ty st;
1173
1174 if (!asdl_seq_LEN(stmts))
1175 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001176 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001177 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1178 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179 i = 1;
1180 VISIT(c, expr, st->v.Expr.value);
1181 if (!compiler_nameop(c, __doc__, Store))
1182 return 0;
1183 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001185 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 return 1;
1187}
1188
1189static PyCodeObject *
1190compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001191{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001192 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001193 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 static PyObject *module;
1195 if (!module) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001196 module = PyString_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 if (!module)
1198 return NULL;
1199 }
Neal Norwitzed657552006-07-10 00:04:44 +00001200 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1201 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001202 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 switch (mod->kind) {
1204 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001205 if (!compiler_body(c, mod->v.Module.body)) {
1206 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 break;
1210 case Interactive_kind:
1211 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001212 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001213 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214 break;
1215 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001216 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001217 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 break;
1219 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001220 PyErr_SetString(PyExc_SystemError,
1221 "suite should not be possible");
1222 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001223 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001224 PyErr_Format(PyExc_SystemError,
1225 "module kind %d should not be possible",
1226 mod->kind);
1227 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001228 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229 co = assemble(c, addNone);
1230 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001231 return co;
1232}
1233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234/* The test for LOCAL must come before the test for FREE in order to
1235 handle classes where name is both local and free. The local var is
1236 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001237*/
1238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239static int
1240get_ref_type(struct compiler *c, PyObject *name)
1241{
1242 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001243 if (scope == 0) {
1244 char buf[350];
1245 PyOS_snprintf(buf, sizeof(buf),
1246 "unknown scope for %.100s in %.100s(%s) in %s\n"
Amaury Forgeot d'Arc59ce0422009-01-17 20:18:59 +00001247 "symbols: %s\nlocals: %s\nglobals: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001248 PyString_AS_STRING(name),
1249 PyString_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 PyObject_REPR(c->u->u_ste->ste_id),
1251 c->c_filename,
1252 PyObject_REPR(c->u->u_ste->ste_symbols),
1253 PyObject_REPR(c->u->u_varnames),
1254 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001256 Py_FatalError(buf);
1257 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001258
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262static int
1263compiler_lookup_arg(PyObject *dict, PyObject *name)
1264{
1265 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001266 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001268 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001270 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273 return PyInt_AS_LONG(v);
1274}
1275
1276static int
1277compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1278{
1279 int i, free = PyCode_GetNumFree(co);
1280 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001281 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1282 ADDOP_I(c, MAKE_FUNCTION, args);
1283 return 1;
1284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285 for (i = 0; i < free; ++i) {
1286 /* Bypass com_addop_varname because it will generate
1287 LOAD_DEREF but LOAD_CLOSURE is needed.
1288 */
1289 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1290 int arg, reftype;
1291
1292 /* Special case: If a class contains a method with a
1293 free variable that has the same name as a method,
1294 the name will be considered free *and* local in the
1295 class. It should be handled by the closure, as
1296 well as by the normal name loookup logic.
1297 */
1298 reftype = get_ref_type(c, name);
1299 if (reftype == CELL)
1300 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1301 else /* (reftype == FREE) */
1302 arg = compiler_lookup_arg(c->u->u_freevars, name);
1303 if (arg == -1) {
1304 printf("lookup %s in %s %d %d\n"
1305 "freevars of %s: %s\n",
1306 PyObject_REPR(name),
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001307 PyString_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 reftype, arg,
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001309 PyString_AS_STRING(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310 PyObject_REPR(co->co_freevars));
1311 Py_FatalError("compiler_make_closure()");
1312 }
1313 ADDOP_I(c, LOAD_CLOSURE, arg);
1314 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001315 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001317 ADDOP_I(c, MAKE_CLOSURE, args);
1318 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319}
1320
1321static int
1322compiler_decorators(struct compiler *c, asdl_seq* decos)
1323{
1324 int i;
1325
1326 if (!decos)
1327 return 1;
1328
1329 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001330 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 }
1332 return 1;
1333}
1334
1335static int
1336compiler_arguments(struct compiler *c, arguments_ty args)
1337{
1338 int i;
1339 int n = asdl_seq_LEN(args->args);
1340 /* Correctly handle nested argument lists */
1341 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001342 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343 if (arg->kind == Tuple_kind) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001344 PyObject *id = PyString_FromFormat(".%d", i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 if (id == NULL) {
1346 return 0;
1347 }
1348 if (!compiler_nameop(c, id, Load)) {
1349 Py_DECREF(id);
1350 return 0;
1351 }
1352 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001353 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 }
1355 }
1356 return 1;
1357}
1358
1359static int
1360compiler_function(struct compiler *c, stmt_ty s)
1361{
1362 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001363 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364 arguments_ty args = s->v.FunctionDef.args;
Christian Heimes5224d282008-02-23 15:01:05 +00001365 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001366 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367 int i, n, docstring;
1368
1369 assert(s->kind == FunctionDef_kind);
1370
1371 if (!compiler_decorators(c, decos))
1372 return 0;
1373 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001374 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1376 s->lineno))
1377 return 0;
1378
Anthony Baxter7b782b62006-04-11 12:01:56 +00001379 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001380 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001381 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001382 first_const = st->v.Expr.value->v.Str.s;
1383 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001384 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001385 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001388 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389 compiler_arguments(c, args);
1390
1391 c->u->u_argcount = asdl_seq_LEN(args->args);
1392 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001393 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001395 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1396 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397 }
1398 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001399 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400 if (co == NULL)
1401 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001403 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001404 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001405
1406 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1407 ADDOP_I(c, CALL_FUNCTION, 1);
1408 }
1409
1410 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1411}
1412
1413static int
1414compiler_class(struct compiler *c, stmt_ty s)
1415{
Christian Heimes5224d282008-02-23 15:01:05 +00001416 int n, i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001418 PyObject *str;
Christian Heimes5224d282008-02-23 15:01:05 +00001419 asdl_seq* decos = s->v.ClassDef.decorator_list;
1420
1421 if (!compiler_decorators(c, decos))
1422 return 0;
1423
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001424 /* push class name on stack, needed by BUILD_CLASS */
1425 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1426 /* push the tuple of base classes on the stack */
1427 n = asdl_seq_LEN(s->v.ClassDef.bases);
1428 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001429 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430 ADDOP_I(c, BUILD_TUPLE, n);
1431 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1432 s->lineno))
1433 return 0;
Amaury Forgeot d'Arc69b747b2008-03-28 20:30:50 +00001434 Py_XDECREF(c->u->u_private);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001435 c->u->u_private = s->v.ClassDef.name;
1436 Py_INCREF(c->u->u_private);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001437 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438 if (!str || !compiler_nameop(c, str, Load)) {
1439 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001440 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001442 }
1443
1444 Py_DECREF(str);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001445 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 if (!str || !compiler_nameop(c, str, Store)) {
1447 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001448 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001450 }
1451 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001453 if (!compiler_body(c, s->v.ClassDef.body)) {
1454 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001456 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001458 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1459 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001461 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462 if (co == NULL)
1463 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001465 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001466 Py_DECREF(co);
1467
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468 ADDOP_I(c, CALL_FUNCTION, 0);
1469 ADDOP(c, BUILD_CLASS);
Christian Heimes5224d282008-02-23 15:01:05 +00001470 /* apply decorators */
1471 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1472 ADDOP_I(c, CALL_FUNCTION, 1);
1473 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1475 return 0;
1476 return 1;
1477}
1478
1479static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001480compiler_ifexp(struct compiler *c, expr_ty e)
1481{
1482 basicblock *end, *next;
1483
1484 assert(e->kind == IfExp_kind);
1485 end = compiler_new_block(c);
1486 if (end == NULL)
1487 return 0;
1488 next = compiler_new_block(c);
1489 if (next == NULL)
1490 return 0;
1491 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001492 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001493 VISIT(c, expr, e->v.IfExp.body);
1494 ADDOP_JREL(c, JUMP_FORWARD, end);
1495 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001496 VISIT(c, expr, e->v.IfExp.orelse);
1497 compiler_use_next_block(c, end);
1498 return 1;
1499}
1500
1501static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502compiler_lambda(struct compiler *c, expr_ty e)
1503{
1504 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001505 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506 arguments_ty args = e->v.Lambda.args;
1507 assert(e->kind == Lambda_kind);
1508
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001509 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001510 name = PyString_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001511 if (!name)
1512 return 0;
1513 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514
1515 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001516 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1518 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001519
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001520 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521 compiler_arguments(c, args);
1522
1523 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001524 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson8d5934b2008-12-27 18:24:11 +00001525 if (c->u->u_ste->ste_generator) {
1526 ADDOP_IN_SCOPE(c, POP_TOP);
1527 }
1528 else {
1529 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1530 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001532 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533 if (co == NULL)
1534 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001536 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001537 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538
1539 return 1;
1540}
1541
1542static int
1543compiler_print(struct compiler *c, stmt_ty s)
1544{
1545 int i, n;
1546 bool dest;
1547
1548 assert(s->kind == Print_kind);
1549 n = asdl_seq_LEN(s->v.Print.values);
1550 dest = false;
1551 if (s->v.Print.dest) {
1552 VISIT(c, expr, s->v.Print.dest);
1553 dest = true;
1554 }
1555 for (i = 0; i < n; i++) {
1556 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1557 if (dest) {
1558 ADDOP(c, DUP_TOP);
1559 VISIT(c, expr, e);
1560 ADDOP(c, ROT_TWO);
1561 ADDOP(c, PRINT_ITEM_TO);
1562 }
1563 else {
1564 VISIT(c, expr, e);
1565 ADDOP(c, PRINT_ITEM);
1566 }
1567 }
1568 if (s->v.Print.nl) {
1569 if (dest)
1570 ADDOP(c, PRINT_NEWLINE_TO)
1571 else
1572 ADDOP(c, PRINT_NEWLINE)
1573 }
1574 else if (dest)
1575 ADDOP(c, POP_TOP);
1576 return 1;
1577}
1578
1579static int
1580compiler_if(struct compiler *c, stmt_ty s)
1581{
1582 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001583 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001584 assert(s->kind == If_kind);
1585 end = compiler_new_block(c);
1586 if (end == NULL)
1587 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001588
1589 constant = expr_constant(s->v.If.test);
1590 /* constant = 0: "if 0"
1591 * constant = 1: "if 1", "if 2", ...
1592 * constant = -1: rest */
1593 if (constant == 0) {
1594 if (s->v.If.orelse)
1595 VISIT_SEQ(c, stmt, s->v.If.orelse);
1596 } else if (constant == 1) {
1597 VISIT_SEQ(c, stmt, s->v.If.body);
1598 } else {
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001599 if (s->v.If.orelse) {
1600 next = compiler_new_block(c);
1601 if (next == NULL)
1602 return 0;
1603 }
1604 else
1605 next = end;
Georg Brandlddbaa662006-06-04 21:56:52 +00001606 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001607 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Georg Brandlddbaa662006-06-04 21:56:52 +00001608 VISIT_SEQ(c, stmt, s->v.If.body);
1609 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001610 if (s->v.If.orelse) {
1611 compiler_use_next_block(c, next);
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001612 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001613 }
Georg Brandlddbaa662006-06-04 21:56:52 +00001614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615 compiler_use_next_block(c, end);
1616 return 1;
1617}
1618
1619static int
1620compiler_for(struct compiler *c, stmt_ty s)
1621{
1622 basicblock *start, *cleanup, *end;
1623
1624 start = compiler_new_block(c);
1625 cleanup = compiler_new_block(c);
1626 end = compiler_new_block(c);
1627 if (start == NULL || end == NULL || cleanup == NULL)
1628 return 0;
1629 ADDOP_JREL(c, SETUP_LOOP, end);
1630 if (!compiler_push_fblock(c, LOOP, start))
1631 return 0;
1632 VISIT(c, expr, s->v.For.iter);
1633 ADDOP(c, GET_ITER);
1634 compiler_use_next_block(c, start);
1635 ADDOP_JREL(c, FOR_ITER, cleanup);
1636 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001637 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1639 compiler_use_next_block(c, cleanup);
1640 ADDOP(c, POP_BLOCK);
1641 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001642 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643 compiler_use_next_block(c, end);
1644 return 1;
1645}
1646
1647static int
1648compiler_while(struct compiler *c, stmt_ty s)
1649{
1650 basicblock *loop, *orelse, *end, *anchor = NULL;
1651 int constant = expr_constant(s->v.While.test);
1652
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001653 if (constant == 0) {
1654 if (s->v.While.orelse)
1655 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001656 return 1;
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001657 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658 loop = compiler_new_block(c);
1659 end = compiler_new_block(c);
1660 if (constant == -1) {
1661 anchor = compiler_new_block(c);
1662 if (anchor == NULL)
1663 return 0;
1664 }
1665 if (loop == NULL || end == NULL)
1666 return 0;
1667 if (s->v.While.orelse) {
1668 orelse = compiler_new_block(c);
1669 if (orelse == NULL)
1670 return 0;
1671 }
1672 else
1673 orelse = NULL;
1674
1675 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001676 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677 if (!compiler_push_fblock(c, LOOP, loop))
1678 return 0;
1679 if (constant == -1) {
1680 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001681 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001683 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001684 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1685
1686 /* XXX should the two POP instructions be in a separate block
1687 if there is no else clause ?
1688 */
1689
1690 if (constant == -1) {
1691 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692 ADDOP(c, POP_BLOCK);
1693 }
1694 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001695 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001696 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697 compiler_use_next_block(c, end);
1698
1699 return 1;
1700}
1701
1702static int
1703compiler_continue(struct compiler *c)
1704{
1705 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001706 static const char IN_FINALLY_ERROR_MSG[] =
1707 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708 int i;
1709
1710 if (!c->u->u_nfblocks)
1711 return compiler_error(c, LOOP_ERROR_MSG);
1712 i = c->u->u_nfblocks - 1;
1713 switch (c->u->u_fblock[i].fb_type) {
1714 case LOOP:
1715 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1716 break;
1717 case EXCEPT:
1718 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001719 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1720 /* Prevent continue anywhere under a finally
1721 even if hidden in a sub-try or except. */
1722 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1723 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1724 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001725 if (i == -1)
1726 return compiler_error(c, LOOP_ERROR_MSG);
1727 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1728 break;
1729 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001730 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001731 }
1732
1733 return 1;
1734}
1735
1736/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1737
1738 SETUP_FINALLY L
1739 <code for body>
1740 POP_BLOCK
1741 LOAD_CONST <None>
1742 L: <code for finalbody>
1743 END_FINALLY
1744
1745 The special instructions use the block stack. Each block
1746 stack entry contains the instruction that created it (here
1747 SETUP_FINALLY), the level of the value stack at the time the
1748 block stack entry was created, and a label (here L).
1749
1750 SETUP_FINALLY:
1751 Pushes the current value stack level and the label
1752 onto the block stack.
1753 POP_BLOCK:
1754 Pops en entry from the block stack, and pops the value
1755 stack until its level is the same as indicated on the
1756 block stack. (The label is ignored.)
1757 END_FINALLY:
1758 Pops a variable number of entries from the *value* stack
1759 and re-raises the exception they specify. The number of
1760 entries popped depends on the (pseudo) exception type.
1761
1762 The block stack is unwound when an exception is raised:
1763 when a SETUP_FINALLY entry is found, the exception is pushed
1764 onto the value stack (and the exception condition is cleared),
1765 and the interpreter jumps to the label gotten from the block
1766 stack.
1767*/
1768
1769static int
1770compiler_try_finally(struct compiler *c, stmt_ty s)
1771{
1772 basicblock *body, *end;
1773 body = compiler_new_block(c);
1774 end = compiler_new_block(c);
1775 if (body == NULL || end == NULL)
1776 return 0;
1777
1778 ADDOP_JREL(c, SETUP_FINALLY, end);
1779 compiler_use_next_block(c, body);
1780 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1781 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001782 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783 ADDOP(c, POP_BLOCK);
1784 compiler_pop_fblock(c, FINALLY_TRY, body);
1785
1786 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1787 compiler_use_next_block(c, end);
1788 if (!compiler_push_fblock(c, FINALLY_END, end))
1789 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001790 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 ADDOP(c, END_FINALLY);
1792 compiler_pop_fblock(c, FINALLY_END, end);
1793
1794 return 1;
1795}
1796
1797/*
1798 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1799 (The contents of the value stack is shown in [], with the top
1800 at the right; 'tb' is trace-back info, 'val' the exception's
1801 associated value, and 'exc' the exception.)
1802
1803 Value stack Label Instruction Argument
1804 [] SETUP_EXCEPT L1
1805 [] <code for S>
1806 [] POP_BLOCK
1807 [] JUMP_FORWARD L0
1808
1809 [tb, val, exc] L1: DUP )
1810 [tb, val, exc, exc] <evaluate E1> )
1811 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001812 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813 [tb, val, exc] POP
1814 [tb, val] <assign to V1> (or POP if no V1)
1815 [tb] POP
1816 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001817 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001819 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820 .............................etc.......................
1821
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001822 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001823
1824 [] L0: <next statement>
1825
1826 Of course, parts are not generated if Vi or Ei is not present.
1827*/
1828static int
1829compiler_try_except(struct compiler *c, stmt_ty s)
1830{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001831 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 int i, n;
1833
1834 body = compiler_new_block(c);
1835 except = compiler_new_block(c);
1836 orelse = compiler_new_block(c);
1837 end = compiler_new_block(c);
1838 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1839 return 0;
1840 ADDOP_JREL(c, SETUP_EXCEPT, except);
1841 compiler_use_next_block(c, body);
1842 if (!compiler_push_fblock(c, EXCEPT, body))
1843 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001844 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845 ADDOP(c, POP_BLOCK);
1846 compiler_pop_fblock(c, EXCEPT, body);
1847 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1848 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1849 compiler_use_next_block(c, except);
1850 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001851 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852 s->v.TryExcept.handlers, i);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001853 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +00001855 c->u->u_lineno_set = false;
1856 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857 except = compiler_new_block(c);
1858 if (except == NULL)
1859 return 0;
Georg Brandla48f3ab2008-03-30 06:40:17 +00001860 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 ADDOP(c, DUP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001862 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001864 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 }
1866 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001867 if (handler->v.ExceptHandler.name) {
1868 VISIT(c, expr, handler->v.ExceptHandler.name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 }
1870 else {
1871 ADDOP(c, POP_TOP);
1872 }
1873 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001874 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875 ADDOP_JREL(c, JUMP_FORWARD, end);
1876 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877 }
1878 ADDOP(c, END_FINALLY);
1879 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001880 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881 compiler_use_next_block(c, end);
1882 return 1;
1883}
1884
1885static int
1886compiler_import_as(struct compiler *c, identifier name, identifier asname)
1887{
1888 /* The IMPORT_NAME opcode was already generated. This function
1889 merely needs to bind the result to a name.
1890
1891 If there is a dot in name, we need to split it and emit a
1892 LOAD_ATTR for each name.
1893 */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001894 const char *src = PyString_AS_STRING(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895 const char *dot = strchr(src, '.');
1896 if (dot) {
1897 /* Consume the base module name to get the first attribute */
1898 src = dot + 1;
1899 while (dot) {
1900 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001901 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001902 dot = strchr(src, '.');
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001903 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001905 if (!attr)
1906 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001908 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909 src = dot + 1;
1910 }
1911 }
1912 return compiler_nameop(c, asname, Store);
1913}
1914
1915static int
1916compiler_import(struct compiler *c, stmt_ty s)
1917{
1918 /* The Import node stores a module name like a.b.c as a single
1919 string. This is convenient for all cases except
1920 import a.b.c as d
1921 where we need to parse that string to extract the individual
1922 module names.
1923 XXX Perhaps change the representation to make this case simpler?
1924 */
1925 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001928 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001930 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931
Neal Norwitzcbce2802006-04-03 06:26:32 +00001932 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001933 level = PyInt_FromLong(0);
1934 else
1935 level = PyInt_FromLong(-1);
1936
1937 if (level == NULL)
1938 return 0;
1939
1940 ADDOP_O(c, LOAD_CONST, level, consts);
1941 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1943 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1944
1945 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001946 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001947 if (!r)
1948 return r;
1949 }
1950 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951 identifier tmp = alias->name;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001952 const char *base = PyString_AS_STRING(alias->name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953 char *dot = strchr(base, '.');
1954 if (dot)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001955 tmp = PyString_FromStringAndSize(base,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 dot - base);
1957 r = compiler_nameop(c, tmp, Store);
1958 if (dot) {
1959 Py_DECREF(tmp);
1960 }
1961 if (!r)
1962 return r;
1963 }
1964 }
1965 return 1;
1966}
1967
1968static int
1969compiler_from_import(struct compiler *c, stmt_ty s)
1970{
1971 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972
1973 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001974 PyObject *level;
Benjamin Petersona72be3b2009-06-13 20:23:33 +00001975 static PyObject *empty_string;
1976
1977 if (!empty_string) {
1978 empty_string = PyString_FromString("");
1979 if (!empty_string)
1980 return 0;
1981 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001982
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001983 if (!names)
1984 return 0;
1985
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001986 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001987 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001988 level = PyInt_FromLong(-1);
1989 else
1990 level = PyInt_FromLong(s->v.ImportFrom.level);
1991
1992 if (!level) {
1993 Py_DECREF(names);
1994 return 0;
1995 }
1996
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 /* build up the names */
1998 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001999 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000 Py_INCREF(alias->name);
2001 PyTuple_SET_ITEM(names, i, alias->name);
2002 }
2003
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002004 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2005 !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
2006 Py_DECREF(level);
2007 Py_DECREF(names);
2008 return compiler_error(c, "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002009 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010 }
2011
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002012 ADDOP_O(c, LOAD_CONST, level, consts);
2013 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002015 Py_DECREF(names);
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002016 if (s->v.ImportFrom.module) {
2017 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2018 }
2019 else {
2020 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2021 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002023 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 identifier store_name;
2025
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002026 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 assert(n == 1);
2028 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030 }
2031
2032 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2033 store_name = alias->name;
2034 if (alias->asname)
2035 store_name = alias->asname;
2036
2037 if (!compiler_nameop(c, store_name, Store)) {
2038 Py_DECREF(names);
2039 return 0;
2040 }
2041 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002042 /* remove imported module */
2043 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044 return 1;
2045}
2046
2047static int
2048compiler_assert(struct compiler *c, stmt_ty s)
2049{
2050 static PyObject *assertion_error = NULL;
2051 basicblock *end;
2052
2053 if (Py_OptimizeFlag)
2054 return 1;
2055 if (assertion_error == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002056 assertion_error = PyString_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 if (assertion_error == NULL)
2058 return 0;
2059 }
Neal Norwitz400aeda2008-03-15 22:03:18 +00002060 if (s->v.Assert.test->kind == Tuple_kind &&
2061 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2062 const char* msg =
2063 "assertion is always true, perhaps remove parentheses?";
2064 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2065 c->u->u_lineno, NULL, NULL) == -1)
2066 return 0;
2067 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 VISIT(c, expr, s->v.Assert.test);
2069 end = compiler_new_block(c);
2070 if (end == NULL)
2071 return 0;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002072 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2074 if (s->v.Assert.msg) {
2075 VISIT(c, expr, s->v.Assert.msg);
2076 ADDOP_I(c, RAISE_VARARGS, 2);
2077 }
2078 else {
2079 ADDOP_I(c, RAISE_VARARGS, 1);
2080 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002081 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 return 1;
2083}
2084
2085static int
2086compiler_visit_stmt(struct compiler *c, stmt_ty s)
2087{
2088 int i, n;
2089
Neal Norwitzf733a012006-10-29 18:30:10 +00002090 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 c->u->u_lineno = s->lineno;
2092 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002093
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 if (c->u->u_ste->ste_type != FunctionBlock)
2101 return compiler_error(c, "'return' outside function");
2102 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 VISIT(c, expr, s->v.Return.value);
2104 }
2105 else
2106 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2107 ADDOP(c, RETURN_VALUE);
2108 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002110 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002112 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 n = asdl_seq_LEN(s->v.Assign.targets);
2114 VISIT(c, expr, s->v.Assign.value);
2115 for (i = 0; i < n; i++) {
2116 if (i < n - 1)
2117 ADDOP(c, DUP_TOP);
2118 VISIT(c, expr,
2119 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2120 }
2121 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002122 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002124 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002126 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002128 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002130 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002132 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 n = 0;
2134 if (s->v.Raise.type) {
2135 VISIT(c, expr, s->v.Raise.type);
2136 n++;
2137 if (s->v.Raise.inst) {
2138 VISIT(c, expr, s->v.Raise.inst);
2139 n++;
2140 if (s->v.Raise.tback) {
2141 VISIT(c, expr, s->v.Raise.tback);
2142 n++;
2143 }
2144 }
2145 }
2146 ADDOP_I(c, RAISE_VARARGS, n);
2147 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002148 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002150 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002152 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002154 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002156 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002158 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159 VISIT(c, expr, s->v.Exec.body);
2160 if (s->v.Exec.globals) {
2161 VISIT(c, expr, s->v.Exec.globals);
2162 if (s->v.Exec.locals) {
2163 VISIT(c, expr, s->v.Exec.locals);
2164 } else {
2165 ADDOP(c, DUP_TOP);
2166 }
2167 } else {
2168 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2169 ADDOP(c, DUP_TOP);
2170 }
2171 ADDOP(c, EXEC_STMT);
2172 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002173 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002175 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002177 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 ADDOP(c, PRINT_EXPR);
2179 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002180 else if (s->v.Expr.value->kind != Str_kind &&
2181 s->v.Expr.value->kind != Num_kind) {
2182 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183 ADDOP(c, POP_TOP);
2184 }
2185 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002186 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002187 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002188 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002189 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 return compiler_error(c, "'break' outside loop");
2191 ADDOP(c, BREAK_LOOP);
2192 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002193 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002195 case With_kind:
2196 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 }
2198 return 1;
2199}
2200
2201static int
2202unaryop(unaryop_ty op)
2203{
2204 switch (op) {
2205 case Invert:
2206 return UNARY_INVERT;
2207 case Not:
2208 return UNARY_NOT;
2209 case UAdd:
2210 return UNARY_POSITIVE;
2211 case USub:
2212 return UNARY_NEGATIVE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002213 default:
2214 PyErr_Format(PyExc_SystemError,
2215 "unary op %d should not be possible", op);
2216 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002218}
2219
2220static int
2221binop(struct compiler *c, operator_ty op)
2222{
2223 switch (op) {
2224 case Add:
2225 return BINARY_ADD;
2226 case Sub:
2227 return BINARY_SUBTRACT;
2228 case Mult:
2229 return BINARY_MULTIPLY;
2230 case Div:
2231 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2232 return BINARY_TRUE_DIVIDE;
2233 else
2234 return BINARY_DIVIDE;
2235 case Mod:
2236 return BINARY_MODULO;
2237 case Pow:
2238 return BINARY_POWER;
2239 case LShift:
2240 return BINARY_LSHIFT;
2241 case RShift:
2242 return BINARY_RSHIFT;
2243 case BitOr:
2244 return BINARY_OR;
2245 case BitXor:
2246 return BINARY_XOR;
2247 case BitAnd:
2248 return BINARY_AND;
2249 case FloorDiv:
2250 return BINARY_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002251 default:
2252 PyErr_Format(PyExc_SystemError,
2253 "binary op %d should not be possible", op);
2254 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256}
2257
2258static int
2259cmpop(cmpop_ty op)
2260{
2261 switch (op) {
2262 case Eq:
2263 return PyCmp_EQ;
2264 case NotEq:
2265 return PyCmp_NE;
2266 case Lt:
2267 return PyCmp_LT;
2268 case LtE:
2269 return PyCmp_LE;
2270 case Gt:
2271 return PyCmp_GT;
2272 case GtE:
2273 return PyCmp_GE;
2274 case Is:
2275 return PyCmp_IS;
2276 case IsNot:
2277 return PyCmp_IS_NOT;
2278 case In:
2279 return PyCmp_IN;
2280 case NotIn:
2281 return PyCmp_NOT_IN;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002282 default:
2283 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
2287static int
2288inplace_binop(struct compiler *c, operator_ty op)
2289{
2290 switch (op) {
2291 case Add:
2292 return INPLACE_ADD;
2293 case Sub:
2294 return INPLACE_SUBTRACT;
2295 case Mult:
2296 return INPLACE_MULTIPLY;
2297 case Div:
2298 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2299 return INPLACE_TRUE_DIVIDE;
2300 else
2301 return INPLACE_DIVIDE;
2302 case Mod:
2303 return INPLACE_MODULO;
2304 case Pow:
2305 return INPLACE_POWER;
2306 case LShift:
2307 return INPLACE_LSHIFT;
2308 case RShift:
2309 return INPLACE_RSHIFT;
2310 case BitOr:
2311 return INPLACE_OR;
2312 case BitXor:
2313 return INPLACE_XOR;
2314 case BitAnd:
2315 return INPLACE_AND;
2316 case FloorDiv:
2317 return INPLACE_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002318 default:
2319 PyErr_Format(PyExc_SystemError,
2320 "inplace binary op %d should not be possible", op);
2321 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323}
2324
2325static int
2326compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2327{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002328 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2330
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002331 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002332 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 /* XXX AugStore isn't used anywhere! */
2334
Neal Norwitz0031ff32008-02-25 01:45:37 +00002335 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002336 if (!mangled)
2337 return 0;
2338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339 op = 0;
2340 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002341 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342 switch (scope) {
2343 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002344 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 optype = OP_DEREF;
2346 break;
2347 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002348 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 optype = OP_DEREF;
2350 break;
2351 case LOCAL:
2352 if (c->u->u_ste->ste_type == FunctionBlock)
2353 optype = OP_FAST;
2354 break;
2355 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002356 if (c->u->u_ste->ste_type == FunctionBlock &&
2357 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358 optype = OP_GLOBAL;
2359 break;
2360 case GLOBAL_EXPLICIT:
2361 optype = OP_GLOBAL;
2362 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002363 default:
2364 /* scope can be 0 */
2365 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366 }
2367
2368 /* XXX Leave assert here, but handle __doc__ and the like better */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002369 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370
2371 switch (optype) {
2372 case OP_DEREF:
2373 switch (ctx) {
2374 case Load: op = LOAD_DEREF; break;
2375 case Store: op = STORE_DEREF; break;
2376 case AugLoad:
2377 case AugStore:
2378 break;
2379 case Del:
2380 PyErr_Format(PyExc_SyntaxError,
2381 "can not delete variable '%s' referenced "
2382 "in nested scope",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002383 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002384 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002387 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002388 PyErr_SetString(PyExc_SystemError,
2389 "param invalid for deref variable");
2390 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391 }
2392 break;
2393 case OP_FAST:
2394 switch (ctx) {
2395 case Load: op = LOAD_FAST; break;
2396 case Store: op = STORE_FAST; break;
2397 case Del: op = DELETE_FAST; break;
2398 case AugLoad:
2399 case AugStore:
2400 break;
2401 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002402 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002403 PyErr_SetString(PyExc_SystemError,
2404 "param invalid for local variable");
2405 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002407 ADDOP_O(c, op, mangled, varnames);
2408 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409 return 1;
2410 case OP_GLOBAL:
2411 switch (ctx) {
2412 case Load: op = LOAD_GLOBAL; break;
2413 case Store: op = STORE_GLOBAL; break;
2414 case Del: op = DELETE_GLOBAL; break;
2415 case AugLoad:
2416 case AugStore:
2417 break;
2418 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002419 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002420 PyErr_SetString(PyExc_SystemError,
2421 "param invalid for global variable");
2422 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423 }
2424 break;
2425 case OP_NAME:
2426 switch (ctx) {
2427 case Load: op = LOAD_NAME; break;
2428 case Store: op = STORE_NAME; break;
2429 case Del: op = DELETE_NAME; break;
2430 case AugLoad:
2431 case AugStore:
2432 break;
2433 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002434 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002435 PyErr_SetString(PyExc_SystemError,
2436 "param invalid for name variable");
2437 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438 }
2439 break;
2440 }
2441
2442 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002443 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002444 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002445 if (arg < 0)
2446 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002447 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448}
2449
2450static int
2451compiler_boolop(struct compiler *c, expr_ty e)
2452{
2453 basicblock *end;
2454 int jumpi, i, n;
2455 asdl_seq *s;
2456
2457 assert(e->kind == BoolOp_kind);
2458 if (e->v.BoolOp.op == And)
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002459 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 else
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002461 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002463 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 return 0;
2465 s = e->v.BoolOp.values;
2466 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002467 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002469 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002470 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002472 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473 compiler_use_next_block(c, end);
2474 return 1;
2475}
2476
2477static int
2478compiler_list(struct compiler *c, expr_ty e)
2479{
2480 int n = asdl_seq_LEN(e->v.List.elts);
2481 if (e->v.List.ctx == Store) {
2482 ADDOP_I(c, UNPACK_SEQUENCE, n);
2483 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002484 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 if (e->v.List.ctx == Load) {
2486 ADDOP_I(c, BUILD_LIST, n);
2487 }
2488 return 1;
2489}
2490
2491static int
2492compiler_tuple(struct compiler *c, expr_ty e)
2493{
2494 int n = asdl_seq_LEN(e->v.Tuple.elts);
2495 if (e->v.Tuple.ctx == Store) {
2496 ADDOP_I(c, UNPACK_SEQUENCE, n);
2497 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002498 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 if (e->v.Tuple.ctx == Load) {
2500 ADDOP_I(c, BUILD_TUPLE, n);
2501 }
2502 return 1;
2503}
2504
2505static int
2506compiler_compare(struct compiler *c, expr_ty e)
2507{
2508 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002509 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510
2511 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2512 VISIT(c, expr, e->v.Compare.left);
2513 n = asdl_seq_LEN(e->v.Compare.ops);
2514 assert(n > 0);
2515 if (n > 1) {
2516 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002517 if (cleanup == NULL)
2518 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002519 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002520 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521 }
2522 for (i = 1; i < n; i++) {
2523 ADDOP(c, DUP_TOP);
2524 ADDOP(c, ROT_THREE);
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(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002527 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002528 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002531 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002532 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002534 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002536 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 if (n > 1) {
2538 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 if (end == NULL)
2540 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 ADDOP_JREL(c, JUMP_FORWARD, end);
2542 compiler_use_next_block(c, cleanup);
2543 ADDOP(c, ROT_TWO);
2544 ADDOP(c, POP_TOP);
2545 compiler_use_next_block(c, end);
2546 }
2547 return 1;
2548}
2549
2550static int
2551compiler_call(struct compiler *c, expr_ty e)
2552{
2553 int n, code = 0;
2554
2555 VISIT(c, expr, e->v.Call.func);
2556 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002557 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002559 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2561 }
2562 if (e->v.Call.starargs) {
2563 VISIT(c, expr, e->v.Call.starargs);
2564 code |= 1;
2565 }
2566 if (e->v.Call.kwargs) {
2567 VISIT(c, expr, e->v.Call.kwargs);
2568 code |= 2;
2569 }
2570 switch (code) {
2571 case 0:
2572 ADDOP_I(c, CALL_FUNCTION, n);
2573 break;
2574 case 1:
2575 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2576 break;
2577 case 2:
2578 ADDOP_I(c, CALL_FUNCTION_KW, n);
2579 break;
2580 case 3:
2581 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2582 break;
2583 }
2584 return 1;
2585}
2586
2587static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002588compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
2589 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590{
2591 /* generate code for the iterator, then each of the ifs,
2592 and then write to the element */
2593
2594 comprehension_ty l;
2595 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002596 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597
2598 start = compiler_new_block(c);
2599 skip = compiler_new_block(c);
2600 if_cleanup = compiler_new_block(c);
2601 anchor = compiler_new_block(c);
2602
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002603 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2604 anchor == NULL)
2605 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606
Anthony Baxter7b782b62006-04-11 12:01:56 +00002607 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608 VISIT(c, expr, l->iter);
2609 ADDOP(c, GET_ITER);
2610 compiler_use_next_block(c, start);
2611 ADDOP_JREL(c, FOR_ITER, anchor);
2612 NEXT_BLOCK(c);
2613 VISIT(c, expr, l->target);
2614
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002615 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 n = asdl_seq_LEN(l->ifs);
2617 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002618 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002620 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622 }
2623
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002624 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitroud0c35152008-12-17 00:38:28 +00002625 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002628 /* only append after the last for generator */
2629 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002630 VISIT(c, expr, elt);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002631 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632
2633 compiler_use_next_block(c, skip);
2634 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002635 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2637 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638
2639 return 1;
2640}
2641
2642static int
2643compiler_listcomp(struct compiler *c, expr_ty e)
2644{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 assert(e->kind == ListComp_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 ADDOP_I(c, BUILD_LIST, 0);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002647 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2648 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649}
2650
2651static int
2652compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002653 asdl_seq *generators, int gen_index,
2654 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655{
2656 /* generate code for the iterator, then each of the ifs,
2657 and then write to the element */
2658
2659 comprehension_ty ge;
2660 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662
2663 start = compiler_new_block(c);
2664 skip = compiler_new_block(c);
2665 if_cleanup = compiler_new_block(c);
2666 anchor = compiler_new_block(c);
2667 end = compiler_new_block(c);
2668
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 anchor == NULL || end == NULL)
2671 return 0;
2672
Anthony Baxter7b782b62006-04-11 12:01:56 +00002673 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 ADDOP_JREL(c, SETUP_LOOP, end);
2675 if (!compiler_push_fblock(c, LOOP, start))
2676 return 0;
2677
2678 if (gen_index == 0) {
2679 /* Receive outermost iter as an implicit argument */
2680 c->u->u_argcount = 1;
2681 ADDOP_I(c, LOAD_FAST, 0);
2682 }
2683 else {
2684 /* Sub-iter - calculate on the fly */
2685 VISIT(c, expr, ge->iter);
2686 ADDOP(c, GET_ITER);
2687 }
2688 compiler_use_next_block(c, start);
2689 ADDOP_JREL(c, FOR_ITER, anchor);
2690 NEXT_BLOCK(c);
2691 VISIT(c, expr, ge->target);
2692
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 n = asdl_seq_LEN(ge->ifs);
2695 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002696 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002698 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 NEXT_BLOCK(c);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002700 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002702 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2704 return 0;
2705
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 /* only append after the last 'for' generator */
2707 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 VISIT(c, expr, elt);
2709 ADDOP(c, YIELD_VALUE);
2710 ADDOP(c, POP_TOP);
2711
2712 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002713 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002714 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2716 compiler_use_next_block(c, anchor);
2717 ADDOP(c, POP_BLOCK);
2718 compiler_pop_fblock(c, LOOP, start);
2719 compiler_use_next_block(c, end);
2720
2721 return 1;
2722}
2723
2724static int
2725compiler_genexp(struct compiler *c, expr_ty e)
2726{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002727 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728 PyCodeObject *co;
2729 expr_ty outermost_iter = ((comprehension_ty)
2730 (asdl_seq_GET(e->v.GeneratorExp.generators,
2731 0)))->iter;
2732
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002733 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002734 name = PyString_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002735 if (!name)
2736 return 0;
2737 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738
2739 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2740 return 0;
2741 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2742 e->v.GeneratorExp.elt);
2743 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002744 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745 if (co == NULL)
2746 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002748 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002749 Py_DECREF(co);
2750
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751 VISIT(c, expr, outermost_iter);
2752 ADDOP(c, GET_ITER);
2753 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754
2755 return 1;
2756}
2757
2758static int
2759compiler_visit_keyword(struct compiler *c, keyword_ty k)
2760{
2761 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2762 VISIT(c, expr, k->value);
2763 return 1;
2764}
2765
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002766/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767 whether they are true or false.
2768
2769 Return values: 1 for true, 0 for false, -1 for non-constant.
2770 */
2771
2772static int
2773expr_constant(expr_ty e)
2774{
2775 switch (e->kind) {
2776 case Num_kind:
2777 return PyObject_IsTrue(e->v.Num.n);
2778 case Str_kind:
2779 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002780 case Name_kind:
2781 /* __debug__ is not assignable, so we can optimize
2782 * it away in if and while statements */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002783 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002784 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002785 return ! Py_OptimizeFlag;
2786 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787 default:
2788 return -1;
2789 }
2790}
2791
Guido van Rossumc2e20742006-02-27 22:32:47 +00002792/*
2793 Implements the with statement from PEP 343.
2794
2795 The semantics outlined in that PEP are as follows:
2796
2797 with EXPR as VAR:
2798 BLOCK
2799
2800 It is implemented roughly as:
2801
Guido van Rossumda5b7012006-05-02 19:47:52 +00002802 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002803 exit = context.__exit__ # not calling it
2804 value = context.__enter__()
2805 try:
2806 VAR = value # if VAR present in the syntax
2807 BLOCK
2808 finally:
2809 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002810 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002811 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002812 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002813 exit(*exc)
2814 */
2815static int
2816compiler_with(struct compiler *c, stmt_ty s)
2817{
Guido van Rossumc2e20742006-02-27 22:32:47 +00002818 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002819
2820 assert(s->kind == With_kind);
2821
Guido van Rossumc2e20742006-02-27 22:32:47 +00002822 block = compiler_new_block(c);
2823 finally = compiler_new_block(c);
2824 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002825 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002826
Guido van Rossumda5b7012006-05-02 19:47:52 +00002827 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002828 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002829 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002831 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002832 compiler_use_next_block(c, block);
2833 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002834 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002835 }
2836
2837 if (s->v.With.optional_vars) {
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002838 VISIT(c, expr, s->v.With.optional_vars);
2839 }
2840 else {
2841 /* Discard result from context.__enter__() */
2842 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002843 }
2844
2845 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002846 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002847
2848 /* End of try block; start the finally block */
2849 ADDOP(c, POP_BLOCK);
2850 compiler_pop_fblock(c, FINALLY_TRY, block);
2851
2852 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2853 compiler_use_next_block(c, finally);
2854 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002855 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002856
Nick Coghlan7af53be2008-03-07 14:13:28 +00002857 /* Finally block starts; context.__exit__ is on the stack under
2858 the exception or return information. Just issue our magic
2859 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002860 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002861
2862 /* Finally block ends. */
2863 ADDOP(c, END_FINALLY);
2864 compiler_pop_fblock(c, FINALLY_END, finally);
2865 return 1;
2866}
2867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868static int
2869compiler_visit_expr(struct compiler *c, expr_ty e)
2870{
2871 int i, n;
2872
Neal Norwitzf733a012006-10-29 18:30:10 +00002873 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002874 set a new line number for the next instruction.
2875 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876 if (e->lineno > c->u->u_lineno) {
2877 c->u->u_lineno = e->lineno;
2878 c->u->u_lineno_set = false;
2879 }
2880 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002881 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002883 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 VISIT(c, expr, e->v.BinOp.left);
2885 VISIT(c, expr, e->v.BinOp.right);
2886 ADDOP(c, binop(c, e->v.BinOp.op));
2887 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002888 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889 VISIT(c, expr, e->v.UnaryOp.operand);
2890 ADDOP(c, unaryop(e->v.UnaryOp.op));
2891 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002892 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002894 case IfExp_kind:
2895 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettinger70fcfd02007-12-19 22:14:34 +00002898 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002900 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002901 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00002902 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002903 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00002904 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905 }
2906 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002907 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002909 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910 return compiler_genexp(c, e);
2911 case Yield_kind:
2912 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002913 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 if (e->v.Yield.value) {
2915 VISIT(c, expr, e->v.Yield.value);
2916 }
2917 else {
2918 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2919 }
2920 ADDOP(c, YIELD_VALUE);
2921 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002922 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002924 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 VISIT(c, expr, e->v.Repr.value);
2928 ADDOP(c, UNARY_CONVERT);
2929 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002930 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2932 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002933 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2935 break;
2936 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002937 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 if (e->v.Attribute.ctx != AugStore)
2939 VISIT(c, expr, e->v.Attribute.value);
2940 switch (e->v.Attribute.ctx) {
2941 case AugLoad:
2942 ADDOP(c, DUP_TOP);
2943 /* Fall through to load */
2944 case Load:
2945 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2946 break;
2947 case AugStore:
2948 ADDOP(c, ROT_TWO);
2949 /* Fall through to save */
2950 case Store:
2951 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2952 break;
2953 case Del:
2954 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2955 break;
2956 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002957 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002958 PyErr_SetString(PyExc_SystemError,
2959 "param invalid in attribute expression");
2960 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 }
2962 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002963 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964 switch (e->v.Subscript.ctx) {
2965 case AugLoad:
2966 VISIT(c, expr, e->v.Subscript.value);
2967 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2968 break;
2969 case Load:
2970 VISIT(c, expr, e->v.Subscript.value);
2971 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2972 break;
2973 case AugStore:
2974 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2975 break;
2976 case Store:
2977 VISIT(c, expr, e->v.Subscript.value);
2978 VISIT_SLICE(c, e->v.Subscript.slice, Store);
2979 break;
2980 case Del:
2981 VISIT(c, expr, e->v.Subscript.value);
2982 VISIT_SLICE(c, e->v.Subscript.slice, Del);
2983 break;
2984 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002985 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002986 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002987 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00002988 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 }
2990 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002991 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
2993 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002994 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002996 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 return compiler_tuple(c, e);
2998 }
2999 return 1;
3000}
3001
3002static int
3003compiler_augassign(struct compiler *c, stmt_ty s)
3004{
3005 expr_ty e = s->v.AugAssign.target;
3006 expr_ty auge;
3007
3008 assert(s->kind == AugAssign_kind);
3009
3010 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003011 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003013 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003014 if (auge == NULL)
3015 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 VISIT(c, expr, auge);
3017 VISIT(c, expr, s->v.AugAssign.value);
3018 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3019 auge->v.Attribute.ctx = AugStore;
3020 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 break;
3022 case Subscript_kind:
3023 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003024 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003025 if (auge == NULL)
3026 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 VISIT(c, expr, auge);
3028 VISIT(c, expr, s->v.AugAssign.value);
3029 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003030 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003032 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003034 if (!compiler_nameop(c, e->v.Name.id, Load))
3035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036 VISIT(c, expr, s->v.AugAssign.value);
3037 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3038 return compiler_nameop(c, e->v.Name.id, Store);
3039 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003040 PyErr_Format(PyExc_SystemError,
3041 "invalid node type (%d) for augmented assignment",
3042 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 }
3045 return 1;
3046}
3047
3048static int
3049compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3050{
3051 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003052 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3053 PyErr_SetString(PyExc_SystemError,
3054 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003056 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057 f = &c->u->u_fblock[c->u->u_nfblocks++];
3058 f->fb_type = t;
3059 f->fb_block = b;
3060 return 1;
3061}
3062
3063static void
3064compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3065{
3066 struct compiler_unit *u = c->u;
3067 assert(u->u_nfblocks > 0);
3068 u->u_nfblocks--;
3069 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3070 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3071}
3072
Jeremy Hylton82271f12006-10-04 02:24:52 +00003073static int
3074compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003075 int i;
3076 struct compiler_unit *u = c->u;
3077 for (i = 0; i < u->u_nfblocks; ++i) {
3078 if (u->u_fblock[i].fb_type == LOOP)
3079 return 1;
3080 }
3081 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003082}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083/* Raises a SyntaxError and returns 0.
3084 If something goes wrong, a different exception may be raised.
3085*/
3086
3087static int
3088compiler_error(struct compiler *c, const char *errstr)
3089{
3090 PyObject *loc;
3091 PyObject *u = NULL, *v = NULL;
3092
3093 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3094 if (!loc) {
3095 Py_INCREF(Py_None);
3096 loc = Py_None;
3097 }
3098 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3099 Py_None, loc);
3100 if (!u)
3101 goto exit;
3102 v = Py_BuildValue("(zO)", errstr, u);
3103 if (!v)
3104 goto exit;
3105 PyErr_SetObject(PyExc_SyntaxError, v);
3106 exit:
3107 Py_DECREF(loc);
3108 Py_XDECREF(u);
3109 Py_XDECREF(v);
3110 return 0;
3111}
3112
3113static int
3114compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003115 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003116{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003117 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003119 /* XXX this code is duplicated */
3120 switch (ctx) {
3121 case AugLoad: /* fall through to Load */
3122 case Load: op = BINARY_SUBSCR; break;
3123 case AugStore:/* fall through to Store */
3124 case Store: op = STORE_SUBSCR; break;
3125 case Del: op = DELETE_SUBSCR; break;
3126 case Param:
3127 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003128 "invalid %s kind %d in subscript\n",
3129 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003130 return 0;
3131 }
3132 if (ctx == AugLoad) {
3133 ADDOP_I(c, DUP_TOPX, 2);
3134 }
3135 else if (ctx == AugStore) {
3136 ADDOP(c, ROT_THREE);
3137 }
3138 ADDOP(c, op);
3139 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140}
3141
3142static int
3143compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3144{
3145 int n = 2;
3146 assert(s->kind == Slice_kind);
3147
3148 /* only handles the cases where BUILD_SLICE is emitted */
3149 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151 }
3152 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003153 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003155
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003157 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158 }
3159 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161 }
3162
3163 if (s->v.Slice.step) {
3164 n++;
3165 VISIT(c, expr, s->v.Slice.step);
3166 }
3167 ADDOP_I(c, BUILD_SLICE, n);
3168 return 1;
3169}
3170
3171static int
3172compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3173{
3174 int op = 0, slice_offset = 0, stack_count = 0;
3175
3176 assert(s->v.Slice.step == NULL);
3177 if (s->v.Slice.lower) {
3178 slice_offset++;
3179 stack_count++;
3180 if (ctx != AugStore)
3181 VISIT(c, expr, s->v.Slice.lower);
3182 }
3183 if (s->v.Slice.upper) {
3184 slice_offset += 2;
3185 stack_count++;
3186 if (ctx != AugStore)
3187 VISIT(c, expr, s->v.Slice.upper);
3188 }
3189
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003190 if (ctx == AugLoad) {
3191 switch (stack_count) {
3192 case 0: ADDOP(c, DUP_TOP); break;
3193 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3194 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3195 }
3196 }
3197 else if (ctx == AugStore) {
3198 switch (stack_count) {
3199 case 0: ADDOP(c, ROT_TWO); break;
3200 case 1: ADDOP(c, ROT_THREE); break;
3201 case 2: ADDOP(c, ROT_FOUR); break;
3202 }
3203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204
3205 switch (ctx) {
3206 case AugLoad: /* fall through to Load */
3207 case Load: op = SLICE; break;
3208 case AugStore:/* fall through to Store */
3209 case Store: op = STORE_SLICE; break;
3210 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003211 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003212 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003213 PyErr_SetString(PyExc_SystemError,
3214 "param invalid in simple slice");
3215 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216 }
3217
3218 ADDOP(c, op + slice_offset);
3219 return 1;
3220}
3221
3222static int
3223compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3224 expr_context_ty ctx)
3225{
3226 switch (s->kind) {
3227 case Ellipsis_kind:
3228 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3229 break;
3230 case Slice_kind:
3231 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 case Index_kind:
3233 VISIT(c, expr, s->v.Index.value);
3234 break;
3235 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003236 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003237 PyErr_SetString(PyExc_SystemError,
3238 "extended slice invalid in nested slice");
3239 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240 }
3241 return 1;
3242}
3243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244static int
3245compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3246{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003247 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003249 case Index_kind:
3250 kindname = "index";
3251 if (ctx != AugStore) {
3252 VISIT(c, expr, s->v.Index.value);
3253 }
3254 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003256 kindname = "ellipsis";
3257 if (ctx != AugStore) {
3258 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 break;
3261 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003262 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 if (!s->v.Slice.step)
3264 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003265 if (ctx != AugStore) {
3266 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 return 0;
3268 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003269 break;
3270 case ExtSlice_kind:
3271 kindname = "extended slice";
3272 if (ctx != AugStore) {
3273 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3274 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003275 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003276 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003277 if (!compiler_visit_nested_slice(c, sub, ctx))
3278 return 0;
3279 }
3280 ADDOP_I(c, BUILD_TUPLE, n);
3281 }
3282 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003283 default:
3284 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003285 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003288 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289}
3290
Neal Norwitzf733a012006-10-29 18:30:10 +00003291
3292/* End of the compiler section, beginning of the assembler section */
3293
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294/* do depth-first search of basic block graph, starting with block.
3295 post records the block indices in post-order.
3296
3297 XXX must handle implicit jumps from one block to next
3298*/
3299
Neal Norwitzf733a012006-10-29 18:30:10 +00003300struct assembler {
3301 PyObject *a_bytecode; /* string containing bytecode */
3302 int a_offset; /* offset into bytecode */
3303 int a_nblocks; /* number of reachable blocks */
3304 basicblock **a_postorder; /* list of blocks in dfs postorder */
3305 PyObject *a_lnotab; /* string containing lnotab */
3306 int a_lnotab_off; /* offset into lnotab */
3307 int a_lineno; /* last lineno of emitted instruction */
3308 int a_lineno_off; /* bytecode offset of last lineno */
3309};
3310
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311static void
3312dfs(struct compiler *c, basicblock *b, struct assembler *a)
3313{
3314 int i;
3315 struct instr *instr = NULL;
3316
3317 if (b->b_seen)
3318 return;
3319 b->b_seen = 1;
3320 if (b->b_next != NULL)
3321 dfs(c, b->b_next, a);
3322 for (i = 0; i < b->b_iused; i++) {
3323 instr = &b->b_instr[i];
3324 if (instr->i_jrel || instr->i_jabs)
3325 dfs(c, instr->i_target, a);
3326 }
3327 a->a_postorder[a->a_nblocks++] = b;
3328}
3329
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003330static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003331stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3332{
3333 int i;
3334 struct instr *instr;
3335 if (b->b_seen || b->b_startdepth >= depth)
3336 return maxdepth;
3337 b->b_seen = 1;
3338 b->b_startdepth = depth;
3339 for (i = 0; i < b->b_iused; i++) {
3340 instr = &b->b_instr[i];
3341 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3342 if (depth > maxdepth)
3343 maxdepth = depth;
3344 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3345 if (instr->i_jrel || instr->i_jabs) {
3346 maxdepth = stackdepth_walk(c, instr->i_target,
3347 depth, maxdepth);
3348 if (instr->i_opcode == JUMP_ABSOLUTE ||
3349 instr->i_opcode == JUMP_FORWARD) {
3350 goto out; /* remaining code is dead */
3351 }
3352 }
3353 }
3354 if (b->b_next)
3355 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3356out:
3357 b->b_seen = 0;
3358 return maxdepth;
3359}
3360
3361/* Find the flow path that needs the largest stack. We assume that
3362 * cycles in the flow graph have no net effect on the stack depth.
3363 */
3364static int
3365stackdepth(struct compiler *c)
3366{
3367 basicblock *b, *entryblock;
3368 entryblock = NULL;
3369 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3370 b->b_seen = 0;
3371 b->b_startdepth = INT_MIN;
3372 entryblock = b;
3373 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003374 if (!entryblock)
3375 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003376 return stackdepth_walk(c, entryblock, 0, 0);
3377}
3378
3379static int
3380assemble_init(struct assembler *a, int nblocks, int firstlineno)
3381{
3382 memset(a, 0, sizeof(struct assembler));
3383 a->a_lineno = firstlineno;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003384 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385 if (!a->a_bytecode)
3386 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003387 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003388 if (!a->a_lnotab)
3389 return 0;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003390 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3391 PyErr_NoMemory();
3392 return 0;
3393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003395 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003396 if (!a->a_postorder) {
3397 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003399 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003400 return 1;
3401}
3402
3403static void
3404assemble_free(struct assembler *a)
3405{
3406 Py_XDECREF(a->a_bytecode);
3407 Py_XDECREF(a->a_lnotab);
3408 if (a->a_postorder)
3409 PyObject_Free(a->a_postorder);
3410}
3411
3412/* Return the size of a basic block in bytes. */
3413
3414static int
3415instrsize(struct instr *instr)
3416{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003417 if (!instr->i_hasarg)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003418 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003419 if (instr->i_oparg > 0xffff)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003420 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3421 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422}
3423
3424static int
3425blocksize(basicblock *b)
3426{
3427 int i;
3428 int size = 0;
3429
3430 for (i = 0; i < b->b_iused; i++)
3431 size += instrsize(&b->b_instr[i]);
3432 return size;
3433}
3434
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003435/* Appends a pair to the end of the line number table, a_lnotab, representing
3436 the instruction's bytecode offset and line number. See
3437 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003438
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003439static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003441{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442 int d_bytecode, d_lineno;
3443 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003444 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003445
3446 d_bytecode = a->a_offset - a->a_lineno_off;
3447 d_lineno = i->i_lineno - a->a_lineno;
3448
3449 assert(d_bytecode >= 0);
3450 assert(d_lineno >= 0);
3451
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003452 if(d_bytecode == 0 && d_lineno == 0)
3453 return 1;
3454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003456 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003458 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003460 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003462 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003463 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003464 else {
3465 PyErr_NoMemory();
3466 return 0;
3467 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003468 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003470 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003471 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003472 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003473 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474 *lnotab++ = 255;
3475 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003476 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477 d_bytecode -= ncodes * 255;
3478 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480 assert(d_bytecode <= 255);
3481 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003482 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003483 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003484 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003485 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003486 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003487 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003488 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003490 else {
3491 PyErr_NoMemory();
3492 return 0;
3493 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003494 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003496 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003497 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003498 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003500 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003501 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003502 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003504 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003505 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506 d_lineno -= ncodes * 255;
3507 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003508 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003509
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003510 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003511 if (a->a_lnotab_off + 2 >= len) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003512 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003513 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003514 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003515 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003516 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518 a->a_lnotab_off += 2;
3519 if (d_bytecode) {
3520 *lnotab++ = d_bytecode;
3521 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003522 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003523 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 *lnotab++ = 0;
3525 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 a->a_lineno = i->i_lineno;
3528 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003529 return 1;
3530}
3531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532/* assemble_emit()
3533 Extend the bytecode with a new instruction.
3534 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003535*/
3536
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003537static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003539{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003540 int size, arg = 0, ext = 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003541 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542 char *code;
3543
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003544 size = instrsize(i);
3545 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003547 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003548 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003550 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 if (a->a_offset + size >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003552 if (len > PY_SSIZE_T_MAX / 2)
3553 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003554 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003555 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003556 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003557 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003559 if (size == 6) {
3560 assert(i->i_hasarg);
3561 *code++ = (char)EXTENDED_ARG;
3562 *code++ = ext & 0xff;
3563 *code++ = ext >> 8;
3564 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003565 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003567 if (i->i_hasarg) {
3568 assert(size == 3 || size == 6);
3569 *code++ = arg & 0xff;
3570 *code++ = arg >> 8;
3571 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003573}
3574
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003575static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003577{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003579 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003580 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003581
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582 /* Compute the size of each block and fixup jump args.
3583 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003584start:
3585 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003587 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 bsize = blocksize(b);
3589 b->b_offset = totsize;
3590 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003591 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003592 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 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;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003607 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003608 else
3609 continue;
3610 if (instr->i_oparg > 0xffff)
3611 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003612 }
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
3619 In the meantime, should the goto be dropped in favor
3620 of a loop?
3621
3622 The issue is that in the first loop blocksize() is called
3623 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003624 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003625 i_oparg is calculated in the second loop above.
3626
3627 So we loop until we stop seeing new EXTENDED_ARGs.
3628 The only EXTENDED_ARGs that could be popping up are
3629 ones in jump instructions. So this should converge
3630 fairly quickly.
3631 */
3632 if (last_extended_arg_count != extended_arg_count) {
3633 last_extended_arg_count = extended_arg_count;
3634 goto start;
3635 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003636}
3637
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003638static PyObject *
3639dict_keys_inorder(PyObject *dict, int offset)
3640{
3641 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003642 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003643
3644 tuple = PyTuple_New(size);
3645 if (tuple == NULL)
3646 return NULL;
3647 while (PyDict_Next(dict, &pos, &k, &v)) {
3648 i = PyInt_AS_LONG(v);
Benjamin Petersonda9327f2009-01-31 23:43:25 +00003649 /* The keys of the dictionary are tuples. (see compiler_add_o)
3650 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003651 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003652 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003653 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003655 PyTuple_SET_ITEM(tuple, i - offset, k);
3656 }
3657 return tuple;
3658}
3659
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003660static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003662{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663 PySTEntryObject *ste = c->u->u_ste;
3664 int flags = 0, n;
3665 if (ste->ste_type != ModuleBlock)
3666 flags |= CO_NEWLOCALS;
3667 if (ste->ste_type == FunctionBlock) {
3668 if (!ste->ste_unoptimized)
3669 flags |= CO_OPTIMIZED;
3670 if (ste->ste_nested)
3671 flags |= CO_NESTED;
3672 if (ste->ste_generator)
3673 flags |= CO_GENERATOR;
Benjamin Peterson12554cb2009-01-31 23:54:38 +00003674 if (ste->ste_varargs)
3675 flags |= CO_VARARGS;
3676 if (ste->ste_varkeywords)
3677 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003678 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003679
3680 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003681 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683 n = PyDict_Size(c->u->u_freevars);
3684 if (n < 0)
3685 return -1;
3686 if (n == 0) {
3687 n = PyDict_Size(c->u->u_cellvars);
3688 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003689 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 if (n == 0) {
3691 flags |= CO_NOFREE;
3692 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003693 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003694
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003695 return flags;
3696}
3697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698static PyCodeObject *
3699makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003700{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003701 PyObject *tmp;
3702 PyCodeObject *co = NULL;
3703 PyObject *consts = NULL;
3704 PyObject *names = NULL;
3705 PyObject *varnames = NULL;
3706 PyObject *filename = NULL;
3707 PyObject *name = NULL;
3708 PyObject *freevars = NULL;
3709 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003710 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003711 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003712
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713 tmp = dict_keys_inorder(c->u->u_consts, 0);
3714 if (!tmp)
3715 goto error;
3716 consts = PySequence_List(tmp); /* optimize_code requires a list */
3717 Py_DECREF(tmp);
3718
3719 names = dict_keys_inorder(c->u->u_names, 0);
3720 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3721 if (!consts || !names || !varnames)
3722 goto error;
3723
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003724 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3725 if (!cellvars)
3726 goto error;
3727 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3728 if (!freevars)
3729 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003730 filename = PyString_FromString(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731 if (!filename)
3732 goto error;
3733
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003734 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735 flags = compute_code_flags(c);
3736 if (flags < 0)
3737 goto error;
3738
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003739 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740 if (!bytecode)
3741 goto error;
3742
3743 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3744 if (!tmp)
3745 goto error;
3746 Py_DECREF(consts);
3747 consts = tmp;
3748
3749 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3750 bytecode, consts, names, varnames,
3751 freevars, cellvars,
3752 filename, c->u->u_name,
3753 c->u->u_firstlineno,
3754 a->a_lnotab);
3755 error:
3756 Py_XDECREF(consts);
3757 Py_XDECREF(names);
3758 Py_XDECREF(varnames);
3759 Py_XDECREF(filename);
3760 Py_XDECREF(name);
3761 Py_XDECREF(freevars);
3762 Py_XDECREF(cellvars);
3763 Py_XDECREF(bytecode);
3764 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003765}
3766
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003767
3768/* For debugging purposes only */
3769#if 0
3770static void
3771dump_instr(const struct instr *i)
3772{
3773 const char *jrel = i->i_jrel ? "jrel " : "";
3774 const char *jabs = i->i_jabs ? "jabs " : "";
3775 char arg[128];
3776
3777 *arg = '\0';
3778 if (i->i_hasarg)
3779 sprintf(arg, "arg: %d ", i->i_oparg);
3780
3781 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3782 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3783}
3784
3785static void
3786dump_basicblock(const basicblock *b)
3787{
3788 const char *seen = b->b_seen ? "seen " : "";
3789 const char *b_return = b->b_return ? "return " : "";
3790 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3791 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3792 if (b->b_instr) {
3793 int i;
3794 for (i = 0; i < b->b_iused; i++) {
3795 fprintf(stderr, " [%02d] ", i);
3796 dump_instr(b->b_instr + i);
3797 }
3798 }
3799}
3800#endif
3801
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802static PyCodeObject *
3803assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003804{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805 basicblock *b, *entryblock;
3806 struct assembler a;
3807 int i, j, nblocks;
3808 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 /* Make sure every block that falls off the end returns None.
3811 XXX NEXT_BLOCK() isn't quite right, because if the last
3812 block ends with a jump or return b_next shouldn't set.
3813 */
3814 if (!c->u->u_curblock->b_return) {
3815 NEXT_BLOCK(c);
3816 if (addNone)
3817 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3818 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003819 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003820
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003821 nblocks = 0;
3822 entryblock = NULL;
3823 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3824 nblocks++;
3825 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003826 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003827
Neal Norwitzed657552006-07-10 00:04:44 +00003828 /* Set firstlineno if it wasn't explicitly set. */
3829 if (!c->u->u_firstlineno) {
3830 if (entryblock && entryblock->b_instr)
3831 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3832 else
3833 c->u->u_firstlineno = 1;
3834 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3836 goto error;
3837 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003838
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003839 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003840 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003841
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842 /* Emit code in reverse postorder from dfs. */
3843 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003844 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003845 for (j = 0; j < b->b_iused; j++)
3846 if (!assemble_emit(&a, &b->b_instr[j]))
3847 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003848 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003849
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003850 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003852 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003854
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855 co = makecode(c, &a);
3856 error:
3857 assemble_free(&a);
3858 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003859}