blob: bdafd922f4c3eef518818ec5c92ab8b66fce07bb [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.
Thomas Wouters89f507f2006-12-13 04:49:30 +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
Thomas Wouters89f507f2006-12-13 04:49:30 +000011 * this file.
12 * 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
Thomas Wouters89f507f2006-12-13 04:49:30 +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_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000110 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000111 /* Pointer to the most recently allocated block. By following b_list
112 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000113 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000115 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000116
117 int u_nfblocks;
118 struct fblockinfo u_fblock[CO_MAXBLOCKS];
119
120 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000121 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122 bool u_lineno_set; /* boolean to indicate whether instr
123 has been generated with current lineno */
124};
125
126/* This struct captures the global state of a compilation.
127
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128The u pointer points to the current compilation unit, while units
129for enclosing blocks are stored in c_stack. The u and c_stack are
130managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131*/
132
133struct compiler {
134 const char *c_filename;
135 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000136 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137 PyCompilerFlags *c_flags;
138
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142 struct compiler_unit *u; /* compiler state for current block */
143 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146};
147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148static int compiler_enter_scope(struct compiler *, identifier, void *, int);
149static void compiler_free(struct compiler *);
150static basicblock *compiler_new_block(struct compiler *);
151static int compiler_next_instr(struct compiler *, basicblock *);
152static int compiler_addop(struct compiler *, int);
153static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
154static int compiler_addop_i(struct compiler *, int, int);
155static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156static basicblock *compiler_use_new_block(struct compiler *);
157static int compiler_error(struct compiler *, const char *);
158static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
159
160static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
161static int compiler_visit_stmt(struct compiler *, stmt_ty);
162static int compiler_visit_keyword(struct compiler *, keyword_ty);
163static int compiler_visit_expr(struct compiler *, expr_ty);
164static int compiler_augassign(struct compiler *, stmt_ty);
165static int compiler_visit_slice(struct compiler *, slice_ty,
166 expr_context_ty);
167
168static int compiler_push_fblock(struct compiler *, enum fblocktype,
169 basicblock *);
170static void compiler_pop_fblock(struct compiler *, enum fblocktype,
171 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000172/* Returns true if there is a loop on the fblock stack. */
173static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174
175static int inplace_binop(struct compiler *, operator_ty);
176static int expr_constant(expr_ty e);
177
Guido van Rossumc2e20742006-02-27 22:32:47 +0000178static int compiler_with(struct compiler *, stmt_ty);
179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static PyCodeObject *assemble(struct compiler *, int addNone);
181static PyObject *__doc__;
182
183PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000185{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186 /* Name mangling: __private becomes _classname__private.
187 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000188 const char *p, *name = PyString_AsString(ident);
189 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000191 if (privateobj == NULL || !PyString_Check(privateobj) ||
192 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000193 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000195 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197 nlen = strlen(name);
198 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000199 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000201 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Strip leading underscores from class name */
203 while (*p == '_')
204 p++;
205 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
211 if (!ident)
212 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000214 buffer = PyString_AS_STRING(ident);
215 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 strncpy(buffer+1, p, plen);
217 strcpy(buffer+1+plen, name);
218 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000219}
220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221static int
222compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000223{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 c->c_stack = PyList_New(0);
227 if (!c->c_stack)
228 return 0;
229
230 return 1;
231}
232
233PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000234PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000236{
237 struct compiler c;
238 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000239 PyCompilerFlags local_flags;
240 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000242 if (!__doc__) {
243 __doc__ = PyString_InternFromString("__doc__");
244 if (!__doc__)
245 return NULL;
246 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000247
248 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000249 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252 c.c_future = PyFuture_FromAST(mod, filename);
253 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000254 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000256 local_flags.cf_flags = 0;
257 flags = &local_flags;
258 }
259 merged = c.c_future->ff_features | flags->cf_flags;
260 c.c_future->ff_features = merged;
261 flags->cf_flags = merged;
262 c.c_flags = flags;
263 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264
265 c.c_st = PySymtable_Build(mod, filename, c.c_future);
266 if (c.c_st == NULL) {
267 if (!PyErr_Occurred())
268 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000269 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 }
271
272 /* XXX initialize to NULL for now, need to handle */
273 c.c_encoding = NULL;
274
275 co = compiler_mod(&c, mod);
276
Thomas Wouters1175c432006-02-27 22:49:54 +0000277 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000279 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280 return co;
281}
282
283PyCodeObject *
284PyNode_Compile(struct _node *n, const char *filename)
285{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000286 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000287 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000288 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000289 if (!arena)
290 return NULL;
291 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000292 if (mod)
293 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000294 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000295 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000296}
297
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000298static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000300{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301 if (c->c_st)
302 PySymtable_Free(c->c_st);
303 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000305 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000306}
307
Guido van Rossum79f25d91997-04-29 20:08:16 +0000308static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000310{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000311 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000312 PyObject *v, *k;
313 PyObject *dict = PyDict_New();
314 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316 n = PyList_Size(list);
317 for (i = 0; i < n; i++) {
318 v = PyInt_FromLong(i);
319 if (!v) {
320 Py_DECREF(dict);
321 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000322 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000323 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000324 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
326 Py_XDECREF(k);
327 Py_DECREF(v);
328 Py_DECREF(dict);
329 return NULL;
330 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000331 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000333 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 return dict;
335}
336
337/* Return new dict containing names from src that match scope(s).
338
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000339src is a symbol table dictionary. If the scope of a name matches
340either scope_type or flag is set, insert it into the new dict. The
341values are integers, starting at offset and increasing by one for
342each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343*/
344
345static PyObject *
346dictbytype(PyObject *src, int scope_type, int flag, int offset)
347{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000348 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349 PyObject *k, *v, *dest = PyDict_New();
350
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000351 assert(offset >= 0);
352 if (dest == NULL)
353 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
355 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000356 /* XXX this should probably be a macro in symtable.h */
357 assert(PyInt_Check(v));
358 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
361 PyObject *tuple, *item = PyInt_FromLong(i);
362 if (item == NULL) {
363 Py_DECREF(dest);
364 return NULL;
365 }
366 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000367 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
369 Py_DECREF(item);
370 Py_DECREF(dest);
371 Py_XDECREF(tuple);
372 return NULL;
373 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000375 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377 }
378 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000379}
380
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381static void
382compiler_unit_check(struct compiler_unit *u)
383{
384 basicblock *block;
385 for (block = u->u_blocks; block != NULL; block = block->b_list) {
386 assert(block != (void *)0xcbcbcbcb);
387 assert(block != (void *)0xfbfbfbfb);
388 assert(block != (void *)0xdbdbdbdb);
389 if (block->b_instr != NULL) {
390 assert(block->b_ialloc > 0);
391 assert(block->b_iused > 0);
392 assert(block->b_ialloc >= block->b_iused);
393 }
394 else {
395 assert (block->b_iused == 0);
396 assert (block->b_ialloc == 0);
397 }
398 }
399}
400
401static void
402compiler_unit_free(struct compiler_unit *u)
403{
404 basicblock *b, *next;
405
406 compiler_unit_check(u);
407 b = u->u_blocks;
408 while (b != NULL) {
409 if (b->b_instr)
410 PyObject_Free((void *)b->b_instr);
411 next = b->b_list;
412 PyObject_Free((void *)b);
413 b = next;
414 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000415 Py_CLEAR(u->u_ste);
416 Py_CLEAR(u->u_name);
417 Py_CLEAR(u->u_consts);
418 Py_CLEAR(u->u_names);
419 Py_CLEAR(u->u_varnames);
420 Py_CLEAR(u->u_freevars);
421 Py_CLEAR(u->u_cellvars);
422 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423 PyObject_Free(u);
424}
425
426static int
427compiler_enter_scope(struct compiler *c, identifier name, void *key,
428 int lineno)
429{
430 struct compiler_unit *u;
431
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
433 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000434 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000435 PyErr_NoMemory();
436 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000437 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000438 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000440 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441 u->u_ste = PySymtable_Lookup(c->c_st, key);
442 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000443 compiler_unit_free(u);
444 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445 }
446 Py_INCREF(name);
447 u->u_name = name;
448 u->u_varnames = list2dict(u->u_ste->ste_varnames);
449 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000450 if (!u->u_varnames || !u->u_cellvars) {
451 compiler_unit_free(u);
452 return 0;
453 }
454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000456 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000457 if (!u->u_freevars) {
458 compiler_unit_free(u);
459 return 0;
460 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461
462 u->u_blocks = NULL;
463 u->u_tmpname = 0;
464 u->u_nfblocks = 0;
465 u->u_firstlineno = lineno;
466 u->u_lineno = 0;
467 u->u_lineno_set = false;
468 u->u_consts = PyDict_New();
469 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000470 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471 return 0;
472 }
473 u->u_names = PyDict_New();
474 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000475 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000476 return 0;
477 }
478
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000479 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480
481 /* Push the old compiler_unit on the stack. */
482 if (c->u) {
483 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000484 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
485 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000486 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487 return 0;
488 }
489 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000490 u->u_private = c->u->u_private;
491 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492 }
493 c->u = u;
494
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000495 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000496 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497 return 0;
498
499 return 1;
500}
501
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000502static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503compiler_exit_scope(struct compiler *c)
504{
505 int n;
506 PyObject *wrapper;
507
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000508 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 compiler_unit_free(c->u);
510 /* Restore c->u to the parent unit. */
511 n = PyList_GET_SIZE(c->c_stack) - 1;
512 if (n >= 0) {
513 wrapper = PyList_GET_ITEM(c->c_stack, n);
514 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000515 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000516 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000518 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519 compiler_unit_check(c->u);
520 }
521 else
522 c->u = NULL;
523
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524}
525
Guido van Rossumc2e20742006-02-27 22:32:47 +0000526/* Allocate a new "anonymous" local variable.
527 Used by list comprehensions and with statements.
528*/
529
530static PyObject *
531compiler_new_tmpname(struct compiler *c)
532{
533 char tmpname[256];
534 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
535 return PyString_FromString(tmpname);
536}
537
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538/* Allocate a new block and return a pointer to it.
539 Returns NULL on error.
540*/
541
542static basicblock *
543compiler_new_block(struct compiler *c)
544{
545 basicblock *b;
546 struct compiler_unit *u;
547
548 u = c->u;
549 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000550 if (b == NULL) {
551 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000555 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556 b->b_list = u->u_blocks;
557 u->u_blocks = b;
558 return b;
559}
560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561static basicblock *
562compiler_use_new_block(struct compiler *c)
563{
564 basicblock *block = compiler_new_block(c);
565 if (block == NULL)
566 return NULL;
567 c->u->u_curblock = block;
568 return block;
569}
570
571static basicblock *
572compiler_next_block(struct compiler *c)
573{
574 basicblock *block = compiler_new_block(c);
575 if (block == NULL)
576 return NULL;
577 c->u->u_curblock->b_next = block;
578 c->u->u_curblock = block;
579 return block;
580}
581
582static basicblock *
583compiler_use_next_block(struct compiler *c, basicblock *block)
584{
585 assert(block != NULL);
586 c->u->u_curblock->b_next = block;
587 c->u->u_curblock = block;
588 return block;
589}
590
591/* Returns the offset of the next instruction in the current block's
592 b_instr array. Resizes the b_instr as necessary.
593 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000595
596static int
597compiler_next_instr(struct compiler *c, basicblock *b)
598{
599 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000600 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601 b->b_instr = (struct instr *)PyObject_Malloc(
602 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603 if (b->b_instr == NULL) {
604 PyErr_NoMemory();
605 return -1;
606 }
607 b->b_ialloc = DEFAULT_BLOCK_SIZE;
608 memset((char *)b->b_instr, 0,
609 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613 size_t oldsize, newsize;
614 oldsize = b->b_ialloc * sizeof(struct instr);
615 newsize = oldsize << 1;
616 if (newsize == 0) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000621 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000622 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623 if (tmp == NULL) {
624 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626 }
627 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
629 }
630 return b->b_iused++;
631}
632
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633/* Set the i_lineno member of the instruction at offse off if the
634 line number for the current expression/statement (?) has not
635 already been set. If it has been set, the call has no effect.
636
637 Every time a new node is b
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000639
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640static void
641compiler_set_lineno(struct compiler *c, int off)
642{
643 basicblock *b;
644 if (c->u->u_lineno_set)
645 return;
646 c->u->u_lineno_set = true;
647 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000648 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649}
650
651static int
652opcode_stack_effect(int opcode, int oparg)
653{
654 switch (opcode) {
655 case POP_TOP:
656 return -1;
657 case ROT_TWO:
658 case ROT_THREE:
659 return 0;
660 case DUP_TOP:
661 return 1;
662 case ROT_FOUR:
663 return 0;
664
665 case UNARY_POSITIVE:
666 case UNARY_NEGATIVE:
667 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668 case UNARY_INVERT:
669 return 0;
670
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000671 case LIST_APPEND:
672 return -2;
673
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000674 case BINARY_POWER:
675 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676 case BINARY_MODULO:
677 case BINARY_ADD:
678 case BINARY_SUBTRACT:
679 case BINARY_SUBSCR:
680 case BINARY_FLOOR_DIVIDE:
681 case BINARY_TRUE_DIVIDE:
682 return -1;
683 case INPLACE_FLOOR_DIVIDE:
684 case INPLACE_TRUE_DIVIDE:
685 return -1;
686
687 case SLICE+0:
688 return 1;
689 case SLICE+1:
690 return 0;
691 case SLICE+2:
692 return 0;
693 case SLICE+3:
694 return -1;
695
696 case STORE_SLICE+0:
697 return -2;
698 case STORE_SLICE+1:
699 return -3;
700 case STORE_SLICE+2:
701 return -3;
702 case STORE_SLICE+3:
703 return -4;
704
705 case DELETE_SLICE+0:
706 return -1;
707 case DELETE_SLICE+1:
708 return -2;
709 case DELETE_SLICE+2:
710 return -2;
711 case DELETE_SLICE+3:
712 return -3;
713
714 case INPLACE_ADD:
715 case INPLACE_SUBTRACT:
716 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000717 case INPLACE_MODULO:
718 return -1;
719 case STORE_SUBSCR:
720 return -3;
721 case DELETE_SUBSCR:
722 return -2;
723
724 case BINARY_LSHIFT:
725 case BINARY_RSHIFT:
726 case BINARY_AND:
727 case BINARY_XOR:
728 case BINARY_OR:
729 return -1;
730 case INPLACE_POWER:
731 return -1;
732 case GET_ITER:
733 return 0;
734
735 case PRINT_EXPR:
736 return -1;
737 case PRINT_ITEM:
738 return -1;
739 case PRINT_NEWLINE:
740 return 0;
741 case PRINT_ITEM_TO:
742 return -2;
743 case PRINT_NEWLINE_TO:
744 return -1;
745 case INPLACE_LSHIFT:
746 case INPLACE_RSHIFT:
747 case INPLACE_AND:
748 case INPLACE_XOR:
749 case INPLACE_OR:
750 return -1;
751 case BREAK_LOOP:
752 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000753 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000754 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755 case LOAD_LOCALS:
756 return 1;
757 case RETURN_VALUE:
758 return -1;
759 case IMPORT_STAR:
760 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761 case YIELD_VALUE:
762 return 0;
763
764 case POP_BLOCK:
765 return 0;
766 case END_FINALLY:
767 return -1; /* or -2 or -3 if exception occurred */
768 case BUILD_CLASS:
769 return -2;
770
771 case STORE_NAME:
772 return -1;
773 case DELETE_NAME:
774 return 0;
775 case UNPACK_SEQUENCE:
776 return oparg-1;
777 case FOR_ITER:
778 return 1;
779
780 case STORE_ATTR:
781 return -2;
782 case DELETE_ATTR:
783 return -1;
784 case STORE_GLOBAL:
785 return -1;
786 case DELETE_GLOBAL:
787 return 0;
788 case DUP_TOPX:
789 return oparg;
790 case LOAD_CONST:
791 return 1;
792 case LOAD_NAME:
793 return 1;
794 case BUILD_TUPLE:
795 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000796 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000797 return 1-oparg;
798 case BUILD_MAP:
799 return 1;
800 case LOAD_ATTR:
801 return 0;
802 case COMPARE_OP:
803 return -1;
804 case IMPORT_NAME:
805 return 0;
806 case IMPORT_FROM:
807 return 1;
808
809 case JUMP_FORWARD:
810 case JUMP_IF_FALSE:
811 case JUMP_IF_TRUE:
812 case JUMP_ABSOLUTE:
813 return 0;
814
815 case LOAD_GLOBAL:
816 return 1;
817
818 case CONTINUE_LOOP:
819 return 0;
820 case SETUP_LOOP:
821 return 0;
822 case SETUP_EXCEPT:
823 case SETUP_FINALLY:
824 return 3; /* actually pushed by an exception */
825
826 case LOAD_FAST:
827 return 1;
828 case STORE_FAST:
829 return -1;
830 case DELETE_FAST:
831 return 0;
832
833 case RAISE_VARARGS:
834 return -oparg;
835#define NARGS(o) (((o) % 256) + 2*((o) / 256))
836 case CALL_FUNCTION:
837 return -NARGS(oparg);
838 case CALL_FUNCTION_VAR:
839 case CALL_FUNCTION_KW:
840 return -NARGS(oparg)-1;
841 case CALL_FUNCTION_VAR_KW:
842 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000843 case MAKE_FUNCTION:
Guido van Rossum4f72a782006-10-27 23:31:49 +0000844 return -NARGS(oparg);
845#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000846 case BUILD_SLICE:
847 if (oparg == 3)
848 return -2;
849 else
850 return -1;
851
852 case MAKE_CLOSURE:
853 return -oparg;
854 case LOAD_CLOSURE:
855 return 1;
856 case LOAD_DEREF:
857 return 1;
858 case STORE_DEREF:
859 return -1;
860 default:
861 fprintf(stderr, "opcode = %d\n", opcode);
862 Py_FatalError("opcode_stack_effect()");
863
864 }
865 return 0; /* not reachable */
866}
867
868/* Add an opcode with no argument.
869 Returns 0 on failure, 1 on success.
870*/
871
872static int
873compiler_addop(struct compiler *c, int opcode)
874{
875 basicblock *b;
876 struct instr *i;
877 int off;
878 off = compiler_next_instr(c, c->u->u_curblock);
879 if (off < 0)
880 return 0;
881 b = c->u->u_curblock;
882 i = &b->b_instr[off];
883 i->i_opcode = opcode;
884 i->i_hasarg = 0;
885 if (opcode == RETURN_VALUE)
886 b->b_return = 1;
887 compiler_set_lineno(c, off);
888 return 1;
889}
890
891static int
892compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
893{
894 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000895 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000896
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000897 /* necessary to make sure types aren't coerced (e.g., int and long) */
898 t = PyTuple_Pack(2, o, o->ob_type);
899 if (t == NULL)
900 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000901
902 v = PyDict_GetItem(dict, t);
903 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000904 if (PyErr_Occurred())
905 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906 arg = PyDict_Size(dict);
907 v = PyInt_FromLong(arg);
908 if (!v) {
909 Py_DECREF(t);
910 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000911 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912 if (PyDict_SetItem(dict, t, v) < 0) {
913 Py_DECREF(t);
914 Py_DECREF(v);
915 return -1;
916 }
917 Py_DECREF(v);
918 }
919 else
920 arg = PyInt_AsLong(v);
921 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000922 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000923}
924
925static int
926compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
927 PyObject *o)
928{
929 int arg = compiler_add_o(c, dict, o);
930 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000931 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932 return compiler_addop_i(c, opcode, arg);
933}
934
935static int
936compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000937 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938{
939 int arg;
940 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
941 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000942 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000943 arg = compiler_add_o(c, dict, mangled);
944 Py_DECREF(mangled);
945 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000946 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000947 return compiler_addop_i(c, opcode, arg);
948}
949
950/* Add an opcode with an integer argument.
951 Returns 0 on failure, 1 on success.
952*/
953
954static int
955compiler_addop_i(struct compiler *c, int opcode, int oparg)
956{
957 struct instr *i;
958 int off;
959 off = compiler_next_instr(c, c->u->u_curblock);
960 if (off < 0)
961 return 0;
962 i = &c->u->u_curblock->b_instr[off];
963 i->i_opcode = opcode;
964 i->i_oparg = oparg;
965 i->i_hasarg = 1;
966 compiler_set_lineno(c, off);
967 return 1;
968}
969
970static int
971compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
972{
973 struct instr *i;
974 int off;
975
976 assert(b != NULL);
977 off = compiler_next_instr(c, c->u->u_curblock);
978 if (off < 0)
979 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980 i = &c->u->u_curblock->b_instr[off];
981 i->i_opcode = opcode;
982 i->i_target = b;
983 i->i_hasarg = 1;
984 if (absolute)
985 i->i_jabs = 1;
986 else
987 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000988 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989 return 1;
990}
991
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000992/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
993 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994 it as the current block. NEXT_BLOCK() also creates an implicit jump
995 from the current block to the new block.
996*/
997
Thomas Wouters89f507f2006-12-13 04:49:30 +0000998/* The returns inside these macros make it impossible to decref objects
999 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000*/
1001
1002
1003#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004 if (compiler_use_new_block((C)) == NULL) \
1005 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006}
1007
1008#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001009 if (compiler_next_block((C)) == NULL) \
1010 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011}
1012
1013#define ADDOP(C, OP) { \
1014 if (!compiler_addop((C), (OP))) \
1015 return 0; \
1016}
1017
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001018#define ADDOP_IN_SCOPE(C, OP) { \
1019 if (!compiler_addop((C), (OP))) { \
1020 compiler_exit_scope(c); \
1021 return 0; \
1022 } \
1023}
1024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025#define ADDOP_O(C, OP, O, TYPE) { \
1026 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1027 return 0; \
1028}
1029
1030#define ADDOP_NAME(C, OP, O, TYPE) { \
1031 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1032 return 0; \
1033}
1034
1035#define ADDOP_I(C, OP, O) { \
1036 if (!compiler_addop_i((C), (OP), (O))) \
1037 return 0; \
1038}
1039
1040#define ADDOP_JABS(C, OP, O) { \
1041 if (!compiler_addop_j((C), (OP), (O), 1)) \
1042 return 0; \
1043}
1044
1045#define ADDOP_JREL(C, OP, O) { \
1046 if (!compiler_addop_j((C), (OP), (O), 0)) \
1047 return 0; \
1048}
1049
1050/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1051 the ASDL name to synthesize the name of the C type and the visit function.
1052*/
1053
1054#define VISIT(C, TYPE, V) {\
1055 if (!compiler_visit_ ## TYPE((C), (V))) \
1056 return 0; \
1057}
1058
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001059#define VISIT_IN_SCOPE(C, TYPE, V) {\
1060 if (!compiler_visit_ ## TYPE((C), (V))) { \
1061 compiler_exit_scope(c); \
1062 return 0; \
1063 } \
1064}
1065
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066#define VISIT_SLICE(C, V, CTX) {\
1067 if (!compiler_visit_slice((C), (V), (CTX))) \
1068 return 0; \
1069}
1070
1071#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001072 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001074 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001075 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076 if (!compiler_visit_ ## TYPE((C), elt)) \
1077 return 0; \
1078 } \
1079}
1080
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001081#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001082 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001083 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001084 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001085 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001086 if (!compiler_visit_ ## TYPE((C), elt)) { \
1087 compiler_exit_scope(c); \
1088 return 0; \
1089 } \
1090 } \
1091}
1092
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093static int
1094compiler_isdocstring(stmt_ty s)
1095{
1096 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 return s->v.Expr.value->kind == Str_kind;
1099}
1100
1101/* Compile a sequence of statements, checking for a docstring. */
1102
1103static int
1104compiler_body(struct compiler *c, asdl_seq *stmts)
1105{
1106 int i = 0;
1107 stmt_ty st;
1108
1109 if (!asdl_seq_LEN(stmts))
1110 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001111 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112 if (compiler_isdocstring(st)) {
1113 i = 1;
1114 VISIT(c, expr, st->v.Expr.value);
1115 if (!compiler_nameop(c, __doc__, Store))
1116 return 0;
1117 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001118 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001119 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 return 1;
1121}
1122
1123static PyCodeObject *
1124compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001125{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001126 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001127 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128 static PyObject *module;
1129 if (!module) {
1130 module = PyString_FromString("<module>");
1131 if (!module)
1132 return NULL;
1133 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001134 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1135 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001136 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137 switch (mod->kind) {
1138 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001139 if (!compiler_body(c, mod->v.Module.body)) {
1140 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001142 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143 break;
1144 case Interactive_kind:
1145 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001146 VISIT_SEQ_IN_SCOPE(c, stmt,
1147 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 break;
1149 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001150 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 break;
1153 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001154 PyErr_SetString(PyExc_SystemError,
1155 "suite should not be possible");
1156 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001157 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001158 PyErr_Format(PyExc_SystemError,
1159 "module kind %d should not be possible",
1160 mod->kind);
1161 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163 co = assemble(c, addNone);
1164 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001165 return co;
1166}
1167
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168/* The test for LOCAL must come before the test for FREE in order to
1169 handle classes where name is both local and free. The local var is
1170 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001171*/
1172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173static int
1174get_ref_type(struct compiler *c, PyObject *name)
1175{
1176 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001177 if (scope == 0) {
1178 char buf[350];
1179 PyOS_snprintf(buf, sizeof(buf),
1180 "unknown scope for %.100s in %.100s(%s) in %s\n"
1181 "symbols: %s\nlocals: %s\nglobals: %s\n",
1182 PyString_AS_STRING(name),
1183 PyString_AS_STRING(c->u->u_name),
1184 PyObject_REPR(c->u->u_ste->ste_id),
1185 c->c_filename,
1186 PyObject_REPR(c->u->u_ste->ste_symbols),
1187 PyObject_REPR(c->u->u_varnames),
1188 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001190 Py_FatalError(buf);
1191 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001192
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001193 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194}
1195
1196static int
1197compiler_lookup_arg(PyObject *dict, PyObject *name)
1198{
1199 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001202 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001204 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001206 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207 return PyInt_AS_LONG(v);
1208}
1209
1210static int
1211compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1212{
1213 int i, free = PyCode_GetNumFree(co);
1214 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001215 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1216 ADDOP_I(c, MAKE_FUNCTION, args);
1217 return 1;
1218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219 for (i = 0; i < free; ++i) {
1220 /* Bypass com_addop_varname because it will generate
1221 LOAD_DEREF but LOAD_CLOSURE is needed.
1222 */
1223 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1224 int arg, reftype;
1225
1226 /* Special case: If a class contains a method with a
1227 free variable that has the same name as a method,
1228 the name will be considered free *and* local in the
1229 class. It should be handled by the closure, as
1230 well as by the normal name loookup logic.
1231 */
1232 reftype = get_ref_type(c, name);
1233 if (reftype == CELL)
1234 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1235 else /* (reftype == FREE) */
1236 arg = compiler_lookup_arg(c->u->u_freevars, name);
1237 if (arg == -1) {
1238 printf("lookup %s in %s %d %d\n"
1239 "freevars of %s: %s\n",
1240 PyObject_REPR(name),
1241 PyString_AS_STRING(c->u->u_name),
1242 reftype, arg,
1243 PyString_AS_STRING(co->co_name),
1244 PyObject_REPR(co->co_freevars));
1245 Py_FatalError("compiler_make_closure()");
1246 }
1247 ADDOP_I(c, LOAD_CLOSURE, arg);
1248 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001249 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 ADDOP_I(c, MAKE_CLOSURE, args);
1252 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253}
1254
1255static int
1256compiler_decorators(struct compiler *c, asdl_seq* decos)
1257{
1258 int i;
1259
1260 if (!decos)
1261 return 1;
1262
1263 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001264 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 }
1266 return 1;
1267}
1268
1269static int
1270compiler_arguments(struct compiler *c, arguments_ty args)
1271{
1272 int i;
1273 int n = asdl_seq_LEN(args->args);
1274 /* Correctly handle nested argument lists */
1275 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001276 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 if (arg->kind == Tuple_kind) {
1278 PyObject *id = PyString_FromFormat(".%d", i);
1279 if (id == NULL) {
1280 return 0;
1281 }
1282 if (!compiler_nameop(c, id, Load)) {
1283 Py_DECREF(id);
1284 return 0;
1285 }
1286 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001287 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288 }
1289 }
1290 return 1;
1291}
1292
1293static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001294compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1295 asdl_seq *kw_defaults)
1296{
1297 int i, default_count = 0;
1298 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1299 expr_ty arg = asdl_seq_GET(kwonlyargs, i);
1300 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1301 if (default_) {
1302 ADDOP_O(c, LOAD_CONST, arg->v.Name.id, consts);
1303 if (!compiler_visit_expr(c, default_)) {
1304 return -1;
1305 }
1306 default_count++;
1307 }
1308 }
1309 return default_count;
1310}
1311
1312static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313compiler_function(struct compiler *c, stmt_ty s)
1314{
1315 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001316 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317 arguments_ty args = s->v.FunctionDef.args;
1318 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001319 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001320 int i, n, docstring, kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321
1322 assert(s->kind == FunctionDef_kind);
1323
1324 if (!compiler_decorators(c, decos))
1325 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001326 if (args->kwonlyargs) {
1327 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1328 args->kw_defaults);
1329 if (res < 0)
1330 return 0;
1331 kw_default_count = res;
1332 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 if (args->defaults)
1334 VISIT_SEQ(c, expr, args->defaults);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001335
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1337 s->lineno))
1338 return 0;
1339
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001340 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001341 docstring = compiler_isdocstring(st);
1342 if (docstring)
1343 first_const = st->v.Expr.value->v.Str.s;
1344 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001345 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001346 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001347 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001349 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350 compiler_arguments(c, args);
1351
1352 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001353 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001355 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001357 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1358 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 }
1360 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001361 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362 if (co == NULL)
1363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364
Guido van Rossum4f72a782006-10-27 23:31:49 +00001365 arglength = asdl_seq_LEN(args->defaults);
1366 arglength |= kw_default_count << 8;
1367 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001368 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369
1370 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1371 ADDOP_I(c, CALL_FUNCTION, 1);
1372 }
1373
1374 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1375}
1376
1377static int
1378compiler_class(struct compiler *c, stmt_ty s)
1379{
1380 int n;
1381 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001382 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 /* push class name on stack, needed by BUILD_CLASS */
1384 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1385 /* push the tuple of base classes on the stack */
1386 n = asdl_seq_LEN(s->v.ClassDef.bases);
1387 if (n > 0)
1388 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1389 ADDOP_I(c, BUILD_TUPLE, n);
1390 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1391 s->lineno))
1392 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001393 c->u->u_private = s->v.ClassDef.name;
1394 Py_INCREF(c->u->u_private);
1395 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396 if (!str || !compiler_nameop(c, str, Load)) {
1397 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001398 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001400 }
1401
1402 Py_DECREF(str);
1403 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404 if (!str || !compiler_nameop(c, str, Store)) {
1405 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001406 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001408 }
1409 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001411 if (!compiler_body(c, s->v.ClassDef.body)) {
1412 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001414 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001416 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1417 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001419 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420 if (co == NULL)
1421 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001423 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001424 Py_DECREF(co);
1425
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426 ADDOP_I(c, CALL_FUNCTION, 0);
1427 ADDOP(c, BUILD_CLASS);
1428 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1429 return 0;
1430 return 1;
1431}
1432
1433static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001434compiler_ifexp(struct compiler *c, expr_ty e)
1435{
1436 basicblock *end, *next;
1437
1438 assert(e->kind == IfExp_kind);
1439 end = compiler_new_block(c);
1440 if (end == NULL)
1441 return 0;
1442 next = compiler_new_block(c);
1443 if (next == NULL)
1444 return 0;
1445 VISIT(c, expr, e->v.IfExp.test);
1446 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1447 ADDOP(c, POP_TOP);
1448 VISIT(c, expr, e->v.IfExp.body);
1449 ADDOP_JREL(c, JUMP_FORWARD, end);
1450 compiler_use_next_block(c, next);
1451 ADDOP(c, POP_TOP);
1452 VISIT(c, expr, e->v.IfExp.orelse);
1453 compiler_use_next_block(c, end);
1454 return 1;
1455}
1456
1457static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458compiler_lambda(struct compiler *c, expr_ty e)
1459{
1460 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001461 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001462 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463 arguments_ty args = e->v.Lambda.args;
1464 assert(e->kind == Lambda_kind);
1465
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001466 if (!name) {
1467 name = PyString_InternFromString("<lambda>");
1468 if (!name)
1469 return 0;
1470 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471
Guido van Rossum4f72a782006-10-27 23:31:49 +00001472 if (args->kwonlyargs) {
1473 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1474 args->kw_defaults);
1475 if (res < 0) return 0;
1476 kw_default_count = res;
1477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478 if (args->defaults)
1479 VISIT_SEQ(c, expr, args->defaults);
1480 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1481 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001482
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001483 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484 compiler_arguments(c, args);
1485
1486 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001487 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001488 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1489 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001491 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492 if (co == NULL)
1493 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494
Guido van Rossum4f72a782006-10-27 23:31:49 +00001495 arglength = asdl_seq_LEN(args->defaults);
1496 arglength |= kw_default_count << 8;
1497 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001498 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499
1500 return 1;
1501}
1502
1503static int
1504compiler_print(struct compiler *c, stmt_ty s)
1505{
1506 int i, n;
1507 bool dest;
1508
1509 assert(s->kind == Print_kind);
1510 n = asdl_seq_LEN(s->v.Print.values);
1511 dest = false;
1512 if (s->v.Print.dest) {
1513 VISIT(c, expr, s->v.Print.dest);
1514 dest = true;
1515 }
1516 for (i = 0; i < n; i++) {
1517 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1518 if (dest) {
1519 ADDOP(c, DUP_TOP);
1520 VISIT(c, expr, e);
1521 ADDOP(c, ROT_TWO);
1522 ADDOP(c, PRINT_ITEM_TO);
1523 }
1524 else {
1525 VISIT(c, expr, e);
1526 ADDOP(c, PRINT_ITEM);
1527 }
1528 }
1529 if (s->v.Print.nl) {
1530 if (dest)
1531 ADDOP(c, PRINT_NEWLINE_TO)
1532 else
1533 ADDOP(c, PRINT_NEWLINE)
1534 }
1535 else if (dest)
1536 ADDOP(c, POP_TOP);
1537 return 1;
1538}
1539
1540static int
1541compiler_if(struct compiler *c, stmt_ty s)
1542{
1543 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001544 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545 assert(s->kind == If_kind);
1546 end = compiler_new_block(c);
1547 if (end == NULL)
1548 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001549 next = compiler_new_block(c);
1550 if (next == NULL)
1551 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001552
1553 constant = expr_constant(s->v.If.test);
1554 /* constant = 0: "if 0"
1555 * constant = 1: "if 1", "if 2", ...
1556 * constant = -1: rest */
1557 if (constant == 0) {
1558 if (s->v.If.orelse)
1559 VISIT_SEQ(c, stmt, s->v.If.orelse);
1560 } else if (constant == 1) {
1561 VISIT_SEQ(c, stmt, s->v.If.body);
1562 } else {
1563 VISIT(c, expr, s->v.If.test);
1564 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1565 ADDOP(c, POP_TOP);
1566 VISIT_SEQ(c, stmt, s->v.If.body);
1567 ADDOP_JREL(c, JUMP_FORWARD, end);
1568 compiler_use_next_block(c, next);
1569 ADDOP(c, POP_TOP);
1570 if (s->v.If.orelse)
1571 VISIT_SEQ(c, stmt, s->v.If.orelse);
1572 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573 compiler_use_next_block(c, end);
1574 return 1;
1575}
1576
1577static int
1578compiler_for(struct compiler *c, stmt_ty s)
1579{
1580 basicblock *start, *cleanup, *end;
1581
1582 start = compiler_new_block(c);
1583 cleanup = compiler_new_block(c);
1584 end = compiler_new_block(c);
1585 if (start == NULL || end == NULL || cleanup == NULL)
1586 return 0;
1587 ADDOP_JREL(c, SETUP_LOOP, end);
1588 if (!compiler_push_fblock(c, LOOP, start))
1589 return 0;
1590 VISIT(c, expr, s->v.For.iter);
1591 ADDOP(c, GET_ITER);
1592 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001593 /* XXX(nnorwitz): is there a better way to handle this?
1594 for loops are special, we want to be able to trace them
1595 each time around, so we need to set an extra line number. */
1596 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001597 ADDOP_JREL(c, FOR_ITER, cleanup);
1598 VISIT(c, expr, s->v.For.target);
1599 VISIT_SEQ(c, stmt, s->v.For.body);
1600 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1601 compiler_use_next_block(c, cleanup);
1602 ADDOP(c, POP_BLOCK);
1603 compiler_pop_fblock(c, LOOP, start);
1604 VISIT_SEQ(c, stmt, s->v.For.orelse);
1605 compiler_use_next_block(c, end);
1606 return 1;
1607}
1608
1609static int
1610compiler_while(struct compiler *c, stmt_ty s)
1611{
1612 basicblock *loop, *orelse, *end, *anchor = NULL;
1613 int constant = expr_constant(s->v.While.test);
1614
1615 if (constant == 0)
1616 return 1;
1617 loop = compiler_new_block(c);
1618 end = compiler_new_block(c);
1619 if (constant == -1) {
1620 anchor = compiler_new_block(c);
1621 if (anchor == NULL)
1622 return 0;
1623 }
1624 if (loop == NULL || end == NULL)
1625 return 0;
1626 if (s->v.While.orelse) {
1627 orelse = compiler_new_block(c);
1628 if (orelse == NULL)
1629 return 0;
1630 }
1631 else
1632 orelse = NULL;
1633
1634 ADDOP_JREL(c, SETUP_LOOP, end);
1635 compiler_use_next_block(c, loop);
1636 if (!compiler_push_fblock(c, LOOP, loop))
1637 return 0;
1638 if (constant == -1) {
1639 VISIT(c, expr, s->v.While.test);
1640 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1641 ADDOP(c, POP_TOP);
1642 }
1643 VISIT_SEQ(c, stmt, s->v.While.body);
1644 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1645
1646 /* XXX should the two POP instructions be in a separate block
1647 if there is no else clause ?
1648 */
1649
1650 if (constant == -1) {
1651 compiler_use_next_block(c, anchor);
1652 ADDOP(c, POP_TOP);
1653 ADDOP(c, POP_BLOCK);
1654 }
1655 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001656 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657 VISIT_SEQ(c, stmt, s->v.While.orelse);
1658 compiler_use_next_block(c, end);
1659
1660 return 1;
1661}
1662
1663static int
1664compiler_continue(struct compiler *c)
1665{
1666 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001667 static const char IN_FINALLY_ERROR_MSG[] =
1668 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001669 int i;
1670
1671 if (!c->u->u_nfblocks)
1672 return compiler_error(c, LOOP_ERROR_MSG);
1673 i = c->u->u_nfblocks - 1;
1674 switch (c->u->u_fblock[i].fb_type) {
1675 case LOOP:
1676 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1677 break;
1678 case EXCEPT:
1679 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001680 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1681 /* Prevent continue anywhere under a finally
1682 even if hidden in a sub-try or except. */
1683 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1684 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1685 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686 if (i == -1)
1687 return compiler_error(c, LOOP_ERROR_MSG);
1688 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1689 break;
1690 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001691 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692 }
1693
1694 return 1;
1695}
1696
1697/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1698
1699 SETUP_FINALLY L
1700 <code for body>
1701 POP_BLOCK
1702 LOAD_CONST <None>
1703 L: <code for finalbody>
1704 END_FINALLY
1705
1706 The special instructions use the block stack. Each block
1707 stack entry contains the instruction that created it (here
1708 SETUP_FINALLY), the level of the value stack at the time the
1709 block stack entry was created, and a label (here L).
1710
1711 SETUP_FINALLY:
1712 Pushes the current value stack level and the label
1713 onto the block stack.
1714 POP_BLOCK:
1715 Pops en entry from the block stack, and pops the value
1716 stack until its level is the same as indicated on the
1717 block stack. (The label is ignored.)
1718 END_FINALLY:
1719 Pops a variable number of entries from the *value* stack
1720 and re-raises the exception they specify. The number of
1721 entries popped depends on the (pseudo) exception type.
1722
1723 The block stack is unwound when an exception is raised:
1724 when a SETUP_FINALLY entry is found, the exception is pushed
1725 onto the value stack (and the exception condition is cleared),
1726 and the interpreter jumps to the label gotten from the block
1727 stack.
1728*/
1729
1730static int
1731compiler_try_finally(struct compiler *c, stmt_ty s)
1732{
1733 basicblock *body, *end;
1734 body = compiler_new_block(c);
1735 end = compiler_new_block(c);
1736 if (body == NULL || end == NULL)
1737 return 0;
1738
1739 ADDOP_JREL(c, SETUP_FINALLY, end);
1740 compiler_use_next_block(c, body);
1741 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1742 return 0;
1743 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1744 ADDOP(c, POP_BLOCK);
1745 compiler_pop_fblock(c, FINALLY_TRY, body);
1746
1747 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1748 compiler_use_next_block(c, end);
1749 if (!compiler_push_fblock(c, FINALLY_END, end))
1750 return 0;
1751 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1752 ADDOP(c, END_FINALLY);
1753 compiler_pop_fblock(c, FINALLY_END, end);
1754
1755 return 1;
1756}
1757
1758/*
1759 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1760 (The contents of the value stack is shown in [], with the top
1761 at the right; 'tb' is trace-back info, 'val' the exception's
1762 associated value, and 'exc' the exception.)
1763
1764 Value stack Label Instruction Argument
1765 [] SETUP_EXCEPT L1
1766 [] <code for S>
1767 [] POP_BLOCK
1768 [] JUMP_FORWARD L0
1769
1770 [tb, val, exc] L1: DUP )
1771 [tb, val, exc, exc] <evaluate E1> )
1772 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1773 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1774 [tb, val, exc, 1] POP )
1775 [tb, val, exc] POP
1776 [tb, val] <assign to V1> (or POP if no V1)
1777 [tb] POP
1778 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001779 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780
1781 [tb, val, exc, 0] L2: POP
1782 [tb, val, exc] DUP
1783 .............................etc.......................
1784
1785 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001786 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787
1788 [] L0: <next statement>
1789
1790 Of course, parts are not generated if Vi or Ei is not present.
1791*/
1792static int
1793compiler_try_except(struct compiler *c, stmt_ty s)
1794{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001795 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796 int i, n;
1797
1798 body = compiler_new_block(c);
1799 except = compiler_new_block(c);
1800 orelse = compiler_new_block(c);
1801 end = compiler_new_block(c);
1802 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1803 return 0;
1804 ADDOP_JREL(c, SETUP_EXCEPT, except);
1805 compiler_use_next_block(c, body);
1806 if (!compiler_push_fblock(c, EXCEPT, body))
1807 return 0;
1808 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1809 ADDOP(c, POP_BLOCK);
1810 compiler_pop_fblock(c, EXCEPT, body);
1811 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1812 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1813 compiler_use_next_block(c, except);
1814 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001815 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816 s->v.TryExcept.handlers, i);
1817 if (!handler->type && i < n-1)
1818 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001819 c->u->u_lineno_set = false;
1820 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821 except = compiler_new_block(c);
1822 if (except == NULL)
1823 return 0;
1824 if (handler->type) {
1825 ADDOP(c, DUP_TOP);
1826 VISIT(c, expr, handler->type);
1827 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1828 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1829 ADDOP(c, POP_TOP);
1830 }
1831 ADDOP(c, POP_TOP);
1832 if (handler->name) {
1833 VISIT(c, expr, handler->name);
1834 }
1835 else {
1836 ADDOP(c, POP_TOP);
1837 }
1838 ADDOP(c, POP_TOP);
1839 VISIT_SEQ(c, stmt, handler->body);
1840 ADDOP_JREL(c, JUMP_FORWARD, end);
1841 compiler_use_next_block(c, except);
1842 if (handler->type)
1843 ADDOP(c, POP_TOP);
1844 }
1845 ADDOP(c, END_FINALLY);
1846 compiler_use_next_block(c, orelse);
1847 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1848 compiler_use_next_block(c, end);
1849 return 1;
1850}
1851
1852static int
1853compiler_import_as(struct compiler *c, identifier name, identifier asname)
1854{
1855 /* The IMPORT_NAME opcode was already generated. This function
1856 merely needs to bind the result to a name.
1857
1858 If there is a dot in name, we need to split it and emit a
1859 LOAD_ATTR for each name.
1860 */
1861 const char *src = PyString_AS_STRING(name);
1862 const char *dot = strchr(src, '.');
1863 if (dot) {
1864 /* Consume the base module name to get the first attribute */
1865 src = dot + 1;
1866 while (dot) {
1867 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001868 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001870 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001872 if (!attr)
1873 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001875 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876 src = dot + 1;
1877 }
1878 }
1879 return compiler_nameop(c, asname, Store);
1880}
1881
1882static int
1883compiler_import(struct compiler *c, stmt_ty s)
1884{
1885 /* The Import node stores a module name like a.b.c as a single
1886 string. This is convenient for all cases except
1887 import a.b.c as d
1888 where we need to parse that string to extract the individual
1889 module names.
1890 XXX Perhaps change the representation to make this case simpler?
1891 */
1892 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001893
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001895 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001897 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898
Guido van Rossum45aecf42006-03-15 04:58:47 +00001899 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001900 if (level == NULL)
1901 return 0;
1902
1903 ADDOP_O(c, LOAD_CONST, level, consts);
1904 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1906 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1907
1908 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001909 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001910 if (!r)
1911 return r;
1912 }
1913 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 identifier tmp = alias->name;
1915 const char *base = PyString_AS_STRING(alias->name);
1916 char *dot = strchr(base, '.');
1917 if (dot)
1918 tmp = PyString_FromStringAndSize(base,
1919 dot - base);
1920 r = compiler_nameop(c, tmp, Store);
1921 if (dot) {
1922 Py_DECREF(tmp);
1923 }
1924 if (!r)
1925 return r;
1926 }
1927 }
1928 return 1;
1929}
1930
1931static int
1932compiler_from_import(struct compiler *c, stmt_ty s)
1933{
1934 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
1936 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001937 PyObject *level;
1938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939 if (!names)
1940 return 0;
1941
Guido van Rossum45aecf42006-03-15 04:58:47 +00001942 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001943 if (!level) {
1944 Py_DECREF(names);
1945 return 0;
1946 }
1947
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948 /* build up the names */
1949 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001950 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951 Py_INCREF(alias->name);
1952 PyTuple_SET_ITEM(names, i, alias->name);
1953 }
1954
1955 if (s->lineno > c->c_future->ff_lineno) {
1956 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1957 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001958 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 Py_DECREF(names);
1960 return compiler_error(c,
1961 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001962 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963
1964 }
1965 }
1966
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001967 ADDOP_O(c, LOAD_CONST, level, consts);
1968 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001970 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1972 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001973 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974 identifier store_name;
1975
1976 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1977 assert(n == 1);
1978 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 }
1981
1982 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1983 store_name = alias->name;
1984 if (alias->asname)
1985 store_name = alias->asname;
1986
1987 if (!compiler_nameop(c, store_name, Store)) {
1988 Py_DECREF(names);
1989 return 0;
1990 }
1991 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001992 /* remove imported module */
1993 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994 return 1;
1995}
1996
1997static int
1998compiler_assert(struct compiler *c, stmt_ty s)
1999{
2000 static PyObject *assertion_error = NULL;
2001 basicblock *end;
2002
2003 if (Py_OptimizeFlag)
2004 return 1;
2005 if (assertion_error == NULL) {
2006 assertion_error = PyString_FromString("AssertionError");
2007 if (assertion_error == NULL)
2008 return 0;
2009 }
2010 VISIT(c, expr, s->v.Assert.test);
2011 end = compiler_new_block(c);
2012 if (end == NULL)
2013 return 0;
2014 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2015 ADDOP(c, POP_TOP);
2016 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2017 if (s->v.Assert.msg) {
2018 VISIT(c, expr, s->v.Assert.msg);
2019 ADDOP_I(c, RAISE_VARARGS, 2);
2020 }
2021 else {
2022 ADDOP_I(c, RAISE_VARARGS, 1);
2023 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002024 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025 ADDOP(c, POP_TOP);
2026 return 1;
2027}
2028
2029static int
2030compiler_visit_stmt(struct compiler *c, stmt_ty s)
2031{
2032 int i, n;
2033
Thomas Wouters89f507f2006-12-13 04:49:30 +00002034 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 c->u->u_lineno = s->lineno;
2036 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002037
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002039 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002041 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002043 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044 if (c->u->u_ste->ste_type != FunctionBlock)
2045 return compiler_error(c, "'return' outside function");
2046 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 VISIT(c, expr, s->v.Return.value);
2048 }
2049 else
2050 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2051 ADDOP(c, RETURN_VALUE);
2052 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002053 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 VISIT_SEQ(c, expr, s->v.Delete.targets)
2055 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002056 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 n = asdl_seq_LEN(s->v.Assign.targets);
2058 VISIT(c, expr, s->v.Assign.value);
2059 for (i = 0; i < n; i++) {
2060 if (i < n - 1)
2061 ADDOP(c, DUP_TOP);
2062 VISIT(c, expr,
2063 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2064 }
2065 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002066 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002068 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002070 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002072 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002074 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002076 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 n = 0;
2078 if (s->v.Raise.type) {
2079 VISIT(c, expr, s->v.Raise.type);
2080 n++;
2081 if (s->v.Raise.inst) {
2082 VISIT(c, expr, s->v.Raise.inst);
2083 n++;
2084 if (s->v.Raise.tback) {
2085 VISIT(c, expr, s->v.Raise.tback);
2086 n++;
2087 }
2088 }
2089 }
2090 ADDOP_I(c, RAISE_VARARGS, n);
2091 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002092 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002094 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002096 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002098 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002100 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002102 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002104 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002105 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002106 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 ADDOP(c, PRINT_EXPR);
2108 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002109 else if (s->v.Expr.value->kind != Str_kind &&
2110 s->v.Expr.value->kind != Num_kind) {
2111 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 ADDOP(c, POP_TOP);
2113 }
2114 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002115 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002117 case Break_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +00002118 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119 return compiler_error(c, "'break' outside loop");
2120 ADDOP(c, BREAK_LOOP);
2121 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002122 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002124 case With_kind:
2125 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 }
2127 return 1;
2128}
2129
2130static int
2131unaryop(unaryop_ty op)
2132{
2133 switch (op) {
2134 case Invert:
2135 return UNARY_INVERT;
2136 case Not:
2137 return UNARY_NOT;
2138 case UAdd:
2139 return UNARY_POSITIVE;
2140 case USub:
2141 return UNARY_NEGATIVE;
2142 }
2143 return 0;
2144}
2145
2146static int
2147binop(struct compiler *c, operator_ty op)
2148{
2149 switch (op) {
2150 case Add:
2151 return BINARY_ADD;
2152 case Sub:
2153 return BINARY_SUBTRACT;
2154 case Mult:
2155 return BINARY_MULTIPLY;
2156 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002157 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 case Mod:
2159 return BINARY_MODULO;
2160 case Pow:
2161 return BINARY_POWER;
2162 case LShift:
2163 return BINARY_LSHIFT;
2164 case RShift:
2165 return BINARY_RSHIFT;
2166 case BitOr:
2167 return BINARY_OR;
2168 case BitXor:
2169 return BINARY_XOR;
2170 case BitAnd:
2171 return BINARY_AND;
2172 case FloorDiv:
2173 return BINARY_FLOOR_DIVIDE;
2174 }
2175 return 0;
2176}
2177
2178static int
2179cmpop(cmpop_ty op)
2180{
2181 switch (op) {
2182 case Eq:
2183 return PyCmp_EQ;
2184 case NotEq:
2185 return PyCmp_NE;
2186 case Lt:
2187 return PyCmp_LT;
2188 case LtE:
2189 return PyCmp_LE;
2190 case Gt:
2191 return PyCmp_GT;
2192 case GtE:
2193 return PyCmp_GE;
2194 case Is:
2195 return PyCmp_IS;
2196 case IsNot:
2197 return PyCmp_IS_NOT;
2198 case In:
2199 return PyCmp_IN;
2200 case NotIn:
2201 return PyCmp_NOT_IN;
2202 }
2203 return PyCmp_BAD;
2204}
2205
2206static int
2207inplace_binop(struct compiler *c, operator_ty op)
2208{
2209 switch (op) {
2210 case Add:
2211 return INPLACE_ADD;
2212 case Sub:
2213 return INPLACE_SUBTRACT;
2214 case Mult:
2215 return INPLACE_MULTIPLY;
2216 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002217 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002218 case Mod:
2219 return INPLACE_MODULO;
2220 case Pow:
2221 return INPLACE_POWER;
2222 case LShift:
2223 return INPLACE_LSHIFT;
2224 case RShift:
2225 return INPLACE_RSHIFT;
2226 case BitOr:
2227 return INPLACE_OR;
2228 case BitXor:
2229 return INPLACE_XOR;
2230 case BitAnd:
2231 return INPLACE_AND;
2232 case FloorDiv:
2233 return INPLACE_FLOOR_DIVIDE;
2234 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002235 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002236 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237 return 0;
2238}
2239
2240static int
2241compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2242{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002243 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2245
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002246 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002247 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248 /* XXX AugStore isn't used anywhere! */
2249
2250 /* First check for assignment to __debug__. Param? */
2251 if ((ctx == Store || ctx == AugStore || ctx == Del)
2252 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2253 return compiler_error(c, "can not assign to __debug__");
2254 }
2255
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002256 mangled = _Py_Mangle(c->u->u_private, name);
2257 if (!mangled)
2258 return 0;
2259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 op = 0;
2261 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002262 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 switch (scope) {
2264 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002265 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 optype = OP_DEREF;
2267 break;
2268 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002269 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 optype = OP_DEREF;
2271 break;
2272 case LOCAL:
2273 if (c->u->u_ste->ste_type == FunctionBlock)
2274 optype = OP_FAST;
2275 break;
2276 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002277 if (c->u->u_ste->ste_type == FunctionBlock &&
2278 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 optype = OP_GLOBAL;
2280 break;
2281 case GLOBAL_EXPLICIT:
2282 optype = OP_GLOBAL;
2283 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002284 default:
2285 /* scope can be 0 */
2286 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 }
2288
2289 /* XXX Leave assert here, but handle __doc__ and the like better */
2290 assert(scope || PyString_AS_STRING(name)[0] == '_');
2291
2292 switch (optype) {
2293 case OP_DEREF:
2294 switch (ctx) {
2295 case Load: op = LOAD_DEREF; break;
2296 case Store: op = STORE_DEREF; break;
2297 case AugLoad:
2298 case AugStore:
2299 break;
2300 case Del:
2301 PyErr_Format(PyExc_SyntaxError,
2302 "can not delete variable '%s' referenced "
2303 "in nested scope",
2304 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002305 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002308 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002309 PyErr_SetString(PyExc_SystemError,
2310 "param invalid for deref variable");
2311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 }
2313 break;
2314 case OP_FAST:
2315 switch (ctx) {
2316 case Load: op = LOAD_FAST; break;
2317 case Store: op = STORE_FAST; break;
2318 case Del: op = DELETE_FAST; break;
2319 case AugLoad:
2320 case AugStore:
2321 break;
2322 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002323 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002324 PyErr_SetString(PyExc_SystemError,
2325 "param invalid for local variable");
2326 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002328 ADDOP_O(c, op, mangled, varnames);
2329 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 return 1;
2331 case OP_GLOBAL:
2332 switch (ctx) {
2333 case Load: op = LOAD_GLOBAL; break;
2334 case Store: op = STORE_GLOBAL; break;
2335 case Del: op = DELETE_GLOBAL; break;
2336 case AugLoad:
2337 case AugStore:
2338 break;
2339 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002340 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002341 PyErr_SetString(PyExc_SystemError,
2342 "param invalid for global variable");
2343 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344 }
2345 break;
2346 case OP_NAME:
2347 switch (ctx) {
2348 case Load: op = LOAD_NAME; break;
2349 case Store: op = STORE_NAME; break;
2350 case Del: op = DELETE_NAME; break;
2351 case AugLoad:
2352 case AugStore:
2353 break;
2354 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002355 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002356 PyErr_SetString(PyExc_SystemError,
2357 "param invalid for name variable");
2358 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359 }
2360 break;
2361 }
2362
2363 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002364 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002365 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002366 if (arg < 0)
2367 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002368 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369}
2370
2371static int
2372compiler_boolop(struct compiler *c, expr_ty e)
2373{
2374 basicblock *end;
2375 int jumpi, i, n;
2376 asdl_seq *s;
2377
2378 assert(e->kind == BoolOp_kind);
2379 if (e->v.BoolOp.op == And)
2380 jumpi = JUMP_IF_FALSE;
2381 else
2382 jumpi = JUMP_IF_TRUE;
2383 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002384 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385 return 0;
2386 s = e->v.BoolOp.values;
2387 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002388 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002390 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391 ADDOP_JREL(c, jumpi, end);
2392 ADDOP(c, POP_TOP)
2393 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002394 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395 compiler_use_next_block(c, end);
2396 return 1;
2397}
2398
2399static int
2400compiler_list(struct compiler *c, expr_ty e)
2401{
2402 int n = asdl_seq_LEN(e->v.List.elts);
2403 if (e->v.List.ctx == Store) {
2404 ADDOP_I(c, UNPACK_SEQUENCE, n);
2405 }
2406 VISIT_SEQ(c, expr, e->v.List.elts);
2407 if (e->v.List.ctx == Load) {
2408 ADDOP_I(c, BUILD_LIST, n);
2409 }
2410 return 1;
2411}
2412
2413static int
2414compiler_tuple(struct compiler *c, expr_ty e)
2415{
2416 int n = asdl_seq_LEN(e->v.Tuple.elts);
2417 if (e->v.Tuple.ctx == Store) {
2418 ADDOP_I(c, UNPACK_SEQUENCE, n);
2419 }
2420 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2421 if (e->v.Tuple.ctx == Load) {
2422 ADDOP_I(c, BUILD_TUPLE, n);
2423 }
2424 return 1;
2425}
2426
2427static int
2428compiler_compare(struct compiler *c, expr_ty e)
2429{
2430 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002431 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432
2433 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2434 VISIT(c, expr, e->v.Compare.left);
2435 n = asdl_seq_LEN(e->v.Compare.ops);
2436 assert(n > 0);
2437 if (n > 1) {
2438 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002439 if (cleanup == NULL)
2440 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002441 VISIT(c, expr,
2442 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443 }
2444 for (i = 1; i < n; i++) {
2445 ADDOP(c, DUP_TOP);
2446 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002448 cmpop((cmpop_ty)(asdl_seq_GET(
2449 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2451 NEXT_BLOCK(c);
2452 ADDOP(c, POP_TOP);
2453 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002454 VISIT(c, expr,
2455 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002457 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002459 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 if (n > 1) {
2461 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002462 if (end == NULL)
2463 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 ADDOP_JREL(c, JUMP_FORWARD, end);
2465 compiler_use_next_block(c, cleanup);
2466 ADDOP(c, ROT_TWO);
2467 ADDOP(c, POP_TOP);
2468 compiler_use_next_block(c, end);
2469 }
2470 return 1;
2471}
2472
2473static int
2474compiler_call(struct compiler *c, expr_ty e)
2475{
2476 int n, code = 0;
2477
2478 VISIT(c, expr, e->v.Call.func);
2479 n = asdl_seq_LEN(e->v.Call.args);
2480 VISIT_SEQ(c, expr, e->v.Call.args);
2481 if (e->v.Call.keywords) {
2482 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2483 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2484 }
2485 if (e->v.Call.starargs) {
2486 VISIT(c, expr, e->v.Call.starargs);
2487 code |= 1;
2488 }
2489 if (e->v.Call.kwargs) {
2490 VISIT(c, expr, e->v.Call.kwargs);
2491 code |= 2;
2492 }
2493 switch (code) {
2494 case 0:
2495 ADDOP_I(c, CALL_FUNCTION, n);
2496 break;
2497 case 1:
2498 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2499 break;
2500 case 2:
2501 ADDOP_I(c, CALL_FUNCTION_KW, n);
2502 break;
2503 case 3:
2504 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2505 break;
2506 }
2507 return 1;
2508}
2509
2510static int
2511compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002512 asdl_seq *generators, int gen_index,
2513 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514{
2515 /* generate code for the iterator, then each of the ifs,
2516 and then write to the element */
2517
2518 comprehension_ty l;
2519 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002520 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521
2522 start = compiler_new_block(c);
2523 skip = compiler_new_block(c);
2524 if_cleanup = compiler_new_block(c);
2525 anchor = compiler_new_block(c);
2526
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002527 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2528 anchor == NULL)
2529 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002531 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 VISIT(c, expr, l->iter);
2533 ADDOP(c, GET_ITER);
2534 compiler_use_next_block(c, start);
2535 ADDOP_JREL(c, FOR_ITER, anchor);
2536 NEXT_BLOCK(c);
2537 VISIT(c, expr, l->target);
2538
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 n = asdl_seq_LEN(l->ifs);
2541 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002542 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 VISIT(c, expr, e);
2544 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2545 NEXT_BLOCK(c);
2546 ADDOP(c, POP_TOP);
2547 }
2548
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002549 if (++gen_index < asdl_seq_LEN(generators))
2550 if (!compiler_listcomp_generator(c, tmpname,
2551 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002554 /* only append after the last for generator */
2555 if (gen_index >= asdl_seq_LEN(generators)) {
2556 if (!compiler_nameop(c, tmpname, Load))
2557 return 0;
2558 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002559 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002560
2561 compiler_use_next_block(c, skip);
2562 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002563 for (i = 0; i < n; i++) {
2564 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002565 if (i == 0)
2566 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567 ADDOP(c, POP_TOP);
2568 }
2569 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2570 compiler_use_next_block(c, anchor);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002571 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002573 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574 return 0;
2575
2576 return 1;
2577}
2578
2579static int
2580compiler_listcomp(struct compiler *c, expr_ty e)
2581{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584 asdl_seq *generators = e->v.ListComp.generators;
2585
2586 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002587 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 if (!tmp)
2589 return 0;
2590 ADDOP_I(c, BUILD_LIST, 0);
2591 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002593 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2594 e->v.ListComp.elt);
2595 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596 return rc;
2597}
2598
2599static int
2600compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002601 asdl_seq *generators, int gen_index,
2602 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603{
2604 /* generate code for the iterator, then each of the ifs,
2605 and then write to the element */
2606
2607 comprehension_ty ge;
2608 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002609 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610
2611 start = compiler_new_block(c);
2612 skip = compiler_new_block(c);
2613 if_cleanup = compiler_new_block(c);
2614 anchor = compiler_new_block(c);
2615 end = compiler_new_block(c);
2616
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002617 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 anchor == NULL || end == NULL)
2619 return 0;
2620
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002621 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622 ADDOP_JREL(c, SETUP_LOOP, end);
2623 if (!compiler_push_fblock(c, LOOP, start))
2624 return 0;
2625
2626 if (gen_index == 0) {
2627 /* Receive outermost iter as an implicit argument */
2628 c->u->u_argcount = 1;
2629 ADDOP_I(c, LOAD_FAST, 0);
2630 }
2631 else {
2632 /* Sub-iter - calculate on the fly */
2633 VISIT(c, expr, ge->iter);
2634 ADDOP(c, GET_ITER);
2635 }
2636 compiler_use_next_block(c, start);
2637 ADDOP_JREL(c, FOR_ITER, anchor);
2638 NEXT_BLOCK(c);
2639 VISIT(c, expr, ge->target);
2640
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002641 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 n = asdl_seq_LEN(ge->ifs);
2643 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002644 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 VISIT(c, expr, e);
2646 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2647 NEXT_BLOCK(c);
2648 ADDOP(c, POP_TOP);
2649 }
2650
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2653 return 0;
2654
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 /* only append after the last 'for' generator */
2656 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 VISIT(c, expr, elt);
2658 ADDOP(c, YIELD_VALUE);
2659 ADDOP(c, POP_TOP);
2660
2661 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002662 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663 for (i = 0; i < n; i++) {
2664 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 compiler_use_next_block(c, if_cleanup);
2667
2668 ADDOP(c, POP_TOP);
2669 }
2670 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2671 compiler_use_next_block(c, anchor);
2672 ADDOP(c, POP_BLOCK);
2673 compiler_pop_fblock(c, LOOP, start);
2674 compiler_use_next_block(c, end);
2675
2676 return 1;
2677}
2678
2679static int
2680compiler_genexp(struct compiler *c, expr_ty e)
2681{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002682 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683 PyCodeObject *co;
2684 expr_ty outermost_iter = ((comprehension_ty)
2685 (asdl_seq_GET(e->v.GeneratorExp.generators,
2686 0)))->iter;
2687
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002688 if (!name) {
2689 name = PyString_FromString("<genexpr>");
2690 if (!name)
2691 return 0;
2692 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693
2694 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2695 return 0;
2696 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2697 e->v.GeneratorExp.elt);
2698 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002699 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 if (co == NULL)
2701 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002703 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002704 Py_DECREF(co);
2705
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 VISIT(c, expr, outermost_iter);
2707 ADDOP(c, GET_ITER);
2708 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
2710 return 1;
2711}
2712
2713static int
2714compiler_visit_keyword(struct compiler *c, keyword_ty k)
2715{
2716 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2717 VISIT(c, expr, k->value);
2718 return 1;
2719}
2720
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002721/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 whether they are true or false.
2723
2724 Return values: 1 for true, 0 for false, -1 for non-constant.
2725 */
2726
2727static int
2728expr_constant(expr_ty e)
2729{
2730 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00002731 case Ellipsis_kind:
2732 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 case Num_kind:
2734 return PyObject_IsTrue(e->v.Num.n);
2735 case Str_kind:
2736 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002737 case Name_kind:
2738 /* __debug__ is not assignable, so we can optimize
2739 * it away in if and while statements */
2740 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2741 "__debug__") == 0)
2742 return ! Py_OptimizeFlag;
2743 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744 default:
2745 return -1;
2746 }
2747}
2748
Guido van Rossumc2e20742006-02-27 22:32:47 +00002749/*
2750 Implements the with statement from PEP 343.
2751
2752 The semantics outlined in that PEP are as follows:
2753
2754 with EXPR as VAR:
2755 BLOCK
2756
2757 It is implemented roughly as:
2758
Thomas Wouters477c8d52006-05-27 19:21:47 +00002759 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002760 exit = context.__exit__ # not calling it
2761 value = context.__enter__()
2762 try:
2763 VAR = value # if VAR present in the syntax
2764 BLOCK
2765 finally:
2766 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002767 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002768 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002769 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002770 exit(*exc)
2771 */
2772static int
2773compiler_with(struct compiler *c, stmt_ty s)
2774{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002775 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002776 basicblock *block, *finally;
2777 identifier tmpexit, tmpvalue = NULL;
2778
2779 assert(s->kind == With_kind);
2780
Guido van Rossumc2e20742006-02-27 22:32:47 +00002781 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002782 enter_attr = PyString_InternFromString("__enter__");
2783 if (!enter_attr)
2784 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002785 }
2786 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002787 exit_attr = PyString_InternFromString("__exit__");
2788 if (!exit_attr)
2789 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002790 }
2791
2792 block = compiler_new_block(c);
2793 finally = compiler_new_block(c);
2794 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002795 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002796
2797 /* Create a temporary variable to hold context.__exit__ */
2798 tmpexit = compiler_new_tmpname(c);
2799 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002800 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801 PyArena_AddPyObject(c->c_arena, tmpexit);
2802
2803 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002804 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002805 We need to do this rather than preserving it on the stack
2806 because SETUP_FINALLY remembers the stack level.
2807 We need to do the assignment *inside* the try/finally
2808 so that context.__exit__() is called when the assignment
2809 fails. But we need to call context.__enter__() *before*
2810 the try/finally so that if it fails we won't call
2811 context.__exit__().
2812 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002813 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002814 if (tmpvalue == NULL)
2815 return 0;
2816 PyArena_AddPyObject(c->c_arena, tmpvalue);
2817 }
2818
Thomas Wouters477c8d52006-05-27 19:21:47 +00002819 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002820 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002821
2822 /* Squirrel away context.__exit__ */
2823 ADDOP(c, DUP_TOP);
2824 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2825 if (!compiler_nameop(c, tmpexit, Store))
2826 return 0;
2827
2828 /* Call context.__enter__() */
2829 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2830 ADDOP_I(c, CALL_FUNCTION, 0);
2831
2832 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002833 /* Store it in tmpvalue */
2834 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002835 return 0;
2836 }
2837 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002838 /* Discard result from context.__enter__() */
2839 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002840 }
2841
2842 /* Start the try block */
2843 ADDOP_JREL(c, SETUP_FINALLY, finally);
2844
2845 compiler_use_next_block(c, block);
2846 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002848 }
2849
2850 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002851 /* Bind saved result of context.__enter__() to VAR */
2852 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002853 !compiler_nameop(c, tmpvalue, Del))
2854 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002855 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002856 }
2857
2858 /* BLOCK code */
2859 VISIT_SEQ(c, stmt, s->v.With.body);
2860
2861 /* End of try block; start the finally block */
2862 ADDOP(c, POP_BLOCK);
2863 compiler_pop_fblock(c, FINALLY_TRY, block);
2864
2865 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2866 compiler_use_next_block(c, finally);
2867 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002868 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869
2870 /* Finally block starts; push tmpexit and issue our magic opcode. */
2871 if (!compiler_nameop(c, tmpexit, Load) ||
2872 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002873 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002874 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002875
2876 /* Finally block ends. */
2877 ADDOP(c, END_FINALLY);
2878 compiler_pop_fblock(c, FINALLY_END, finally);
2879 return 1;
2880}
2881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882static int
2883compiler_visit_expr(struct compiler *c, expr_ty e)
2884{
2885 int i, n;
2886
Thomas Wouters89f507f2006-12-13 04:49:30 +00002887 /* If expr e has a different line number than the last expr/stmt,
2888 set a new line number for the next instruction.
2889 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890 if (e->lineno > c->u->u_lineno) {
2891 c->u->u_lineno = e->lineno;
2892 c->u->u_lineno_set = false;
2893 }
2894 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002895 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002897 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898 VISIT(c, expr, e->v.BinOp.left);
2899 VISIT(c, expr, e->v.BinOp.right);
2900 ADDOP(c, binop(c, e->v.BinOp.op));
2901 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002902 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903 VISIT(c, expr, e->v.UnaryOp.operand);
2904 ADDOP(c, unaryop(e->v.UnaryOp.op));
2905 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002906 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002908 case IfExp_kind:
2909 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002910 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911 /* XXX get rid of arg? */
2912 ADDOP_I(c, BUILD_MAP, 0);
2913 n = asdl_seq_LEN(e->v.Dict.values);
2914 /* We must arrange things just right for STORE_SUBSCR.
2915 It wants the stack to look like (value) (dict) (key) */
2916 for (i = 0; i < n; i++) {
2917 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002918 VISIT(c, expr,
2919 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002921 VISIT(c, expr,
2922 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 ADDOP(c, STORE_SUBSCR);
2924 }
2925 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002926 case Set_kind:
2927 n = asdl_seq_LEN(e->v.Set.elts);
2928 VISIT_SEQ(c, expr, e->v.Set.elts);
2929 ADDOP_I(c, BUILD_SET, n);
2930 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002931 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002932 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002933 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 return compiler_genexp(c, e);
2935 case Yield_kind:
2936 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002937 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 if (e->v.Yield.value) {
2939 VISIT(c, expr, e->v.Yield.value);
2940 }
2941 else {
2942 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2943 }
2944 ADDOP(c, YIELD_VALUE);
2945 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002946 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002948 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002950 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2952 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002953 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2955 break;
Georg Brandl52318d62006-09-06 07:06:08 +00002956 case Ellipsis_kind:
2957 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
2958 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002960 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 if (e->v.Attribute.ctx != AugStore)
2962 VISIT(c, expr, e->v.Attribute.value);
2963 switch (e->v.Attribute.ctx) {
2964 case AugLoad:
2965 ADDOP(c, DUP_TOP);
2966 /* Fall through to load */
2967 case Load:
2968 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2969 break;
2970 case AugStore:
2971 ADDOP(c, ROT_TWO);
2972 /* Fall through to save */
2973 case Store:
2974 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2975 break;
2976 case Del:
2977 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2978 break;
2979 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002980 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002981 PyErr_SetString(PyExc_SystemError,
2982 "param invalid in attribute expression");
2983 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 }
2985 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002986 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987 switch (e->v.Subscript.ctx) {
2988 case AugLoad:
2989 VISIT(c, expr, e->v.Subscript.value);
2990 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2991 break;
2992 case Load:
2993 VISIT(c, expr, e->v.Subscript.value);
2994 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2995 break;
2996 case AugStore:
2997 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2998 break;
2999 case Store:
3000 VISIT(c, expr, e->v.Subscript.value);
3001 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3002 break;
3003 case Del:
3004 VISIT(c, expr, e->v.Subscript.value);
3005 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3006 break;
3007 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003008 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003009 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003010 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003011 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012 }
3013 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003014 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3016 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003017 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003019 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003020 return compiler_tuple(c, e);
3021 }
3022 return 1;
3023}
3024
3025static int
3026compiler_augassign(struct compiler *c, stmt_ty s)
3027{
3028 expr_ty e = s->v.AugAssign.target;
3029 expr_ty auge;
3030
3031 assert(s->kind == AugAssign_kind);
3032
3033 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003034 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003036 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003037 if (auge == NULL)
3038 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039 VISIT(c, expr, auge);
3040 VISIT(c, expr, s->v.AugAssign.value);
3041 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3042 auge->v.Attribute.ctx = AugStore;
3043 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 break;
3045 case Subscript_kind:
3046 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003047 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003048 if (auge == NULL)
3049 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 VISIT(c, expr, auge);
3051 VISIT(c, expr, s->v.AugAssign.value);
3052 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003053 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003054 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003055 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003057 if (!compiler_nameop(c, e->v.Name.id, Load))
3058 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059 VISIT(c, expr, s->v.AugAssign.value);
3060 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3061 return compiler_nameop(c, e->v.Name.id, Store);
3062 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003063 PyErr_Format(PyExc_SystemError,
3064 "invalid node type (%d) for augmented assignment",
3065 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003066 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067 }
3068 return 1;
3069}
3070
3071static int
3072compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3073{
3074 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003075 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3076 PyErr_SetString(PyExc_SystemError,
3077 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003079 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080 f = &c->u->u_fblock[c->u->u_nfblocks++];
3081 f->fb_type = t;
3082 f->fb_block = b;
3083 return 1;
3084}
3085
3086static void
3087compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3088{
3089 struct compiler_unit *u = c->u;
3090 assert(u->u_nfblocks > 0);
3091 u->u_nfblocks--;
3092 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3093 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3094}
3095
Thomas Wouters89f507f2006-12-13 04:49:30 +00003096static int
3097compiler_in_loop(struct compiler *c) {
3098 int i;
3099 struct compiler_unit *u = c->u;
3100 for (i = 0; i < u->u_nfblocks; ++i) {
3101 if (u->u_fblock[i].fb_type == LOOP)
3102 return 1;
3103 }
3104 return 0;
3105}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106/* Raises a SyntaxError and returns 0.
3107 If something goes wrong, a different exception may be raised.
3108*/
3109
3110static int
3111compiler_error(struct compiler *c, const char *errstr)
3112{
3113 PyObject *loc;
3114 PyObject *u = NULL, *v = NULL;
3115
3116 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3117 if (!loc) {
3118 Py_INCREF(Py_None);
3119 loc = Py_None;
3120 }
3121 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3122 Py_None, loc);
3123 if (!u)
3124 goto exit;
3125 v = Py_BuildValue("(zO)", errstr, u);
3126 if (!v)
3127 goto exit;
3128 PyErr_SetObject(PyExc_SyntaxError, v);
3129 exit:
3130 Py_DECREF(loc);
3131 Py_XDECREF(u);
3132 Py_XDECREF(v);
3133 return 0;
3134}
3135
3136static int
3137compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003140 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003142 /* XXX this code is duplicated */
3143 switch (ctx) {
3144 case AugLoad: /* fall through to Load */
3145 case Load: op = BINARY_SUBSCR; break;
3146 case AugStore:/* fall through to Store */
3147 case Store: op = STORE_SUBSCR; break;
3148 case Del: op = DELETE_SUBSCR; break;
3149 case Param:
3150 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003151 "invalid %s kind %d in subscript\n",
3152 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003153 return 0;
3154 }
3155 if (ctx == AugLoad) {
3156 ADDOP_I(c, DUP_TOPX, 2);
3157 }
3158 else if (ctx == AugStore) {
3159 ADDOP(c, ROT_THREE);
3160 }
3161 ADDOP(c, op);
3162 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163}
3164
3165static int
3166compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3167{
3168 int n = 2;
3169 assert(s->kind == Slice_kind);
3170
3171 /* only handles the cases where BUILD_SLICE is emitted */
3172 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003173 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003174 }
3175 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003176 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003180 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181 }
3182 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003183 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184 }
3185
3186 if (s->v.Slice.step) {
3187 n++;
3188 VISIT(c, expr, s->v.Slice.step);
3189 }
3190 ADDOP_I(c, BUILD_SLICE, n);
3191 return 1;
3192}
3193
3194static int
3195compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3196{
3197 int op = 0, slice_offset = 0, stack_count = 0;
3198
3199 assert(s->v.Slice.step == NULL);
3200 if (s->v.Slice.lower) {
3201 slice_offset++;
3202 stack_count++;
3203 if (ctx != AugStore)
3204 VISIT(c, expr, s->v.Slice.lower);
3205 }
3206 if (s->v.Slice.upper) {
3207 slice_offset += 2;
3208 stack_count++;
3209 if (ctx != AugStore)
3210 VISIT(c, expr, s->v.Slice.upper);
3211 }
3212
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003213 if (ctx == AugLoad) {
3214 switch (stack_count) {
3215 case 0: ADDOP(c, DUP_TOP); break;
3216 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3217 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3218 }
3219 }
3220 else if (ctx == AugStore) {
3221 switch (stack_count) {
3222 case 0: ADDOP(c, ROT_TWO); break;
3223 case 1: ADDOP(c, ROT_THREE); break;
3224 case 2: ADDOP(c, ROT_FOUR); break;
3225 }
3226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227
3228 switch (ctx) {
3229 case AugLoad: /* fall through to Load */
3230 case Load: op = SLICE; break;
3231 case AugStore:/* fall through to Store */
3232 case Store: op = STORE_SLICE; break;
3233 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003234 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003235 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003236 PyErr_SetString(PyExc_SystemError,
3237 "param invalid in simple slice");
3238 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239 }
3240
3241 ADDOP(c, op + slice_offset);
3242 return 1;
3243}
3244
3245static int
3246compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3247 expr_context_ty ctx)
3248{
3249 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 case Slice_kind:
3251 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 case Index_kind:
3253 VISIT(c, expr, s->v.Index.value);
3254 break;
3255 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003256 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003257 PyErr_SetString(PyExc_SystemError,
3258 "extended slice invalid in nested slice");
3259 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 }
3261 return 1;
3262}
3263
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264static int
3265compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3266{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003267 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003269 case Index_kind:
3270 kindname = "index";
3271 if (ctx != AugStore) {
3272 VISIT(c, expr, s->v.Index.value);
3273 }
3274 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003276 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 if (!s->v.Slice.step)
3278 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003279 if (ctx != AugStore) {
3280 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281 return 0;
3282 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003283 break;
3284 case ExtSlice_kind:
3285 kindname = "extended slice";
3286 if (ctx != AugStore) {
3287 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3288 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003289 slice_ty sub = (slice_ty)asdl_seq_GET(
3290 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003291 if (!compiler_visit_nested_slice(c, sub, ctx))
3292 return 0;
3293 }
3294 ADDOP_I(c, BUILD_TUPLE, n);
3295 }
3296 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003297 default:
3298 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003299 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003300 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003302 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303}
3304
Thomas Wouters89f507f2006-12-13 04:49:30 +00003305
3306/* End of the compiler section, beginning of the assembler section */
3307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308/* do depth-first search of basic block graph, starting with block.
3309 post records the block indices in post-order.
3310
3311 XXX must handle implicit jumps from one block to next
3312*/
3313
Thomas Wouters89f507f2006-12-13 04:49:30 +00003314struct assembler {
3315 PyObject *a_bytecode; /* string containing bytecode */
3316 int a_offset; /* offset into bytecode */
3317 int a_nblocks; /* number of reachable blocks */
3318 basicblock **a_postorder; /* list of blocks in dfs postorder */
3319 PyObject *a_lnotab; /* string containing lnotab */
3320 int a_lnotab_off; /* offset into lnotab */
3321 int a_lineno; /* last lineno of emitted instruction */
3322 int a_lineno_off; /* bytecode offset of last lineno */
3323};
3324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325static void
3326dfs(struct compiler *c, basicblock *b, struct assembler *a)
3327{
3328 int i;
3329 struct instr *instr = NULL;
3330
3331 if (b->b_seen)
3332 return;
3333 b->b_seen = 1;
3334 if (b->b_next != NULL)
3335 dfs(c, b->b_next, a);
3336 for (i = 0; i < b->b_iused; i++) {
3337 instr = &b->b_instr[i];
3338 if (instr->i_jrel || instr->i_jabs)
3339 dfs(c, instr->i_target, a);
3340 }
3341 a->a_postorder[a->a_nblocks++] = b;
3342}
3343
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003344static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3346{
3347 int i;
3348 struct instr *instr;
3349 if (b->b_seen || b->b_startdepth >= depth)
3350 return maxdepth;
3351 b->b_seen = 1;
3352 b->b_startdepth = depth;
3353 for (i = 0; i < b->b_iused; i++) {
3354 instr = &b->b_instr[i];
3355 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3356 if (depth > maxdepth)
3357 maxdepth = depth;
3358 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3359 if (instr->i_jrel || instr->i_jabs) {
3360 maxdepth = stackdepth_walk(c, instr->i_target,
3361 depth, maxdepth);
3362 if (instr->i_opcode == JUMP_ABSOLUTE ||
3363 instr->i_opcode == JUMP_FORWARD) {
3364 goto out; /* remaining code is dead */
3365 }
3366 }
3367 }
3368 if (b->b_next)
3369 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3370out:
3371 b->b_seen = 0;
3372 return maxdepth;
3373}
3374
3375/* Find the flow path that needs the largest stack. We assume that
3376 * cycles in the flow graph have no net effect on the stack depth.
3377 */
3378static int
3379stackdepth(struct compiler *c)
3380{
3381 basicblock *b, *entryblock;
3382 entryblock = NULL;
3383 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3384 b->b_seen = 0;
3385 b->b_startdepth = INT_MIN;
3386 entryblock = b;
3387 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003388 if (!entryblock)
3389 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003390 return stackdepth_walk(c, entryblock, 0, 0);
3391}
3392
3393static int
3394assemble_init(struct assembler *a, int nblocks, int firstlineno)
3395{
3396 memset(a, 0, sizeof(struct assembler));
3397 a->a_lineno = firstlineno;
3398 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3399 if (!a->a_bytecode)
3400 return 0;
3401 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3402 if (!a->a_lnotab)
3403 return 0;
3404 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003405 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003406 if (!a->a_postorder) {
3407 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003409 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003410 return 1;
3411}
3412
3413static void
3414assemble_free(struct assembler *a)
3415{
3416 Py_XDECREF(a->a_bytecode);
3417 Py_XDECREF(a->a_lnotab);
3418 if (a->a_postorder)
3419 PyObject_Free(a->a_postorder);
3420}
3421
3422/* Return the size of a basic block in bytes. */
3423
3424static int
3425instrsize(struct instr *instr)
3426{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003427 if (!instr->i_hasarg)
3428 return 1;
3429 if (instr->i_oparg > 0xffff)
3430 return 6;
3431 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432}
3433
3434static int
3435blocksize(basicblock *b)
3436{
3437 int i;
3438 int size = 0;
3439
3440 for (i = 0; i < b->b_iused; i++)
3441 size += instrsize(&b->b_instr[i]);
3442 return size;
3443}
3444
3445/* All about a_lnotab.
3446
3447c_lnotab is an array of unsigned bytes disguised as a Python string.
3448It is used to map bytecode offsets to source code line #s (when needed
3449for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003450
Tim Peters2a7f3842001-06-09 09:26:21 +00003451The array is conceptually a list of
3452 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003453pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003454
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 byte code offset source code line number
3456 0 1
3457 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003458 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003459 350 307
3460 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003461
3462The first trick is that these numbers aren't stored, only the increments
3463from one row to the next (this doesn't really work, but it's a start):
3464
3465 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3466
3467The second trick is that an unsigned byte can't hold negative values, or
3468values larger than 255, so (a) there's a deep assumption that byte code
3469offsets and their corresponding line #s both increase monotonically, and (b)
3470if at least one column jumps by more than 255 from one row to the next, more
3471than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003472from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003473part. A user of c_lnotab desiring to find the source line number
3474corresponding to a bytecode address A should do something like this
3475
3476 lineno = addr = 0
3477 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003478 addr += addr_incr
3479 if addr > A:
3480 return lineno
3481 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003482
3483In order for this to work, when the addr field increments by more than 255,
3484the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003485increment is < 256. So, in the example above, assemble_lnotab (it used
3486to be called com_set_lineno) should not (as was actually done until 2.2)
3487expand 300, 300 to 255, 255, 45, 45,
3488 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003489*/
3490
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003491static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003493{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 int d_bytecode, d_lineno;
3495 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003496 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497
3498 d_bytecode = a->a_offset - a->a_lineno_off;
3499 d_lineno = i->i_lineno - a->a_lineno;
3500
3501 assert(d_bytecode >= 0);
3502 assert(d_lineno >= 0);
3503
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003504 /* XXX(nnorwitz): is there a better way to handle this?
3505 for loops are special, we want to be able to trace them
3506 each time around, so we need to set an extra line number. */
3507 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003508 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003509
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003511 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512 nbytes = a->a_lnotab_off + 2 * ncodes;
3513 len = PyString_GET_SIZE(a->a_lnotab);
3514 if (nbytes >= len) {
3515 if (len * 2 < nbytes)
3516 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003517 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518 len *= 2;
3519 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3520 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003521 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003522 lnotab = (unsigned char *)
3523 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003524 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525 *lnotab++ = 255;
3526 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003527 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 d_bytecode -= ncodes * 255;
3529 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003530 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531 assert(d_bytecode <= 255);
3532 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003533 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 nbytes = a->a_lnotab_off + 2 * ncodes;
3535 len = PyString_GET_SIZE(a->a_lnotab);
3536 if (nbytes >= len) {
3537 if (len * 2 < nbytes)
3538 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003539 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 len *= 2;
3541 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3542 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003543 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003544 lnotab = (unsigned char *)
3545 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003547 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003549 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003551 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003552 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 d_lineno -= ncodes * 255;
3554 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003555 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003556
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557 len = PyString_GET_SIZE(a->a_lnotab);
3558 if (a->a_lnotab_off + 2 >= len) {
3559 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003560 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003561 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003562 lnotab = (unsigned char *)
3563 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003564
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 a->a_lnotab_off += 2;
3566 if (d_bytecode) {
3567 *lnotab++ = d_bytecode;
3568 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003569 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003570 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571 *lnotab++ = 0;
3572 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003573 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 a->a_lineno = i->i_lineno;
3575 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003576 return 1;
3577}
3578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579/* assemble_emit()
3580 Extend the bytecode with a new instruction.
3581 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003582*/
3583
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003584static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003586{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003587 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003588 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 char *code;
3590
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003591 size = instrsize(i);
3592 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003594 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003597 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598 if (a->a_offset + size >= len) {
3599 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003600 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3603 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003604 if (size == 6) {
3605 assert(i->i_hasarg);
3606 *code++ = (char)EXTENDED_ARG;
3607 *code++ = ext & 0xff;
3608 *code++ = ext >> 8;
3609 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003612 if (i->i_hasarg) {
3613 assert(size == 3 || size == 6);
3614 *code++ = arg & 0xff;
3615 *code++ = arg >> 8;
3616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003618}
3619
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003620static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003622{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003624 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003625 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003626
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627 /* Compute the size of each block and fixup jump args.
3628 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003629start:
3630 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003632 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 bsize = blocksize(b);
3634 b->b_offset = totsize;
3635 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003636 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003637 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3639 bsize = b->b_offset;
3640 for (i = 0; i < b->b_iused; i++) {
3641 struct instr *instr = &b->b_instr[i];
3642 /* Relative jumps are computed relative to
3643 the instruction pointer after fetching
3644 the jump instruction.
3645 */
3646 bsize += instrsize(instr);
3647 if (instr->i_jabs)
3648 instr->i_oparg = instr->i_target->b_offset;
3649 else if (instr->i_jrel) {
3650 int delta = instr->i_target->b_offset - bsize;
3651 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003652 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003653 else
3654 continue;
3655 if (instr->i_oparg > 0xffff)
3656 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003657 }
3658 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003659
3660 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003661 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003662 with a better solution.
3663
3664 In the meantime, should the goto be dropped in favor
3665 of a loop?
3666
3667 The issue is that in the first loop blocksize() is called
3668 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003669 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003670 i_oparg is calculated in the second loop above.
3671
3672 So we loop until we stop seeing new EXTENDED_ARGs.
3673 The only EXTENDED_ARGs that could be popping up are
3674 ones in jump instructions. So this should converge
3675 fairly quickly.
3676 */
3677 if (last_extended_arg_count != extended_arg_count) {
3678 last_extended_arg_count = extended_arg_count;
3679 goto start;
3680 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003681}
3682
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003683static PyObject *
3684dict_keys_inorder(PyObject *dict, int offset)
3685{
3686 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003687 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003688
3689 tuple = PyTuple_New(size);
3690 if (tuple == NULL)
3691 return NULL;
3692 while (PyDict_Next(dict, &pos, &k, &v)) {
3693 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003694 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003695 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003696 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003697 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003698 PyTuple_SET_ITEM(tuple, i - offset, k);
3699 }
3700 return tuple;
3701}
3702
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003703static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003705{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003706 PySTEntryObject *ste = c->u->u_ste;
3707 int flags = 0, n;
3708 if (ste->ste_type != ModuleBlock)
3709 flags |= CO_NEWLOCALS;
3710 if (ste->ste_type == FunctionBlock) {
3711 if (!ste->ste_unoptimized)
3712 flags |= CO_OPTIMIZED;
3713 if (ste->ste_nested)
3714 flags |= CO_NESTED;
3715 if (ste->ste_generator)
3716 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003717 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718 if (ste->ste_varargs)
3719 flags |= CO_VARARGS;
3720 if (ste->ste_varkeywords)
3721 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003722 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003724
3725 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003726 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003727
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728 n = PyDict_Size(c->u->u_freevars);
3729 if (n < 0)
3730 return -1;
3731 if (n == 0) {
3732 n = PyDict_Size(c->u->u_cellvars);
3733 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003734 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735 if (n == 0) {
3736 flags |= CO_NOFREE;
3737 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003738 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003739
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003740 return flags;
3741}
3742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743static PyCodeObject *
3744makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003745{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746 PyObject *tmp;
3747 PyCodeObject *co = NULL;
3748 PyObject *consts = NULL;
3749 PyObject *names = NULL;
3750 PyObject *varnames = NULL;
3751 PyObject *filename = NULL;
3752 PyObject *name = NULL;
3753 PyObject *freevars = NULL;
3754 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003755 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758 tmp = dict_keys_inorder(c->u->u_consts, 0);
3759 if (!tmp)
3760 goto error;
3761 consts = PySequence_List(tmp); /* optimize_code requires a list */
3762 Py_DECREF(tmp);
3763
3764 names = dict_keys_inorder(c->u->u_names, 0);
3765 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3766 if (!consts || !names || !varnames)
3767 goto error;
3768
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003769 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3770 if (!cellvars)
3771 goto error;
3772 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3773 if (!freevars)
3774 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 filename = PyString_FromString(c->c_filename);
3776 if (!filename)
3777 goto error;
3778
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003779 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 flags = compute_code_flags(c);
3781 if (flags < 0)
3782 goto error;
3783
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003784 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785 if (!bytecode)
3786 goto error;
3787
3788 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3789 if (!tmp)
3790 goto error;
3791 Py_DECREF(consts);
3792 consts = tmp;
3793
Guido van Rossum4f72a782006-10-27 23:31:49 +00003794 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3795 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 bytecode, consts, names, varnames,
3797 freevars, cellvars,
3798 filename, c->u->u_name,
3799 c->u->u_firstlineno,
3800 a->a_lnotab);
3801 error:
3802 Py_XDECREF(consts);
3803 Py_XDECREF(names);
3804 Py_XDECREF(varnames);
3805 Py_XDECREF(filename);
3806 Py_XDECREF(name);
3807 Py_XDECREF(freevars);
3808 Py_XDECREF(cellvars);
3809 Py_XDECREF(bytecode);
3810 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003811}
3812
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003813
3814/* For debugging purposes only */
3815#if 0
3816static void
3817dump_instr(const struct instr *i)
3818{
3819 const char *jrel = i->i_jrel ? "jrel " : "";
3820 const char *jabs = i->i_jabs ? "jabs " : "";
3821 char arg[128];
3822
3823 *arg = '\0';
3824 if (i->i_hasarg)
3825 sprintf(arg, "arg: %d ", i->i_oparg);
3826
3827 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3828 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3829}
3830
3831static void
3832dump_basicblock(const basicblock *b)
3833{
3834 const char *seen = b->b_seen ? "seen " : "";
3835 const char *b_return = b->b_return ? "return " : "";
3836 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3837 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3838 if (b->b_instr) {
3839 int i;
3840 for (i = 0; i < b->b_iused; i++) {
3841 fprintf(stderr, " [%02d] ", i);
3842 dump_instr(b->b_instr + i);
3843 }
3844 }
3845}
3846#endif
3847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848static PyCodeObject *
3849assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003850{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851 basicblock *b, *entryblock;
3852 struct assembler a;
3853 int i, j, nblocks;
3854 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003855
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003856 /* Make sure every block that falls off the end returns None.
3857 XXX NEXT_BLOCK() isn't quite right, because if the last
3858 block ends with a jump or return b_next shouldn't set.
3859 */
3860 if (!c->u->u_curblock->b_return) {
3861 NEXT_BLOCK(c);
3862 if (addNone)
3863 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3864 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003865 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867 nblocks = 0;
3868 entryblock = NULL;
3869 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3870 nblocks++;
3871 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003872 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003873
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003874 /* Set firstlineno if it wasn't explicitly set. */
3875 if (!c->u->u_firstlineno) {
3876 if (entryblock && entryblock->b_instr)
3877 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3878 else
3879 c->u->u_firstlineno = 1;
3880 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3882 goto error;
3883 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003884
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003886 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 /* Emit code in reverse postorder from dfs. */
3889 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003890 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 for (j = 0; j < b->b_iused; j++)
3892 if (!assemble_emit(&a, &b->b_instr[j]))
3893 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003894 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003895
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003896 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3897 goto error;
3898 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3899 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 co = makecode(c, &a);
3902 error:
3903 assemble_free(&a);
3904 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003905}