blob: d2bfe86ff16d3de188b82e36ec9127a846a2b3d4 [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
Guido van Rossumd8faa362007-04-27 19:54:29 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
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
Nick Coghlan650f0d02007-04-15 12:05:43 +000042#define COMP_GENEXP 0
43#define COMP_LISTCOMP 1
44#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000045#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
50 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000072 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000073 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
88enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
89
90struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000091 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092 basicblock *fb_block;
93};
94
95/* The following items change on entry and exit of code blocks.
96 They must be saved and restored when returning to a block.
97*/
98struct compiler_unit {
99 PySTEntryObject *u_ste;
100
101 PyObject *u_name;
102 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000103 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000104 the argument for opcodes that refer to those collections.
105 */
106 PyObject *u_consts; /* all constants */
107 PyObject *u_names; /* all names */
108 PyObject *u_varnames; /* local variables */
109 PyObject *u_cellvars; /* cell variables */
110 PyObject *u_freevars; /* free variables */
111
112 PyObject *u_private; /* for private name mangling */
113
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000114 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000115 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 /* Pointer to the most recently allocated block. By following b_list
117 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
122 int u_nfblocks;
123 struct fblockinfo u_fblock[CO_MAXBLOCKS];
124
125 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000126 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000127 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128 has been generated with current lineno */
129};
130
131/* This struct captures the global state of a compilation.
132
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133The u pointer points to the current compilation unit, while units
134for enclosing blocks are stored in c_stack. The u and c_stack are
135managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136*/
137
138struct compiler {
139 const char *c_filename;
140 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142 PyCompilerFlags *c_flags;
143
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 struct compiler_unit *u; /* compiler state for current block */
148 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151};
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153static int compiler_enter_scope(struct compiler *, identifier, void *, int);
154static void compiler_free(struct compiler *);
155static basicblock *compiler_new_block(struct compiler *);
156static int compiler_next_instr(struct compiler *, basicblock *);
157static int compiler_addop(struct compiler *, int);
158static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
159static int compiler_addop_i(struct compiler *, int, int);
160static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161static basicblock *compiler_use_new_block(struct compiler *);
162static int compiler_error(struct compiler *, const char *);
163static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
164
165static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
166static int compiler_visit_stmt(struct compiler *, stmt_ty);
167static int compiler_visit_keyword(struct compiler *, keyword_ty);
168static int compiler_visit_expr(struct compiler *, expr_ty);
169static int compiler_augassign(struct compiler *, stmt_ty);
170static int compiler_visit_slice(struct compiler *, slice_ty,
171 expr_context_ty);
172
173static int compiler_push_fblock(struct compiler *, enum fblocktype,
174 basicblock *);
175static void compiler_pop_fblock(struct compiler *, enum fblocktype,
176 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177/* Returns true if there is a loop on the fblock stack. */
178static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179
180static int inplace_binop(struct compiler *, operator_ty);
181static int expr_constant(expr_ty e);
182
Guido van Rossumc2e20742006-02-27 22:32:47 +0000183static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000184static int compiler_call_helper(struct compiler *c, int n,
185 asdl_seq *args,
186 asdl_seq *keywords,
187 expr_ty starargs,
188 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static PyCodeObject *assemble(struct compiler *, int addNone);
191static PyObject *__doc__;
192
193PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000195{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 /* Name mangling: __private becomes _classname__private.
197 This is independent from how the name is used. */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000198 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
199 Py_UNICODE *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200 size_t nlen, plen;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000201 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000202 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000203 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000206 p = PyUnicode_AS_UNICODE(privateobj);
207 nlen = Py_UNICODE_strlen(name);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 /* Don't mangle __id__ or names with dots.
209
210 The only time a name with a dot can occur is when
211 we are compiling an import statement that has a
212 package name.
213
214 TODO(jhylton): Decide whether we want to support
215 mangling of the module name, e.g. __M.X.
216 */
217 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Martin v. Löwis5b222132007-06-10 09:51:05 +0000218 || Py_UNICODE_strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 /* Strip leading underscores from class name */
223 while (*p == '_')
224 p++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000225 if (*p == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000229 plen = Py_UNICODE_strlen(p);
230 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000231 if (!ident)
232 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000234 buffer = PyUnicode_AS_UNICODE(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 buffer[0] = '_';
Martin v. Löwis5b222132007-06-10 09:51:05 +0000236 Py_UNICODE_strncpy(buffer+1, p, plen);
237 Py_UNICODE_strcpy(buffer+1+plen, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000238 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000239}
240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241static int
242compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000243{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000245
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000246 c->c_stack = PyList_New(0);
247 if (!c->c_stack)
248 return 0;
249
250 return 1;
251}
252
253PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000254PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256{
257 struct compiler c;
258 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000259 PyCompilerFlags local_flags;
260 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000262 if (!__doc__) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000263 __doc__ = PyUnicode_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 if (!__doc__)
265 return NULL;
266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267
268 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000269 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000271 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272 c.c_future = PyFuture_FromAST(mod, filename);
273 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000274 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000275 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000276 local_flags.cf_flags = 0;
277 flags = &local_flags;
278 }
279 merged = c.c_future->ff_features | flags->cf_flags;
280 c.c_future->ff_features = merged;
281 flags->cf_flags = merged;
282 c.c_flags = flags;
283 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284
285 c.c_st = PySymtable_Build(mod, filename, c.c_future);
286 if (c.c_st == NULL) {
287 if (!PyErr_Occurred())
288 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000289 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290 }
291
292 /* XXX initialize to NULL for now, need to handle */
293 c.c_encoding = NULL;
294
295 co = compiler_mod(&c, mod);
296
Thomas Wouters1175c432006-02-27 22:49:54 +0000297 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000299 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300 return co;
301}
302
303PyCodeObject *
304PyNode_Compile(struct _node *n, const char *filename)
305{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000306 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000307 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000308 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000309 if (!arena)
310 return NULL;
311 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000312 if (mod)
313 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000314 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000315 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000316}
317
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321 if (c->c_st)
322 PySymtable_Free(c->c_st);
323 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000326}
327
Guido van Rossum79f25d91997-04-29 20:08:16 +0000328static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000330{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000331 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000332 PyObject *v, *k;
333 PyObject *dict = PyDict_New();
334 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000335
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336 n = PyList_Size(list);
337 for (i = 0; i < n; i++) {
338 v = PyInt_FromLong(i);
339 if (!v) {
340 Py_DECREF(dict);
341 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000342 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000343 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000344 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
346 Py_XDECREF(k);
347 Py_DECREF(v);
348 Py_DECREF(dict);
349 return NULL;
350 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000351 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354 return dict;
355}
356
357/* Return new dict containing names from src that match scope(s).
358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359src is a symbol table dictionary. If the scope of a name matches
360either scope_type or flag is set, insert it into the new dict. The
361values are integers, starting at offset and increasing by one for
362each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363*/
364
365static PyObject *
366dictbytype(PyObject *src, int scope_type, int flag, int offset)
367{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000368 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369 PyObject *k, *v, *dest = PyDict_New();
370
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000371 assert(offset >= 0);
372 if (dest == NULL)
373 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374
375 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000377 long vi;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000378 assert(PyInt_Check(v));
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000379 vi = PyInt_AS_LONG(v);
380 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000382 if (scope == scope_type || vi & flag) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000383 PyObject *tuple, *item = PyInt_FromLong(i);
384 if (item == NULL) {
385 Py_DECREF(dest);
386 return NULL;
387 }
388 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000389 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000390 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
391 Py_DECREF(item);
392 Py_DECREF(dest);
393 Py_XDECREF(tuple);
394 return NULL;
395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399 }
400 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000401}
402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403static void
404compiler_unit_check(struct compiler_unit *u)
405{
406 basicblock *block;
407 for (block = u->u_blocks; block != NULL; block = block->b_list) {
408 assert(block != (void *)0xcbcbcbcb);
409 assert(block != (void *)0xfbfbfbfb);
410 assert(block != (void *)0xdbdbdbdb);
411 if (block->b_instr != NULL) {
412 assert(block->b_ialloc > 0);
413 assert(block->b_iused > 0);
414 assert(block->b_ialloc >= block->b_iused);
415 }
416 else {
417 assert (block->b_iused == 0);
418 assert (block->b_ialloc == 0);
419 }
420 }
421}
422
423static void
424compiler_unit_free(struct compiler_unit *u)
425{
426 basicblock *b, *next;
427
428 compiler_unit_check(u);
429 b = u->u_blocks;
430 while (b != NULL) {
431 if (b->b_instr)
432 PyObject_Free((void *)b->b_instr);
433 next = b->b_list;
434 PyObject_Free((void *)b);
435 b = next;
436 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000437 Py_CLEAR(u->u_ste);
438 Py_CLEAR(u->u_name);
439 Py_CLEAR(u->u_consts);
440 Py_CLEAR(u->u_names);
441 Py_CLEAR(u->u_varnames);
442 Py_CLEAR(u->u_freevars);
443 Py_CLEAR(u->u_cellvars);
444 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445 PyObject_Free(u);
446}
447
448static int
449compiler_enter_scope(struct compiler *c, identifier name, void *key,
450 int lineno)
451{
452 struct compiler_unit *u;
453
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000454 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000455 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000456 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 PyErr_NoMemory();
458 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000459 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000460 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000462 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463 u->u_ste = PySymtable_Lookup(c->c_st, key);
464 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000465 compiler_unit_free(u);
466 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 }
468 Py_INCREF(name);
469 u->u_name = name;
470 u->u_varnames = list2dict(u->u_ste->ste_varnames);
471 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000472 if (!u->u_varnames || !u->u_cellvars) {
473 compiler_unit_free(u);
474 return 0;
475 }
476
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000477 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000478 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000479 if (!u->u_freevars) {
480 compiler_unit_free(u);
481 return 0;
482 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483
484 u->u_blocks = NULL;
485 u->u_tmpname = 0;
486 u->u_nfblocks = 0;
487 u->u_firstlineno = lineno;
488 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000489 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490 u->u_consts = PyDict_New();
491 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000492 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493 return 0;
494 }
495 u->u_names = PyDict_New();
496 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000497 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498 return 0;
499 }
500
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000501 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502
503 /* Push the old compiler_unit on the stack. */
504 if (c->u) {
505 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
507 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000508 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 return 0;
510 }
511 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 u->u_private = c->u->u_private;
513 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000514 }
515 c->u = u;
516
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000517 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000518 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519 return 0;
520
521 return 1;
522}
523
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525compiler_exit_scope(struct compiler *c)
526{
527 int n;
528 PyObject *wrapper;
529
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000530 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531 compiler_unit_free(c->u);
532 /* Restore c->u to the parent unit. */
533 n = PyList_GET_SIZE(c->c_stack) - 1;
534 if (n >= 0) {
535 wrapper = PyList_GET_ITEM(c->c_stack, n);
536 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000537 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000538 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000539 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000540 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541 compiler_unit_check(c->u);
542 }
543 else
544 c->u = NULL;
545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546}
547
Guido van Rossumc2e20742006-02-27 22:32:47 +0000548/* Allocate a new "anonymous" local variable.
549 Used by list comprehensions and with statements.
550*/
551
552static PyObject *
553compiler_new_tmpname(struct compiler *c)
554{
555 char tmpname[256];
556 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000557 return PyUnicode_FromString(tmpname);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000558}
559
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560/* Allocate a new block and return a pointer to it.
561 Returns NULL on error.
562*/
563
564static basicblock *
565compiler_new_block(struct compiler *c)
566{
567 basicblock *b;
568 struct compiler_unit *u;
569
570 u = c->u;
571 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000572 if (b == NULL) {
573 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000574 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000576 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000577 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578 b->b_list = u->u_blocks;
579 u->u_blocks = b;
580 return b;
581}
582
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000583static basicblock *
584compiler_use_new_block(struct compiler *c)
585{
586 basicblock *block = compiler_new_block(c);
587 if (block == NULL)
588 return NULL;
589 c->u->u_curblock = block;
590 return block;
591}
592
593static basicblock *
594compiler_next_block(struct compiler *c)
595{
596 basicblock *block = compiler_new_block(c);
597 if (block == NULL)
598 return NULL;
599 c->u->u_curblock->b_next = block;
600 c->u->u_curblock = block;
601 return block;
602}
603
604static basicblock *
605compiler_use_next_block(struct compiler *c, basicblock *block)
606{
607 assert(block != NULL);
608 c->u->u_curblock->b_next = block;
609 c->u->u_curblock = block;
610 return block;
611}
612
613/* Returns the offset of the next instruction in the current block's
614 b_instr array. Resizes the b_instr as necessary.
615 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000616*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617
618static int
619compiler_next_instr(struct compiler *c, basicblock *b)
620{
621 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000622 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000623 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000624 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 if (b->b_instr == NULL) {
626 PyErr_NoMemory();
627 return -1;
628 }
629 b->b_ialloc = DEFAULT_BLOCK_SIZE;
630 memset((char *)b->b_instr, 0,
631 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000632 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635 size_t oldsize, newsize;
636 oldsize = b->b_ialloc * sizeof(struct instr);
637 newsize = oldsize << 1;
638 if (newsize == 0) {
639 PyErr_NoMemory();
640 return -1;
641 }
642 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645 if (tmp == NULL) {
646 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648 }
649 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
651 }
652 return b->b_iused++;
653}
654
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000655/* Set the i_lineno member of the instruction at offse off if the
656 line number for the current expression/statement (?) has not
657 already been set. If it has been set, the call has no effect.
658
659 Every time a new node is b
Thomas Wouters89f507f2006-12-13 04:49:30 +0000660*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000661
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662static void
663compiler_set_lineno(struct compiler *c, int off)
664{
665 basicblock *b;
666 if (c->u->u_lineno_set)
667 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000668 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000670 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000671}
672
673static int
674opcode_stack_effect(int opcode, int oparg)
675{
676 switch (opcode) {
677 case POP_TOP:
678 return -1;
679 case ROT_TWO:
680 case ROT_THREE:
681 return 0;
682 case DUP_TOP:
683 return 1;
684 case ROT_FOUR:
685 return 0;
686
687 case UNARY_POSITIVE:
688 case UNARY_NEGATIVE:
689 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000690 case UNARY_INVERT:
691 return 0;
692
Nick Coghlan650f0d02007-04-15 12:05:43 +0000693 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000694 case LIST_APPEND:
695 return -2;
696
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000697 case BINARY_POWER:
698 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000699 case BINARY_MODULO:
700 case BINARY_ADD:
701 case BINARY_SUBTRACT:
702 case BINARY_SUBSCR:
703 case BINARY_FLOOR_DIVIDE:
704 case BINARY_TRUE_DIVIDE:
705 return -1;
706 case INPLACE_FLOOR_DIVIDE:
707 case INPLACE_TRUE_DIVIDE:
708 return -1;
709
710 case SLICE+0:
711 return 1;
712 case SLICE+1:
713 return 0;
714 case SLICE+2:
715 return 0;
716 case SLICE+3:
717 return -1;
718
719 case STORE_SLICE+0:
720 return -2;
721 case STORE_SLICE+1:
722 return -3;
723 case STORE_SLICE+2:
724 return -3;
725 case STORE_SLICE+3:
726 return -4;
727
728 case DELETE_SLICE+0:
729 return -1;
730 case DELETE_SLICE+1:
731 return -2;
732 case DELETE_SLICE+2:
733 return -2;
734 case DELETE_SLICE+3:
735 return -3;
736
737 case INPLACE_ADD:
738 case INPLACE_SUBTRACT:
739 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000740 case INPLACE_MODULO:
741 return -1;
742 case STORE_SUBSCR:
743 return -3;
744 case DELETE_SUBSCR:
745 return -2;
746
747 case BINARY_LSHIFT:
748 case BINARY_RSHIFT:
749 case BINARY_AND:
750 case BINARY_XOR:
751 case BINARY_OR:
752 return -1;
753 case INPLACE_POWER:
754 return -1;
755 case GET_ITER:
756 return 0;
757
758 case PRINT_EXPR:
759 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000760 case LOAD_BUILD_CLASS:
761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762 case INPLACE_LSHIFT:
763 case INPLACE_RSHIFT:
764 case INPLACE_AND:
765 case INPLACE_XOR:
766 case INPLACE_OR:
767 return -1;
768 case BREAK_LOOP:
769 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000770 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000771 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000772 case STORE_LOCALS:
773 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774 case RETURN_VALUE:
775 return -1;
776 case IMPORT_STAR:
777 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778 case YIELD_VALUE:
779 return 0;
780
781 case POP_BLOCK:
782 return 0;
783 case END_FINALLY:
784 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785
786 case STORE_NAME:
787 return -1;
788 case DELETE_NAME:
789 return 0;
790 case UNPACK_SEQUENCE:
791 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000792 case UNPACK_EX:
793 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794 case FOR_ITER:
795 return 1;
796
797 case STORE_ATTR:
798 return -2;
799 case DELETE_ATTR:
800 return -1;
801 case STORE_GLOBAL:
802 return -1;
803 case DELETE_GLOBAL:
804 return 0;
805 case DUP_TOPX:
806 return oparg;
807 case LOAD_CONST:
808 return 1;
809 case LOAD_NAME:
810 return 1;
811 case BUILD_TUPLE:
812 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000813 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000814 return 1-oparg;
815 case BUILD_MAP:
816 return 1;
Thomas Wouters00e41de2007-02-23 19:56:57 +0000817 case MAKE_BYTES:
818 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819 case LOAD_ATTR:
820 return 0;
821 case COMPARE_OP:
822 return -1;
823 case IMPORT_NAME:
824 return 0;
825 case IMPORT_FROM:
826 return 1;
827
828 case JUMP_FORWARD:
829 case JUMP_IF_FALSE:
830 case JUMP_IF_TRUE:
831 case JUMP_ABSOLUTE:
832 return 0;
833
834 case LOAD_GLOBAL:
835 return 1;
836
837 case CONTINUE_LOOP:
838 return 0;
839 case SETUP_LOOP:
840 return 0;
841 case SETUP_EXCEPT:
842 case SETUP_FINALLY:
843 return 3; /* actually pushed by an exception */
844
845 case LOAD_FAST:
846 return 1;
847 case STORE_FAST:
848 return -1;
849 case DELETE_FAST:
850 return 0;
851
852 case RAISE_VARARGS:
853 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000854#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855 case CALL_FUNCTION:
856 return -NARGS(oparg);
857 case CALL_FUNCTION_VAR:
858 case CALL_FUNCTION_KW:
859 return -NARGS(oparg)-1;
860 case CALL_FUNCTION_VAR_KW:
861 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000863 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000864 case MAKE_CLOSURE:
865 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000866#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867 case BUILD_SLICE:
868 if (oparg == 3)
869 return -2;
870 else
871 return -1;
872
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873 case LOAD_CLOSURE:
874 return 1;
875 case LOAD_DEREF:
876 return 1;
877 case STORE_DEREF:
878 return -1;
879 default:
880 fprintf(stderr, "opcode = %d\n", opcode);
881 Py_FatalError("opcode_stack_effect()");
882
883 }
884 return 0; /* not reachable */
885}
886
887/* Add an opcode with no argument.
888 Returns 0 on failure, 1 on success.
889*/
890
891static int
892compiler_addop(struct compiler *c, int opcode)
893{
894 basicblock *b;
895 struct instr *i;
896 int off;
897 off = compiler_next_instr(c, c->u->u_curblock);
898 if (off < 0)
899 return 0;
900 b = c->u->u_curblock;
901 i = &b->b_instr[off];
902 i->i_opcode = opcode;
903 i->i_hasarg = 0;
904 if (opcode == RETURN_VALUE)
905 b->b_return = 1;
906 compiler_set_lineno(c, off);
907 return 1;
908}
909
910static int
911compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
912{
913 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000914 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000916 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000917 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
918 if (PyFloat_Check(o)) {
919 double d = PyFloat_AS_DOUBLE(o);
920 unsigned char* p = (unsigned char*) &d;
921 /* all we need is to make the tuple different in either the 0.0
922 * or -0.0 case from all others, just to avoid the "coercion".
923 */
924 if (*p==0 && p[sizeof(double)-1]==0)
925 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
926 else
927 t = PyTuple_Pack(2, o, o->ob_type);
928 } else {
929 t = PyTuple_Pack(2, o, o->ob_type);
930 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000931 if (t == NULL)
932 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933
934 v = PyDict_GetItem(dict, t);
935 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000936 if (PyErr_Occurred())
937 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938 arg = PyDict_Size(dict);
939 v = PyInt_FromLong(arg);
940 if (!v) {
941 Py_DECREF(t);
942 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000943 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000944 if (PyDict_SetItem(dict, t, v) < 0) {
945 Py_DECREF(t);
946 Py_DECREF(v);
947 return -1;
948 }
949 Py_DECREF(v);
950 }
951 else
952 arg = PyInt_AsLong(v);
953 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000954 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000955}
956
957static int
958compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
959 PyObject *o)
960{
961 int arg = compiler_add_o(c, dict, o);
962 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000963 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964 return compiler_addop_i(c, opcode, arg);
965}
966
967static int
968compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000969 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970{
971 int arg;
972 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
973 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000974 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000975 arg = compiler_add_o(c, dict, mangled);
976 Py_DECREF(mangled);
977 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000978 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979 return compiler_addop_i(c, opcode, arg);
980}
981
982/* Add an opcode with an integer argument.
983 Returns 0 on failure, 1 on success.
984*/
985
986static int
987compiler_addop_i(struct compiler *c, int opcode, int oparg)
988{
989 struct instr *i;
990 int off;
991 off = compiler_next_instr(c, c->u->u_curblock);
992 if (off < 0)
993 return 0;
994 i = &c->u->u_curblock->b_instr[off];
995 i->i_opcode = opcode;
996 i->i_oparg = oparg;
997 i->i_hasarg = 1;
998 compiler_set_lineno(c, off);
999 return 1;
1000}
1001
1002static int
1003compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1004{
1005 struct instr *i;
1006 int off;
1007
1008 assert(b != NULL);
1009 off = compiler_next_instr(c, c->u->u_curblock);
1010 if (off < 0)
1011 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001012 i = &c->u->u_curblock->b_instr[off];
1013 i->i_opcode = opcode;
1014 i->i_target = b;
1015 i->i_hasarg = 1;
1016 if (absolute)
1017 i->i_jabs = 1;
1018 else
1019 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001020 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001021 return 1;
1022}
1023
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001024/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1025 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026 it as the current block. NEXT_BLOCK() also creates an implicit jump
1027 from the current block to the new block.
1028*/
1029
Thomas Wouters89f507f2006-12-13 04:49:30 +00001030/* The returns inside these macros make it impossible to decref objects
1031 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032*/
1033
1034
1035#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001036 if (compiler_use_new_block((C)) == NULL) \
1037 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038}
1039
1040#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001041 if (compiler_next_block((C)) == NULL) \
1042 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043}
1044
1045#define ADDOP(C, OP) { \
1046 if (!compiler_addop((C), (OP))) \
1047 return 0; \
1048}
1049
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001050#define ADDOP_IN_SCOPE(C, OP) { \
1051 if (!compiler_addop((C), (OP))) { \
1052 compiler_exit_scope(c); \
1053 return 0; \
1054 } \
1055}
1056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057#define ADDOP_O(C, OP, O, TYPE) { \
1058 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1059 return 0; \
1060}
1061
1062#define ADDOP_NAME(C, OP, O, TYPE) { \
1063 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1064 return 0; \
1065}
1066
1067#define ADDOP_I(C, OP, O) { \
1068 if (!compiler_addop_i((C), (OP), (O))) \
1069 return 0; \
1070}
1071
1072#define ADDOP_JABS(C, OP, O) { \
1073 if (!compiler_addop_j((C), (OP), (O), 1)) \
1074 return 0; \
1075}
1076
1077#define ADDOP_JREL(C, OP, O) { \
1078 if (!compiler_addop_j((C), (OP), (O), 0)) \
1079 return 0; \
1080}
1081
1082/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1083 the ASDL name to synthesize the name of the C type and the visit function.
1084*/
1085
1086#define VISIT(C, TYPE, V) {\
1087 if (!compiler_visit_ ## TYPE((C), (V))) \
1088 return 0; \
1089}
1090
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001091#define VISIT_IN_SCOPE(C, TYPE, V) {\
1092 if (!compiler_visit_ ## TYPE((C), (V))) { \
1093 compiler_exit_scope(c); \
1094 return 0; \
1095 } \
1096}
1097
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098#define VISIT_SLICE(C, V, CTX) {\
1099 if (!compiler_visit_slice((C), (V), (CTX))) \
1100 return 0; \
1101}
1102
1103#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001104 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001106 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001107 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108 if (!compiler_visit_ ## TYPE((C), elt)) \
1109 return 0; \
1110 } \
1111}
1112
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001113#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001114 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001115 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001116 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001117 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001118 if (!compiler_visit_ ## TYPE((C), elt)) { \
1119 compiler_exit_scope(c); \
1120 return 0; \
1121 } \
1122 } \
1123}
1124
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125static int
1126compiler_isdocstring(stmt_ty s)
1127{
1128 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001129 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 return s->v.Expr.value->kind == Str_kind;
1131}
1132
1133/* Compile a sequence of statements, checking for a docstring. */
1134
1135static int
1136compiler_body(struct compiler *c, asdl_seq *stmts)
1137{
1138 int i = 0;
1139 stmt_ty st;
1140
1141 if (!asdl_seq_LEN(stmts))
1142 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001144 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1145 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 i = 1;
1147 VISIT(c, expr, st->v.Expr.value);
1148 if (!compiler_nameop(c, __doc__, Store))
1149 return 0;
1150 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001152 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 return 1;
1154}
1155
1156static PyCodeObject *
1157compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001158{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001159 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001160 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 static PyObject *module;
1162 if (!module) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001163 module = PyUnicode_FromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164 if (!module)
1165 return NULL;
1166 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001167 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1168 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001169 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 switch (mod->kind) {
1171 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001172 if (!compiler_body(c, mod->v.Module.body)) {
1173 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001175 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 break;
1177 case Interactive_kind:
1178 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001179 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181 break;
1182 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001183 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 break;
1186 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001187 PyErr_SetString(PyExc_SystemError,
1188 "suite should not be possible");
1189 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001190 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001191 PyErr_Format(PyExc_SystemError,
1192 "module kind %d should not be possible",
1193 mod->kind);
1194 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 co = assemble(c, addNone);
1197 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001198 return co;
1199}
1200
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201/* The test for LOCAL must come before the test for FREE in order to
1202 handle classes where name is both local and free. The local var is
1203 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001204*/
1205
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206static int
1207get_ref_type(struct compiler *c, PyObject *name)
1208{
1209 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001210 if (scope == 0) {
1211 char buf[350];
1212 PyOS_snprintf(buf, sizeof(buf),
1213 "unknown scope for %.100s in %.100s(%s) in %s\n"
1214 "symbols: %s\nlocals: %s\nglobals: %s\n",
1215 PyString_AS_STRING(name),
1216 PyString_AS_STRING(c->u->u_name),
1217 PyObject_REPR(c->u->u_ste->ste_id),
1218 c->c_filename,
1219 PyObject_REPR(c->u->u_ste->ste_symbols),
1220 PyObject_REPR(c->u->u_varnames),
1221 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001223 Py_FatalError(buf);
1224 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001225
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001226 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001227}
1228
1229static int
1230compiler_lookup_arg(PyObject *dict, PyObject *name)
1231{
1232 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001233 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001235 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001237 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001239 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001240 return PyInt_AS_LONG(v);
1241}
1242
1243static int
1244compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1245{
1246 int i, free = PyCode_GetNumFree(co);
1247 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001248 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1249 ADDOP_I(c, MAKE_FUNCTION, args);
1250 return 1;
1251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252 for (i = 0; i < free; ++i) {
1253 /* Bypass com_addop_varname because it will generate
1254 LOAD_DEREF but LOAD_CLOSURE is needed.
1255 */
1256 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1257 int arg, reftype;
1258
1259 /* Special case: If a class contains a method with a
1260 free variable that has the same name as a method,
1261 the name will be considered free *and* local in the
1262 class. It should be handled by the closure, as
1263 well as by the normal name loookup logic.
1264 */
1265 reftype = get_ref_type(c, name);
1266 if (reftype == CELL)
1267 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1268 else /* (reftype == FREE) */
1269 arg = compiler_lookup_arg(c->u->u_freevars, name);
1270 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001271 fprintf(stderr,
1272 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273 "freevars of %s: %s\n",
1274 PyObject_REPR(name),
1275 PyString_AS_STRING(c->u->u_name),
1276 reftype, arg,
1277 PyString_AS_STRING(co->co_name),
1278 PyObject_REPR(co->co_freevars));
1279 Py_FatalError("compiler_make_closure()");
1280 }
1281 ADDOP_I(c, LOAD_CLOSURE, arg);
1282 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001283 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001285 ADDOP_I(c, MAKE_CLOSURE, args);
1286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
1289static int
1290compiler_decorators(struct compiler *c, asdl_seq* decos)
1291{
1292 int i;
1293
1294 if (!decos)
1295 return 1;
1296
1297 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001298 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299 }
1300 return 1;
1301}
1302
1303static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001304compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1305 asdl_seq *kw_defaults)
1306{
1307 int i, default_count = 0;
1308 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001309 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001310 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1311 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001312 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001313 if (!compiler_visit_expr(c, default_)) {
1314 return -1;
1315 }
1316 default_count++;
1317 }
1318 }
1319 return default_count;
1320}
1321
1322static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001323compiler_visit_argannotation(struct compiler *c, identifier id,
1324 expr_ty annotation, PyObject *names)
1325{
1326 if (annotation) {
1327 VISIT(c, expr, annotation);
1328 if (PyList_Append(names, id))
1329 return -1;
1330 }
1331 return 0;
1332}
1333
1334static int
1335compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1336 PyObject *names)
1337{
1338 int i, error;
1339 for (i = 0; i < asdl_seq_LEN(args); i++) {
1340 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001341 error = compiler_visit_argannotation(
1342 c,
1343 arg->arg,
1344 arg->annotation,
1345 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001346 if (error)
1347 return error;
1348 }
1349 return 0;
1350}
1351
1352static int
1353compiler_visit_annotations(struct compiler *c, arguments_ty args,
1354 expr_ty returns)
1355{
Guido van Rossum0240b922007-02-26 21:23:50 +00001356 /* Push arg annotations and a list of the argument names. Return the #
1357 of items pushed. The expressions are evaluated out-of-order wrt the
1358 source code.
1359
1360 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1361 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001362 static identifier return_str;
1363 PyObject *names;
1364 int len;
1365 names = PyList_New(0);
1366 if (!names)
1367 return -1;
1368
1369 if (compiler_visit_argannotations(c, args->args, names))
1370 goto error;
1371 if (args->varargannotation &&
1372 compiler_visit_argannotation(c, args->vararg,
1373 args->varargannotation, names))
1374 goto error;
1375 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1376 goto error;
1377 if (args->kwargannotation &&
1378 compiler_visit_argannotation(c, args->kwarg,
1379 args->kwargannotation, names))
1380 goto error;
1381
1382 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001383 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001384 if (!return_str)
1385 goto error;
1386 }
1387 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1388 goto error;
1389 }
1390
1391 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001392 if (len > 65534) {
1393 /* len must fit in 16 bits, and len is incremented below */
1394 PyErr_SetString(PyExc_SyntaxError,
1395 "too many annotations");
1396 goto error;
1397 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001398 if (len) {
1399 /* convert names to a tuple and place on stack */
1400 PyObject *elt;
1401 int i;
1402 PyObject *s = PyTuple_New(len);
1403 if (!s)
1404 goto error;
1405 for (i = 0; i < len; i++) {
1406 elt = PyList_GET_ITEM(names, i);
1407 Py_INCREF(elt);
1408 PyTuple_SET_ITEM(s, i, elt);
1409 }
1410 ADDOP_O(c, LOAD_CONST, s, consts);
1411 Py_DECREF(s);
1412 len++; /* include the just-pushed tuple */
1413 }
1414 Py_DECREF(names);
1415 return len;
1416
1417error:
1418 Py_DECREF(names);
1419 return -1;
1420}
1421
1422static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423compiler_function(struct compiler *c, stmt_ty s)
1424{
1425 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001426 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001428 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001429 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001430 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001431 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001432 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433
1434 assert(s->kind == FunctionDef_kind);
1435
1436 if (!compiler_decorators(c, decos))
1437 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001438 if (args->kwonlyargs) {
1439 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1440 args->kw_defaults);
1441 if (res < 0)
1442 return 0;
1443 kw_default_count = res;
1444 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445 if (args->defaults)
1446 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001447 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001448 if (num_annotations < 0)
1449 return 0;
1450 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1453 s->lineno))
1454 return 0;
1455
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001456 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001457 docstring = compiler_isdocstring(st);
1458 if (docstring)
1459 first_const = st->v.Expr.value->v.Str.s;
1460 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001461 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001462 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001466 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001468 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001470 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1471 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472 }
1473 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001474 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475 if (co == NULL)
1476 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477
Guido van Rossum4f72a782006-10-27 23:31:49 +00001478 arglength = asdl_seq_LEN(args->defaults);
1479 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001480 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001481 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001482 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483
Neal Norwitzc1505362006-12-28 06:47:50 +00001484 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1486 ADDOP_I(c, CALL_FUNCTION, 1);
1487 }
1488
1489 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1490}
1491
1492static int
1493compiler_class(struct compiler *c, stmt_ty s)
1494{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001495 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001497 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001498 PySTEntryObject *ste;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001499 int err, i;
1500 asdl_seq* decos = s->v.ClassDef.decorator_list;
1501
1502 if (!compiler_decorators(c, decos))
1503 return 0;
1504
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001505 /* initialize statics */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001506 if (locals == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001507 locals = PyUnicode_FromString("__locals__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001508 if (locals == NULL)
1509 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001510 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001512 /* ultimately generate code for:
1513 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1514 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001515 <func> is a function/closure created from the class body;
1516 it has a single argument (__locals__) where the dict
1517 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001518 <name> is the class name
1519 <bases> is the positional arguments and *varargs argument
1520 <keywords> is the keyword arguments and **kwds argument
1521 This borrows from compiler_call.
1522 */
1523
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001524 /* 0. Create a fake argument named __locals__ */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001525 ste = PySymtable_Lookup(c->c_st, s);
1526 if (ste == NULL)
1527 return 0;
1528 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001529 err = PyList_Append(ste->ste_varnames, locals);
1530 Py_DECREF(ste);
1531 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001532 return 0;
1533
1534 /* 1. compile the class body into a code object */
1535 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1536 return 0;
1537 /* this block represents what we do in the new scope */
1538 {
1539 /* use the class name for name mangling */
1540 Py_INCREF(s->v.ClassDef.name);
1541 c->u->u_private = s->v.ClassDef.name;
1542 /* force it to have one mandatory argument */
1543 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001544 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001545 ADDOP_I(c, LOAD_FAST, 0);
1546 /* ... and store it into f_locals */
1547 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001548 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001549 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001550 if (!str || !compiler_nameop(c, str, Load)) {
1551 Py_XDECREF(str);
1552 compiler_exit_scope(c);
1553 return 0;
1554 }
1555 Py_DECREF(str);
1556 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001557 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001558 if (!str || !compiler_nameop(c, str, Store)) {
1559 Py_XDECREF(str);
1560 compiler_exit_scope(c);
1561 return 0;
1562 }
1563 Py_DECREF(str);
1564 /* compile the body proper */
1565 if (!compiler_body(c, s->v.ClassDef.body)) {
1566 compiler_exit_scope(c);
1567 return 0;
1568 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001569 /* return the (empty) __class__ cell */
1570 str = PyUnicode_InternFromString("__class__");
1571 if (str == NULL) {
1572 compiler_exit_scope(c);
1573 return 0;
1574 }
1575 i = compiler_lookup_arg(c->u->u_cellvars, str);
1576 Py_DECREF(str);
1577 if (i == -1) {
1578 /* This happens when nobody references the cell */
1579 PyErr_Clear();
1580 /* Return None */
1581 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1582 }
1583 else {
1584 /* Return the cell where to store __class__ */
1585 ADDOP_I(c, LOAD_CLOSURE, i);
1586 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001587 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1588 /* create the code object */
1589 co = assemble(c, 1);
1590 }
1591 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001592 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001593 if (co == NULL)
1594 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001596 /* 2. load the 'build_class' function */
1597 ADDOP(c, LOAD_BUILD_CLASS);
1598
1599 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001600 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001601 Py_DECREF(co);
1602
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001603 /* 4. load class name */
1604 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1605
1606 /* 5. generate the rest of the code for the call */
1607 if (!compiler_call_helper(c, 2,
1608 s->v.ClassDef.bases,
1609 s->v.ClassDef.keywords,
1610 s->v.ClassDef.starargs,
1611 s->v.ClassDef.kwargs))
1612 return 0;
1613
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001614 /* 6. apply decorators */
1615 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1616 ADDOP_I(c, CALL_FUNCTION, 1);
1617 }
1618
1619 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001620 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1621 return 0;
1622 return 1;
1623}
1624
1625static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001626compiler_ifexp(struct compiler *c, expr_ty e)
1627{
1628 basicblock *end, *next;
1629
1630 assert(e->kind == IfExp_kind);
1631 end = compiler_new_block(c);
1632 if (end == NULL)
1633 return 0;
1634 next = compiler_new_block(c);
1635 if (next == NULL)
1636 return 0;
1637 VISIT(c, expr, e->v.IfExp.test);
1638 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1639 ADDOP(c, POP_TOP);
1640 VISIT(c, expr, e->v.IfExp.body);
1641 ADDOP_JREL(c, JUMP_FORWARD, end);
1642 compiler_use_next_block(c, next);
1643 ADDOP(c, POP_TOP);
1644 VISIT(c, expr, e->v.IfExp.orelse);
1645 compiler_use_next_block(c, end);
1646 return 1;
1647}
1648
1649static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001650compiler_lambda(struct compiler *c, expr_ty e)
1651{
1652 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001653 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001654 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655 arguments_ty args = e->v.Lambda.args;
1656 assert(e->kind == Lambda_kind);
1657
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001658 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001659 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001660 if (!name)
1661 return 0;
1662 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663
Guido van Rossum4f72a782006-10-27 23:31:49 +00001664 if (args->kwonlyargs) {
1665 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1666 args->kw_defaults);
1667 if (res < 0) return 0;
1668 kw_default_count = res;
1669 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670 if (args->defaults)
1671 VISIT_SEQ(c, expr, args->defaults);
1672 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1673 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001674
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001676 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001677 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1678 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001680 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681 if (co == NULL)
1682 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683
Guido van Rossum4f72a782006-10-27 23:31:49 +00001684 arglength = asdl_seq_LEN(args->defaults);
1685 arglength |= kw_default_count << 8;
1686 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001687 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688
1689 return 1;
1690}
1691
1692static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693compiler_if(struct compiler *c, stmt_ty s)
1694{
1695 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001696 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697 assert(s->kind == If_kind);
1698 end = compiler_new_block(c);
1699 if (end == NULL)
1700 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001701 next = compiler_new_block(c);
1702 if (next == NULL)
1703 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001704
1705 constant = expr_constant(s->v.If.test);
1706 /* constant = 0: "if 0"
1707 * constant = 1: "if 1", "if 2", ...
1708 * constant = -1: rest */
1709 if (constant == 0) {
1710 if (s->v.If.orelse)
1711 VISIT_SEQ(c, stmt, s->v.If.orelse);
1712 } else if (constant == 1) {
1713 VISIT_SEQ(c, stmt, s->v.If.body);
1714 } else {
1715 VISIT(c, expr, s->v.If.test);
1716 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1717 ADDOP(c, POP_TOP);
1718 VISIT_SEQ(c, stmt, s->v.If.body);
1719 ADDOP_JREL(c, JUMP_FORWARD, end);
1720 compiler_use_next_block(c, next);
1721 ADDOP(c, POP_TOP);
1722 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001723 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001724 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001725 compiler_use_next_block(c, end);
1726 return 1;
1727}
1728
1729static int
1730compiler_for(struct compiler *c, stmt_ty s)
1731{
1732 basicblock *start, *cleanup, *end;
1733
1734 start = compiler_new_block(c);
1735 cleanup = compiler_new_block(c);
1736 end = compiler_new_block(c);
1737 if (start == NULL || end == NULL || cleanup == NULL)
1738 return 0;
1739 ADDOP_JREL(c, SETUP_LOOP, end);
1740 if (!compiler_push_fblock(c, LOOP, start))
1741 return 0;
1742 VISIT(c, expr, s->v.For.iter);
1743 ADDOP(c, GET_ITER);
1744 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001745 /* XXX(nnorwitz): is there a better way to handle this?
1746 for loops are special, we want to be able to trace them
1747 each time around, so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001748 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001749 ADDOP_JREL(c, FOR_ITER, cleanup);
1750 VISIT(c, expr, s->v.For.target);
1751 VISIT_SEQ(c, stmt, s->v.For.body);
1752 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1753 compiler_use_next_block(c, cleanup);
1754 ADDOP(c, POP_BLOCK);
1755 compiler_pop_fblock(c, LOOP, start);
1756 VISIT_SEQ(c, stmt, s->v.For.orelse);
1757 compiler_use_next_block(c, end);
1758 return 1;
1759}
1760
1761static int
1762compiler_while(struct compiler *c, stmt_ty s)
1763{
1764 basicblock *loop, *orelse, *end, *anchor = NULL;
1765 int constant = expr_constant(s->v.While.test);
1766
1767 if (constant == 0)
1768 return 1;
1769 loop = compiler_new_block(c);
1770 end = compiler_new_block(c);
1771 if (constant == -1) {
1772 anchor = compiler_new_block(c);
1773 if (anchor == NULL)
1774 return 0;
1775 }
1776 if (loop == NULL || end == NULL)
1777 return 0;
1778 if (s->v.While.orelse) {
1779 orelse = compiler_new_block(c);
1780 if (orelse == NULL)
1781 return 0;
1782 }
1783 else
1784 orelse = NULL;
1785
1786 ADDOP_JREL(c, SETUP_LOOP, end);
1787 compiler_use_next_block(c, loop);
1788 if (!compiler_push_fblock(c, LOOP, loop))
1789 return 0;
1790 if (constant == -1) {
1791 VISIT(c, expr, s->v.While.test);
1792 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1793 ADDOP(c, POP_TOP);
1794 }
1795 VISIT_SEQ(c, stmt, s->v.While.body);
1796 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1797
1798 /* XXX should the two POP instructions be in a separate block
1799 if there is no else clause ?
1800 */
1801
1802 if (constant == -1) {
1803 compiler_use_next_block(c, anchor);
1804 ADDOP(c, POP_TOP);
1805 ADDOP(c, POP_BLOCK);
1806 }
1807 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001808 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 VISIT_SEQ(c, stmt, s->v.While.orelse);
1810 compiler_use_next_block(c, end);
1811
1812 return 1;
1813}
1814
1815static int
1816compiler_continue(struct compiler *c)
1817{
1818 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001819 static const char IN_FINALLY_ERROR_MSG[] =
1820 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821 int i;
1822
1823 if (!c->u->u_nfblocks)
1824 return compiler_error(c, LOOP_ERROR_MSG);
1825 i = c->u->u_nfblocks - 1;
1826 switch (c->u->u_fblock[i].fb_type) {
1827 case LOOP:
1828 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1829 break;
1830 case EXCEPT:
1831 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001832 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1833 /* Prevent continue anywhere under a finally
1834 even if hidden in a sub-try or except. */
1835 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1836 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838 if (i == -1)
1839 return compiler_error(c, LOOP_ERROR_MSG);
1840 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1841 break;
1842 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001843 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 }
1845
1846 return 1;
1847}
1848
1849/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1850
1851 SETUP_FINALLY L
1852 <code for body>
1853 POP_BLOCK
1854 LOAD_CONST <None>
1855 L: <code for finalbody>
1856 END_FINALLY
1857
1858 The special instructions use the block stack. Each block
1859 stack entry contains the instruction that created it (here
1860 SETUP_FINALLY), the level of the value stack at the time the
1861 block stack entry was created, and a label (here L).
1862
1863 SETUP_FINALLY:
1864 Pushes the current value stack level and the label
1865 onto the block stack.
1866 POP_BLOCK:
1867 Pops en entry from the block stack, and pops the value
1868 stack until its level is the same as indicated on the
1869 block stack. (The label is ignored.)
1870 END_FINALLY:
1871 Pops a variable number of entries from the *value* stack
1872 and re-raises the exception they specify. The number of
1873 entries popped depends on the (pseudo) exception type.
1874
1875 The block stack is unwound when an exception is raised:
1876 when a SETUP_FINALLY entry is found, the exception is pushed
1877 onto the value stack (and the exception condition is cleared),
1878 and the interpreter jumps to the label gotten from the block
1879 stack.
1880*/
1881
1882static int
1883compiler_try_finally(struct compiler *c, stmt_ty s)
1884{
1885 basicblock *body, *end;
1886 body = compiler_new_block(c);
1887 end = compiler_new_block(c);
1888 if (body == NULL || end == NULL)
1889 return 0;
1890
1891 ADDOP_JREL(c, SETUP_FINALLY, end);
1892 compiler_use_next_block(c, body);
1893 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1894 return 0;
1895 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1896 ADDOP(c, POP_BLOCK);
1897 compiler_pop_fblock(c, FINALLY_TRY, body);
1898
1899 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1900 compiler_use_next_block(c, end);
1901 if (!compiler_push_fblock(c, FINALLY_END, end))
1902 return 0;
1903 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1904 ADDOP(c, END_FINALLY);
1905 compiler_pop_fblock(c, FINALLY_END, end);
1906
1907 return 1;
1908}
1909
1910/*
1911 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1912 (The contents of the value stack is shown in [], with the top
1913 at the right; 'tb' is trace-back info, 'val' the exception's
1914 associated value, and 'exc' the exception.)
1915
1916 Value stack Label Instruction Argument
1917 [] SETUP_EXCEPT L1
1918 [] <code for S>
1919 [] POP_BLOCK
1920 [] JUMP_FORWARD L0
1921
1922 [tb, val, exc] L1: DUP )
1923 [tb, val, exc, exc] <evaluate E1> )
1924 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1925 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1926 [tb, val, exc, 1] POP )
1927 [tb, val, exc] POP
1928 [tb, val] <assign to V1> (or POP if no V1)
1929 [tb] POP
1930 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001931 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932
1933 [tb, val, exc, 0] L2: POP
1934 [tb, val, exc] DUP
1935 .............................etc.......................
1936
1937 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001938 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939
1940 [] L0: <next statement>
1941
1942 Of course, parts are not generated if Vi or Ei is not present.
1943*/
1944static int
1945compiler_try_except(struct compiler *c, stmt_ty s)
1946{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001947 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948 int i, n;
1949
1950 body = compiler_new_block(c);
1951 except = compiler_new_block(c);
1952 orelse = compiler_new_block(c);
1953 end = compiler_new_block(c);
1954 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1955 return 0;
1956 ADDOP_JREL(c, SETUP_EXCEPT, except);
1957 compiler_use_next_block(c, body);
1958 if (!compiler_push_fblock(c, EXCEPT, body))
1959 return 0;
1960 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1961 ADDOP(c, POP_BLOCK);
1962 compiler_pop_fblock(c, EXCEPT, body);
1963 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1964 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1965 compiler_use_next_block(c, except);
1966 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001967 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968 s->v.TryExcept.handlers, i);
1969 if (!handler->type && i < n-1)
1970 return compiler_error(c, "default 'except:' must be last");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001971 c->u->u_lineno_set = 0;
1972 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973 except = compiler_new_block(c);
1974 if (except == NULL)
1975 return 0;
1976 if (handler->type) {
1977 ADDOP(c, DUP_TOP);
1978 VISIT(c, expr, handler->type);
1979 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1980 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1981 ADDOP(c, POP_TOP);
1982 }
1983 ADDOP(c, POP_TOP);
1984 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001985 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001986
1987 cleanup_end = compiler_new_block(c);
1988 cleanup_body = compiler_new_block(c);
1989 if(!(cleanup_end || cleanup_body))
1990 return 0;
1991
Guido van Rossum16be03e2007-01-10 18:51:35 +00001992 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001993 ADDOP(c, POP_TOP);
1994
1995 /*
1996 try:
1997 # body
1998 except type as name:
1999 try:
2000 # body
2001 finally:
2002 name = None
2003 del name
2004 */
2005
2006 /* second try: */
2007 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2008 compiler_use_next_block(c, cleanup_body);
2009 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2010 return 0;
2011
2012 /* second # body */
2013 VISIT_SEQ(c, stmt, handler->body);
2014 ADDOP(c, POP_BLOCK);
2015 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2016
2017 /* finally: */
2018 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2019 compiler_use_next_block(c, cleanup_end);
2020 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2021 return 0;
2022
2023 /* name = None */
2024 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00002025 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002026
Guido van Rossum16be03e2007-01-10 18:51:35 +00002027 /* del name */
2028 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002029
2030 ADDOP(c, END_FINALLY);
2031 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032 }
2033 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00002034 ADDOP(c, POP_TOP);
2035 ADDOP(c, POP_TOP);
2036 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 ADDOP_JREL(c, JUMP_FORWARD, end);
2039 compiler_use_next_block(c, except);
2040 if (handler->type)
2041 ADDOP(c, POP_TOP);
2042 }
2043 ADDOP(c, END_FINALLY);
2044 compiler_use_next_block(c, orelse);
2045 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2046 compiler_use_next_block(c, end);
2047 return 1;
2048}
2049
2050static int
2051compiler_import_as(struct compiler *c, identifier name, identifier asname)
2052{
2053 /* The IMPORT_NAME opcode was already generated. This function
2054 merely needs to bind the result to a name.
2055
2056 If there is a dot in name, we need to split it and emit a
2057 LOAD_ATTR for each name.
2058 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002059 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2060 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 if (dot) {
2062 /* Consume the base module name to get the first attribute */
2063 src = dot + 1;
2064 while (dot) {
2065 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002066 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002067 dot = Py_UNICODE_strchr(src, '.');
2068 attr = PyUnicode_FromUnicode(src,
2069 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002070 if (!attr)
2071 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002073 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 src = dot + 1;
2075 }
2076 }
2077 return compiler_nameop(c, asname, Store);
2078}
2079
2080static int
2081compiler_import(struct compiler *c, stmt_ty s)
2082{
2083 /* The Import node stores a module name like a.b.c as a single
2084 string. This is convenient for all cases except
2085 import a.b.c as d
2086 where we need to parse that string to extract the individual
2087 module names.
2088 XXX Perhaps change the representation to make this case simpler?
2089 */
2090 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002091
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002093 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002095 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096
Guido van Rossum45aecf42006-03-15 04:58:47 +00002097 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002098 if (level == NULL)
2099 return 0;
2100
2101 ADDOP_O(c, LOAD_CONST, level, consts);
2102 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2104 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2105
2106 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002107 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002108 if (!r)
2109 return r;
2110 }
2111 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002113 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2114 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002116 tmp = PyUnicode_FromUnicode(base,
2117 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118 r = compiler_nameop(c, tmp, Store);
2119 if (dot) {
2120 Py_DECREF(tmp);
2121 }
2122 if (!r)
2123 return r;
2124 }
2125 }
2126 return 1;
2127}
2128
2129static int
2130compiler_from_import(struct compiler *c, stmt_ty s)
2131{
2132 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133
2134 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002135 PyObject *level;
2136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137 if (!names)
2138 return 0;
2139
Guido van Rossum45aecf42006-03-15 04:58:47 +00002140 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002141 if (!level) {
2142 Py_DECREF(names);
2143 return 0;
2144 }
2145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 /* build up the names */
2147 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002148 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 Py_INCREF(alias->name);
2150 PyTuple_SET_ITEM(names, i, alias->name);
2151 }
2152
2153 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002154 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2155 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002156 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157 Py_DECREF(names);
2158 return compiler_error(c,
2159 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002160 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161
2162 }
2163 }
2164
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002165 ADDOP_O(c, LOAD_CONST, level, consts);
2166 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002168 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2170 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002171 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172 identifier store_name;
2173
Martin v. Löwis5b222132007-06-10 09:51:05 +00002174 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175 assert(n == 1);
2176 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002177 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 }
2179
2180 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2181 store_name = alias->name;
2182 if (alias->asname)
2183 store_name = alias->asname;
2184
2185 if (!compiler_nameop(c, store_name, Store)) {
2186 Py_DECREF(names);
2187 return 0;
2188 }
2189 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002190 /* remove imported module */
2191 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192 return 1;
2193}
2194
2195static int
2196compiler_assert(struct compiler *c, stmt_ty s)
2197{
2198 static PyObject *assertion_error = NULL;
2199 basicblock *end;
2200
2201 if (Py_OptimizeFlag)
2202 return 1;
2203 if (assertion_error == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002204 assertion_error = PyUnicode_FromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205 if (assertion_error == NULL)
2206 return 0;
2207 }
2208 VISIT(c, expr, s->v.Assert.test);
2209 end = compiler_new_block(c);
2210 if (end == NULL)
2211 return 0;
2212 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2213 ADDOP(c, POP_TOP);
2214 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2215 if (s->v.Assert.msg) {
2216 VISIT(c, expr, s->v.Assert.msg);
2217 ADDOP_I(c, RAISE_VARARGS, 2);
2218 }
2219 else {
2220 ADDOP_I(c, RAISE_VARARGS, 1);
2221 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002222 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 ADDOP(c, POP_TOP);
2224 return 1;
2225}
2226
2227static int
2228compiler_visit_stmt(struct compiler *c, stmt_ty s)
2229{
2230 int i, n;
2231
Thomas Wouters89f507f2006-12-13 04:49:30 +00002232 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002233 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002234 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002235
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002237 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002239 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002241 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 if (c->u->u_ste->ste_type != FunctionBlock)
2243 return compiler_error(c, "'return' outside function");
2244 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 VISIT(c, expr, s->v.Return.value);
2246 }
2247 else
2248 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2249 ADDOP(c, RETURN_VALUE);
2250 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002251 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252 VISIT_SEQ(c, expr, s->v.Delete.targets)
2253 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002254 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 n = asdl_seq_LEN(s->v.Assign.targets);
2256 VISIT(c, expr, s->v.Assign.value);
2257 for (i = 0; i < n; i++) {
2258 if (i < n - 1)
2259 ADDOP(c, DUP_TOP);
2260 VISIT(c, expr,
2261 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2262 }
2263 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002264 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002266 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002268 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002270 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002272 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273 n = 0;
2274 if (s->v.Raise.type) {
2275 VISIT(c, expr, s->v.Raise.type);
2276 n++;
2277 if (s->v.Raise.inst) {
2278 VISIT(c, expr, s->v.Raise.inst);
2279 n++;
2280 if (s->v.Raise.tback) {
2281 VISIT(c, expr, s->v.Raise.tback);
2282 n++;
2283 }
2284 }
2285 }
2286 ADDOP_I(c, RAISE_VARARGS, n);
2287 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002288 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002290 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002292 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002294 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002295 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002296 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002298 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002299 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002301 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002303 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304 ADDOP(c, PRINT_EXPR);
2305 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002306 else if (s->v.Expr.value->kind != Str_kind &&
2307 s->v.Expr.value->kind != Num_kind) {
2308 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 ADDOP(c, POP_TOP);
2310 }
2311 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002312 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002314 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002315 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 return compiler_error(c, "'break' outside loop");
2317 ADDOP(c, BREAK_LOOP);
2318 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002321 case With_kind:
2322 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 }
2324 return 1;
2325}
2326
2327static int
2328unaryop(unaryop_ty op)
2329{
2330 switch (op) {
2331 case Invert:
2332 return UNARY_INVERT;
2333 case Not:
2334 return UNARY_NOT;
2335 case UAdd:
2336 return UNARY_POSITIVE;
2337 case USub:
2338 return UNARY_NEGATIVE;
2339 }
2340 return 0;
2341}
2342
2343static int
2344binop(struct compiler *c, operator_ty op)
2345{
2346 switch (op) {
2347 case Add:
2348 return BINARY_ADD;
2349 case Sub:
2350 return BINARY_SUBTRACT;
2351 case Mult:
2352 return BINARY_MULTIPLY;
2353 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002354 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 case Mod:
2356 return BINARY_MODULO;
2357 case Pow:
2358 return BINARY_POWER;
2359 case LShift:
2360 return BINARY_LSHIFT;
2361 case RShift:
2362 return BINARY_RSHIFT;
2363 case BitOr:
2364 return BINARY_OR;
2365 case BitXor:
2366 return BINARY_XOR;
2367 case BitAnd:
2368 return BINARY_AND;
2369 case FloorDiv:
2370 return BINARY_FLOOR_DIVIDE;
2371 }
2372 return 0;
2373}
2374
2375static int
2376cmpop(cmpop_ty op)
2377{
2378 switch (op) {
2379 case Eq:
2380 return PyCmp_EQ;
2381 case NotEq:
2382 return PyCmp_NE;
2383 case Lt:
2384 return PyCmp_LT;
2385 case LtE:
2386 return PyCmp_LE;
2387 case Gt:
2388 return PyCmp_GT;
2389 case GtE:
2390 return PyCmp_GE;
2391 case Is:
2392 return PyCmp_IS;
2393 case IsNot:
2394 return PyCmp_IS_NOT;
2395 case In:
2396 return PyCmp_IN;
2397 case NotIn:
2398 return PyCmp_NOT_IN;
2399 }
2400 return PyCmp_BAD;
2401}
2402
2403static int
2404inplace_binop(struct compiler *c, operator_ty op)
2405{
2406 switch (op) {
2407 case Add:
2408 return INPLACE_ADD;
2409 case Sub:
2410 return INPLACE_SUBTRACT;
2411 case Mult:
2412 return INPLACE_MULTIPLY;
2413 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002414 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415 case Mod:
2416 return INPLACE_MODULO;
2417 case Pow:
2418 return INPLACE_POWER;
2419 case LShift:
2420 return INPLACE_LSHIFT;
2421 case RShift:
2422 return INPLACE_RSHIFT;
2423 case BitOr:
2424 return INPLACE_OR;
2425 case BitXor:
2426 return INPLACE_XOR;
2427 case BitAnd:
2428 return INPLACE_AND;
2429 case FloorDiv:
2430 return INPLACE_FLOOR_DIVIDE;
2431 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002432 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002433 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002434 return 0;
2435}
2436
2437static int
2438compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2439{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002440 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2442
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002443 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002444 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002445 /* XXX AugStore isn't used anywhere! */
2446
2447 /* First check for assignment to __debug__. Param? */
2448 if ((ctx == Store || ctx == AugStore || ctx == Del)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002449 && !PyUnicode_CompareWithASCIIString(name, "__debug__")) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 return compiler_error(c, "can not assign to __debug__");
2451 }
2452
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002453 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002454 if (!mangled)
2455 return 0;
2456
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002457 op = 0;
2458 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002459 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 switch (scope) {
2461 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002462 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 optype = OP_DEREF;
2464 break;
2465 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002466 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 optype = OP_DEREF;
2468 break;
2469 case LOCAL:
2470 if (c->u->u_ste->ste_type == FunctionBlock)
2471 optype = OP_FAST;
2472 break;
2473 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002474 if (c->u->u_ste->ste_type == FunctionBlock &&
2475 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 optype = OP_GLOBAL;
2477 break;
2478 case GLOBAL_EXPLICIT:
2479 optype = OP_GLOBAL;
2480 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002481 default:
2482 /* scope can be 0 */
2483 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 }
2485
2486 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002487 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488
2489 switch (optype) {
2490 case OP_DEREF:
2491 switch (ctx) {
2492 case Load: op = LOAD_DEREF; break;
2493 case Store: op = STORE_DEREF; break;
2494 case AugLoad:
2495 case AugStore:
2496 break;
2497 case Del:
2498 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002499 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002501 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002502 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002505 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002506 PyErr_SetString(PyExc_SystemError,
2507 "param invalid for deref variable");
2508 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509 }
2510 break;
2511 case OP_FAST:
2512 switch (ctx) {
2513 case Load: op = LOAD_FAST; break;
2514 case Store: op = STORE_FAST; break;
2515 case Del: op = DELETE_FAST; break;
2516 case AugLoad:
2517 case AugStore:
2518 break;
2519 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002520 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002521 PyErr_SetString(PyExc_SystemError,
2522 "param invalid for local variable");
2523 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002525 ADDOP_O(c, op, mangled, varnames);
2526 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 return 1;
2528 case OP_GLOBAL:
2529 switch (ctx) {
2530 case Load: op = LOAD_GLOBAL; break;
2531 case Store: op = STORE_GLOBAL; break;
2532 case Del: op = DELETE_GLOBAL; break;
2533 case AugLoad:
2534 case AugStore:
2535 break;
2536 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002537 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002538 PyErr_SetString(PyExc_SystemError,
2539 "param invalid for global variable");
2540 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 }
2542 break;
2543 case OP_NAME:
2544 switch (ctx) {
2545 case Load: op = LOAD_NAME; break;
2546 case Store: op = STORE_NAME; break;
2547 case Del: op = DELETE_NAME; break;
2548 case AugLoad:
2549 case AugStore:
2550 break;
2551 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002552 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002553 PyErr_SetString(PyExc_SystemError,
2554 "param invalid for name variable");
2555 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556 }
2557 break;
2558 }
2559
2560 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002561 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002562 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002563 if (arg < 0)
2564 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002565 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002566}
2567
2568static int
2569compiler_boolop(struct compiler *c, expr_ty e)
2570{
2571 basicblock *end;
2572 int jumpi, i, n;
2573 asdl_seq *s;
2574
2575 assert(e->kind == BoolOp_kind);
2576 if (e->v.BoolOp.op == And)
2577 jumpi = JUMP_IF_FALSE;
2578 else
2579 jumpi = JUMP_IF_TRUE;
2580 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002581 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 return 0;
2583 s = e->v.BoolOp.values;
2584 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002585 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002587 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 ADDOP_JREL(c, jumpi, end);
2589 ADDOP(c, POP_TOP)
2590 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002591 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 compiler_use_next_block(c, end);
2593 return 1;
2594}
2595
2596static int
2597compiler_list(struct compiler *c, expr_ty e)
2598{
2599 int n = asdl_seq_LEN(e->v.List.elts);
2600 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002601 int i, seen_star = 0;
2602 for (i = 0; i < n; i++) {
2603 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2604 if (elt->kind == Starred_kind && !seen_star) {
2605 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2606 seen_star = 1;
2607 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2608 } else if (elt->kind == Starred_kind) {
2609 return compiler_error(c,
2610 "two starred expressions in assignment");
2611 }
2612 }
2613 if (!seen_star) {
2614 ADDOP_I(c, UNPACK_SEQUENCE, n);
2615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 }
2617 VISIT_SEQ(c, expr, e->v.List.elts);
2618 if (e->v.List.ctx == Load) {
2619 ADDOP_I(c, BUILD_LIST, n);
2620 }
2621 return 1;
2622}
2623
2624static int
2625compiler_tuple(struct compiler *c, expr_ty e)
2626{
2627 int n = asdl_seq_LEN(e->v.Tuple.elts);
2628 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002629 int i, seen_star = 0;
2630 for (i = 0; i < n; i++) {
2631 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2632 if (elt->kind == Starred_kind && !seen_star) {
2633 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2634 seen_star = 1;
2635 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2636 } else if (elt->kind == Starred_kind) {
2637 return compiler_error(c,
2638 "two starred expressions in assignment");
2639 }
2640 }
2641 if (!seen_star) {
2642 ADDOP_I(c, UNPACK_SEQUENCE, n);
2643 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644 }
2645 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2646 if (e->v.Tuple.ctx == Load) {
2647 ADDOP_I(c, BUILD_TUPLE, n);
2648 }
2649 return 1;
2650}
2651
2652static int
2653compiler_compare(struct compiler *c, expr_ty e)
2654{
2655 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002656 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657
2658 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2659 VISIT(c, expr, e->v.Compare.left);
2660 n = asdl_seq_LEN(e->v.Compare.ops);
2661 assert(n > 0);
2662 if (n > 1) {
2663 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002664 if (cleanup == NULL)
2665 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002666 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002667 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 }
2669 for (i = 1; i < n; i++) {
2670 ADDOP(c, DUP_TOP);
2671 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002673 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002674 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2676 NEXT_BLOCK(c);
2677 ADDOP(c, POP_TOP);
2678 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002679 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002680 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002682 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002684 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685 if (n > 1) {
2686 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002687 if (end == NULL)
2688 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 ADDOP_JREL(c, JUMP_FORWARD, end);
2690 compiler_use_next_block(c, cleanup);
2691 ADDOP(c, ROT_TWO);
2692 ADDOP(c, POP_TOP);
2693 compiler_use_next_block(c, end);
2694 }
2695 return 1;
2696}
2697
2698static int
2699compiler_call(struct compiler *c, expr_ty e)
2700{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002702 return compiler_call_helper(c, 0,
2703 e->v.Call.args,
2704 e->v.Call.keywords,
2705 e->v.Call.starargs,
2706 e->v.Call.kwargs);
2707}
2708
2709/* shared code between compiler_call and compiler_class */
2710static int
2711compiler_call_helper(struct compiler *c,
2712 int n, /* Args already pushed */
2713 asdl_seq *args,
2714 asdl_seq *keywords,
2715 expr_ty starargs,
2716 expr_ty kwargs)
2717{
2718 int code = 0;
2719
2720 n += asdl_seq_LEN(args);
2721 VISIT_SEQ(c, expr, args);
2722 if (keywords) {
2723 VISIT_SEQ(c, keyword, keywords);
2724 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002725 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002726 if (starargs) {
2727 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728 code |= 1;
2729 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002730 if (kwargs) {
2731 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 code |= 2;
2733 }
2734 switch (code) {
2735 case 0:
2736 ADDOP_I(c, CALL_FUNCTION, n);
2737 break;
2738 case 1:
2739 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2740 break;
2741 case 2:
2742 ADDOP_I(c, CALL_FUNCTION_KW, n);
2743 break;
2744 case 3:
2745 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2746 break;
2747 }
2748 return 1;
2749}
2750
Nick Coghlan650f0d02007-04-15 12:05:43 +00002751
2752/* List and set comprehensions and generator expressions work by creating a
2753 nested function to perform the actual iteration. This means that the
2754 iteration variables don't leak into the current scope.
2755 The defined function is called immediately following its definition, with the
2756 result of that call being the result of the expression.
2757 The LC/SC version returns the populated container, while the GE version is
2758 flagged in symtable.c as a generator, so it returns the generator object
2759 when the function is called.
2760 This code *knows* that the loop cannot contain break, continue, or return,
2761 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2762
2763 Possible cleanups:
2764 - iterate over the generator sequence instead of using recursion
2765*/
2766
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002768compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
2769 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002770 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771{
2772 /* generate code for the iterator, then each of the ifs,
2773 and then write to the element */
2774
Nick Coghlan650f0d02007-04-15 12:05:43 +00002775 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002777 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778
2779 start = compiler_new_block(c);
2780 skip = compiler_new_block(c);
2781 if_cleanup = compiler_new_block(c);
2782 anchor = compiler_new_block(c);
2783
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002784 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002785 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787
Nick Coghlan650f0d02007-04-15 12:05:43 +00002788 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002790 if (gen_index == 0) {
2791 /* Receive outermost iter as an implicit argument */
2792 c->u->u_argcount = 1;
2793 ADDOP_I(c, LOAD_FAST, 0);
2794 }
2795 else {
2796 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002797 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798 ADDOP(c, GET_ITER);
2799 }
2800 compiler_use_next_block(c, start);
2801 ADDOP_JREL(c, FOR_ITER, anchor);
2802 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002803 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002805 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002806 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002808 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809 VISIT(c, expr, e);
2810 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2811 NEXT_BLOCK(c);
2812 ADDOP(c, POP_TOP);
2813 }
2814
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 if (++gen_index < asdl_seq_LEN(generators))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002816 if (!compiler_comprehension_generator(c, tmpname,
2817 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002818 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002819 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
Nick Coghlan650f0d02007-04-15 12:05:43 +00002821 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002822 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002823 /* comprehension specific code */
2824 switch (type) {
2825 case COMP_GENEXP:
2826 VISIT(c, expr, elt);
2827 ADDOP(c, YIELD_VALUE);
2828 ADDOP(c, POP_TOP);
2829 break;
2830 case COMP_LISTCOMP:
2831 if (!compiler_nameop(c, tmpname, Load))
2832 return 0;
2833 VISIT(c, expr, elt);
2834 ADDOP(c, LIST_APPEND);
2835 break;
2836 case COMP_SETCOMP:
2837 if (!compiler_nameop(c, tmpname, Load))
2838 return 0;
2839 VISIT(c, expr, elt);
2840 ADDOP(c, SET_ADD);
2841 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002842 case COMP_DICTCOMP:
2843 if (!compiler_nameop(c, tmpname, Load))
2844 return 0;
2845 /* With 'd[k] = v', v is evaluated before k, so we do
2846 the same. STORE_SUBSCR requires (item, map, key),
2847 so we still end up ROTing once. */
2848 VISIT(c, expr, val);
2849 ADDOP(c, ROT_TWO);
2850 VISIT(c, expr, elt);
2851 ADDOP(c, STORE_SUBSCR);
2852 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002853 default:
2854 return 0;
2855 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856
2857 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002858 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859 for (i = 0; i < n; i++) {
2860 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002861 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 ADDOP(c, POP_TOP);
2865 }
2866 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2867 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868
2869 return 1;
2870}
2871
2872static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002873compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002874 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875{
2876 PyCodeObject *co = NULL;
2877 identifier tmp = NULL;
2878 expr_ty outermost_iter;
2879
2880 outermost_iter = ((comprehension_ty)
2881 asdl_seq_GET(generators, 0))->iter;
2882
2883 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2884 goto error;
2885
2886 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002887 int op;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002888 tmp = compiler_new_tmpname(c);
2889 if (!tmp)
2890 goto error_in_scope;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002891 switch (type) {
2892 case COMP_LISTCOMP:
2893 op = BUILD_LIST;
2894 break;
2895 case COMP_SETCOMP:
2896 op = BUILD_SET;
2897 break;
2898 case COMP_DICTCOMP:
2899 op = BUILD_MAP;
2900 break;
2901 default:
2902 PyErr_Format(PyExc_SystemError,
2903 "unknown comprehension type %d", type);
2904 goto error_in_scope;
2905 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002906
Guido van Rossum992d4a32007-07-11 13:09:30 +00002907 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002908 ADDOP(c, DUP_TOP);
2909 if (!compiler_nameop(c, tmp, Store))
2910 goto error_in_scope;
2911 }
2912
Guido van Rossum992d4a32007-07-11 13:09:30 +00002913 if (!compiler_comprehension_generator(c, tmp, generators, 0, elt,
2914 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002915 goto error_in_scope;
2916
2917 if (type != COMP_GENEXP) {
2918 ADDOP(c, RETURN_VALUE);
2919 }
2920
2921 co = assemble(c, 1);
2922 compiler_exit_scope(c);
2923 if (co == NULL)
2924 goto error;
2925
2926 if (!compiler_make_closure(c, co, 0))
2927 goto error;
2928 Py_DECREF(co);
2929 Py_XDECREF(tmp);
2930
2931 VISIT(c, expr, outermost_iter);
2932 ADDOP(c, GET_ITER);
2933 ADDOP_I(c, CALL_FUNCTION, 1);
2934 return 1;
2935error_in_scope:
2936 compiler_exit_scope(c);
2937error:
2938 Py_XDECREF(co);
2939 Py_XDECREF(tmp);
2940 return 0;
2941}
2942
2943static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944compiler_genexp(struct compiler *c, expr_ty e)
2945{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002946 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002947 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002948 name = PyUnicode_FromString("<genexp>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002949 if (!name)
2950 return 0;
2951 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002952 assert(e->kind == GeneratorExp_kind);
2953 return compiler_comprehension(c, e, COMP_GENEXP, name,
2954 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002955 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956}
2957
2958static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002959compiler_listcomp(struct compiler *c, expr_ty e)
2960{
2961 static identifier name;
2962 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002963 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002964 if (!name)
2965 return 0;
2966 }
2967 assert(e->kind == ListComp_kind);
2968 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2969 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002970 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002971}
2972
2973static int
2974compiler_setcomp(struct compiler *c, expr_ty e)
2975{
2976 static identifier name;
2977 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002978 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002979 if (!name)
2980 return 0;
2981 }
2982 assert(e->kind == SetComp_kind);
2983 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2984 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002985 e->v.SetComp.elt, NULL);
2986}
2987
2988
2989static int
2990compiler_dictcomp(struct compiler *c, expr_ty e)
2991{
2992 static identifier name;
2993 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00002994 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00002995 if (!name)
2996 return 0;
2997 }
2998 assert(e->kind == DictComp_kind);
2999 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3000 e->v.DictComp.generators,
3001 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003002}
3003
3004
3005static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006compiler_visit_keyword(struct compiler *c, keyword_ty k)
3007{
3008 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3009 VISIT(c, expr, k->value);
3010 return 1;
3011}
3012
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003013/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 whether they are true or false.
3015
3016 Return values: 1 for true, 0 for false, -1 for non-constant.
3017 */
3018
3019static int
3020expr_constant(expr_ty e)
3021{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003022 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003024 case Ellipsis_kind:
3025 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003026 case Num_kind:
3027 return PyObject_IsTrue(e->v.Num.n);
3028 case Str_kind:
3029 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003030 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003031 /* optimize away names that can't be reassigned */
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003032 id = PyString_AS_STRING(
3033 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003034 if (strcmp(id, "True") == 0) return 1;
3035 if (strcmp(id, "False") == 0) return 0;
3036 if (strcmp(id, "None") == 0) return 0;
3037 if (strcmp(id, "__debug__") == 0)
3038 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003039 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 default:
3041 return -1;
3042 }
3043}
3044
Guido van Rossumc2e20742006-02-27 22:32:47 +00003045/*
3046 Implements the with statement from PEP 343.
3047
3048 The semantics outlined in that PEP are as follows:
3049
3050 with EXPR as VAR:
3051 BLOCK
3052
3053 It is implemented roughly as:
3054
Thomas Wouters477c8d52006-05-27 19:21:47 +00003055 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003056 exit = context.__exit__ # not calling it
3057 value = context.__enter__()
3058 try:
3059 VAR = value # if VAR present in the syntax
3060 BLOCK
3061 finally:
3062 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003063 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003064 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003065 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003066 exit(*exc)
3067 */
3068static int
3069compiler_with(struct compiler *c, stmt_ty s)
3070{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003071 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003072 basicblock *block, *finally;
3073 identifier tmpexit, tmpvalue = NULL;
3074
3075 assert(s->kind == With_kind);
3076
Guido van Rossumc2e20742006-02-27 22:32:47 +00003077 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003078 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003079 if (!enter_attr)
3080 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 }
3082 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003083 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003084 if (!exit_attr)
3085 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003086 }
3087
3088 block = compiler_new_block(c);
3089 finally = compiler_new_block(c);
3090 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003091 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003092
3093 /* Create a temporary variable to hold context.__exit__ */
3094 tmpexit = compiler_new_tmpname(c);
3095 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003096 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003097 PyArena_AddPyObject(c->c_arena, tmpexit);
3098
3099 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003100 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003101 We need to do this rather than preserving it on the stack
3102 because SETUP_FINALLY remembers the stack level.
3103 We need to do the assignment *inside* the try/finally
3104 so that context.__exit__() is called when the assignment
3105 fails. But we need to call context.__enter__() *before*
3106 the try/finally so that if it fails we won't call
3107 context.__exit__().
3108 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003109 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003110 if (tmpvalue == NULL)
3111 return 0;
3112 PyArena_AddPyObject(c->c_arena, tmpvalue);
3113 }
3114
Thomas Wouters477c8d52006-05-27 19:21:47 +00003115 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003116 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003117
3118 /* Squirrel away context.__exit__ */
3119 ADDOP(c, DUP_TOP);
3120 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3121 if (!compiler_nameop(c, tmpexit, Store))
3122 return 0;
3123
3124 /* Call context.__enter__() */
3125 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3126 ADDOP_I(c, CALL_FUNCTION, 0);
3127
3128 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003129 /* Store it in tmpvalue */
3130 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003131 return 0;
3132 }
3133 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 /* Discard result from context.__enter__() */
3135 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003136 }
3137
3138 /* Start the try block */
3139 ADDOP_JREL(c, SETUP_FINALLY, finally);
3140
3141 compiler_use_next_block(c, block);
3142 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003143 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003144 }
3145
3146 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 /* Bind saved result of context.__enter__() to VAR */
3148 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003149 !compiler_nameop(c, tmpvalue, Del))
3150 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003151 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003152 }
3153
3154 /* BLOCK code */
3155 VISIT_SEQ(c, stmt, s->v.With.body);
3156
3157 /* End of try block; start the finally block */
3158 ADDOP(c, POP_BLOCK);
3159 compiler_pop_fblock(c, FINALLY_TRY, block);
3160
3161 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3162 compiler_use_next_block(c, finally);
3163 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003165
3166 /* Finally block starts; push tmpexit and issue our magic opcode. */
3167 if (!compiler_nameop(c, tmpexit, Load) ||
3168 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003170 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003171
3172 /* Finally block ends. */
3173 ADDOP(c, END_FINALLY);
3174 compiler_pop_fblock(c, FINALLY_END, finally);
3175 return 1;
3176}
3177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178static int
3179compiler_visit_expr(struct compiler *c, expr_ty e)
3180{
3181 int i, n;
3182
Thomas Wouters89f507f2006-12-13 04:49:30 +00003183 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003184 set a new line number for the next instruction.
3185 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186 if (e->lineno > c->u->u_lineno) {
3187 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003188 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189 }
3190 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003191 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 VISIT(c, expr, e->v.BinOp.left);
3195 VISIT(c, expr, e->v.BinOp.right);
3196 ADDOP(c, binop(c, e->v.BinOp.op));
3197 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 VISIT(c, expr, e->v.UnaryOp.operand);
3200 ADDOP(c, unaryop(e->v.UnaryOp.op));
3201 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003202 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003204 case IfExp_kind:
3205 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003206 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207 /* XXX get rid of arg? */
3208 ADDOP_I(c, BUILD_MAP, 0);
3209 n = asdl_seq_LEN(e->v.Dict.values);
3210 /* We must arrange things just right for STORE_SUBSCR.
3211 It wants the stack to look like (value) (dict) (key) */
3212 for (i = 0; i < n; i++) {
3213 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003214 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003215 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003217 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003218 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 ADDOP(c, STORE_SUBSCR);
3220 }
3221 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003222 case Set_kind:
3223 n = asdl_seq_LEN(e->v.Set.elts);
3224 VISIT_SEQ(c, expr, e->v.Set.elts);
3225 ADDOP_I(c, BUILD_SET, n);
3226 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003227 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003229 case ListComp_kind:
3230 return compiler_listcomp(c, e);
3231 case SetComp_kind:
3232 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003233 case DictComp_kind:
3234 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235 case Yield_kind:
3236 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003237 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 if (e->v.Yield.value) {
3239 VISIT(c, expr, e->v.Yield.value);
3240 }
3241 else {
3242 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3243 }
3244 ADDOP(c, YIELD_VALUE);
3245 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003246 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003247 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003248 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003250 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3252 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003253 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3255 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003256 case Bytes_kind:
3257 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3258 ADDOP(c, MAKE_BYTES);
3259 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003260 case Ellipsis_kind:
3261 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3262 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003264 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265 if (e->v.Attribute.ctx != AugStore)
3266 VISIT(c, expr, e->v.Attribute.value);
3267 switch (e->v.Attribute.ctx) {
3268 case AugLoad:
3269 ADDOP(c, DUP_TOP);
3270 /* Fall through to load */
3271 case Load:
3272 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3273 break;
3274 case AugStore:
3275 ADDOP(c, ROT_TWO);
3276 /* Fall through to save */
3277 case Store:
3278 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3279 break;
3280 case Del:
3281 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3282 break;
3283 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003284 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003285 PyErr_SetString(PyExc_SystemError,
3286 "param invalid in attribute expression");
3287 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288 }
3289 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003290 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003291 switch (e->v.Subscript.ctx) {
3292 case AugLoad:
3293 VISIT(c, expr, e->v.Subscript.value);
3294 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3295 break;
3296 case Load:
3297 VISIT(c, expr, e->v.Subscript.value);
3298 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3299 break;
3300 case AugStore:
3301 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3302 break;
3303 case Store:
3304 VISIT(c, expr, e->v.Subscript.value);
3305 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3306 break;
3307 case Del:
3308 VISIT(c, expr, e->v.Subscript.value);
3309 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3310 break;
3311 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003312 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003313 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003314 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003315 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 }
3317 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003318 case Starred_kind:
3319 switch (e->v.Starred.ctx) {
3320 case Store:
3321 /* In all legitimate cases, the Starred node was already replaced
3322 * by compiler_list/compiler_tuple. XXX: is that okay? */
3323 return compiler_error(c,
3324 "starred assignment target must be in a list or tuple");
3325 default:
3326 return compiler_error(c,
3327 "can use starred expression only as assignment target");
3328 }
3329 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003330 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003331 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3332 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003333 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003334 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003335 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336 return compiler_tuple(c, e);
3337 }
3338 return 1;
3339}
3340
3341static int
3342compiler_augassign(struct compiler *c, stmt_ty s)
3343{
3344 expr_ty e = s->v.AugAssign.target;
3345 expr_ty auge;
3346
3347 assert(s->kind == AugAssign_kind);
3348
3349 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003350 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003351 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003352 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003353 if (auge == NULL)
3354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355 VISIT(c, expr, auge);
3356 VISIT(c, expr, s->v.AugAssign.value);
3357 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3358 auge->v.Attribute.ctx = AugStore;
3359 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360 break;
3361 case Subscript_kind:
3362 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003363 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003364 if (auge == NULL)
3365 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366 VISIT(c, expr, auge);
3367 VISIT(c, expr, s->v.AugAssign.value);
3368 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003369 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003370 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003371 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003372 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003373 if (!compiler_nameop(c, e->v.Name.id, Load))
3374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375 VISIT(c, expr, s->v.AugAssign.value);
3376 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3377 return compiler_nameop(c, e->v.Name.id, Store);
3378 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003379 PyErr_Format(PyExc_SystemError,
3380 "invalid node type (%d) for augmented assignment",
3381 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003382 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003383 }
3384 return 1;
3385}
3386
3387static int
3388compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3389{
3390 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003391 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3392 PyErr_SetString(PyExc_SystemError,
3393 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396 f = &c->u->u_fblock[c->u->u_nfblocks++];
3397 f->fb_type = t;
3398 f->fb_block = b;
3399 return 1;
3400}
3401
3402static void
3403compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3404{
3405 struct compiler_unit *u = c->u;
3406 assert(u->u_nfblocks > 0);
3407 u->u_nfblocks--;
3408 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3409 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3410}
3411
Thomas Wouters89f507f2006-12-13 04:49:30 +00003412static int
3413compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003414 int i;
3415 struct compiler_unit *u = c->u;
3416 for (i = 0; i < u->u_nfblocks; ++i) {
3417 if (u->u_fblock[i].fb_type == LOOP)
3418 return 1;
3419 }
3420 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003421}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422/* Raises a SyntaxError and returns 0.
3423 If something goes wrong, a different exception may be raised.
3424*/
3425
3426static int
3427compiler_error(struct compiler *c, const char *errstr)
3428{
3429 PyObject *loc;
3430 PyObject *u = NULL, *v = NULL;
3431
3432 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3433 if (!loc) {
3434 Py_INCREF(Py_None);
3435 loc = Py_None;
3436 }
3437 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3438 Py_None, loc);
3439 if (!u)
3440 goto exit;
3441 v = Py_BuildValue("(zO)", errstr, u);
3442 if (!v)
3443 goto exit;
3444 PyErr_SetObject(PyExc_SyntaxError, v);
3445 exit:
3446 Py_DECREF(loc);
3447 Py_XDECREF(u);
3448 Py_XDECREF(v);
3449 return 0;
3450}
3451
3452static int
3453compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003454 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003456 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003458 /* XXX this code is duplicated */
3459 switch (ctx) {
3460 case AugLoad: /* fall through to Load */
3461 case Load: op = BINARY_SUBSCR; break;
3462 case AugStore:/* fall through to Store */
3463 case Store: op = STORE_SUBSCR; break;
3464 case Del: op = DELETE_SUBSCR; break;
3465 case Param:
3466 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003467 "invalid %s kind %d in subscript\n",
3468 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003469 return 0;
3470 }
3471 if (ctx == AugLoad) {
3472 ADDOP_I(c, DUP_TOPX, 2);
3473 }
3474 else if (ctx == AugStore) {
3475 ADDOP(c, ROT_THREE);
3476 }
3477 ADDOP(c, op);
3478 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479}
3480
3481static int
3482compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3483{
3484 int n = 2;
3485 assert(s->kind == Slice_kind);
3486
3487 /* only handles the cases where BUILD_SLICE is emitted */
3488 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003489 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003490 }
3491 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003492 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003494
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003496 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497 }
3498 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003499 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500 }
3501
3502 if (s->v.Slice.step) {
3503 n++;
3504 VISIT(c, expr, s->v.Slice.step);
3505 }
3506 ADDOP_I(c, BUILD_SLICE, n);
3507 return 1;
3508}
3509
3510static int
3511compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3512{
3513 int op = 0, slice_offset = 0, stack_count = 0;
3514
3515 assert(s->v.Slice.step == NULL);
3516 if (s->v.Slice.lower) {
3517 slice_offset++;
3518 stack_count++;
3519 if (ctx != AugStore)
3520 VISIT(c, expr, s->v.Slice.lower);
3521 }
3522 if (s->v.Slice.upper) {
3523 slice_offset += 2;
3524 stack_count++;
3525 if (ctx != AugStore)
3526 VISIT(c, expr, s->v.Slice.upper);
3527 }
3528
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003529 if (ctx == AugLoad) {
3530 switch (stack_count) {
3531 case 0: ADDOP(c, DUP_TOP); break;
3532 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3533 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3534 }
3535 }
3536 else if (ctx == AugStore) {
3537 switch (stack_count) {
3538 case 0: ADDOP(c, ROT_TWO); break;
3539 case 1: ADDOP(c, ROT_THREE); break;
3540 case 2: ADDOP(c, ROT_FOUR); break;
3541 }
3542 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543
3544 switch (ctx) {
3545 case AugLoad: /* fall through to Load */
3546 case Load: op = SLICE; break;
3547 case AugStore:/* fall through to Store */
3548 case Store: op = STORE_SLICE; break;
3549 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003550 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003551 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003552 PyErr_SetString(PyExc_SystemError,
3553 "param invalid in simple slice");
3554 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 }
3556
3557 ADDOP(c, op + slice_offset);
3558 return 1;
3559}
3560
3561static int
3562compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3563 expr_context_ty ctx)
3564{
3565 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 case Slice_kind:
3567 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 case Index_kind:
3569 VISIT(c, expr, s->v.Index.value);
3570 break;
3571 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003572 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003573 PyErr_SetString(PyExc_SystemError,
3574 "extended slice invalid in nested slice");
3575 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576 }
3577 return 1;
3578}
3579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580static int
3581compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3582{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003583 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003585 case Index_kind:
3586 kindname = "index";
3587 if (ctx != AugStore) {
3588 VISIT(c, expr, s->v.Index.value);
3589 }
3590 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003592 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 if (!s->v.Slice.step)
3594 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003595 if (ctx != AugStore) {
3596 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 return 0;
3598 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003599 break;
3600 case ExtSlice_kind:
3601 kindname = "extended slice";
3602 if (ctx != AugStore) {
3603 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3604 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003605 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003606 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003607 if (!compiler_visit_nested_slice(c, sub, ctx))
3608 return 0;
3609 }
3610 ADDOP_I(c, BUILD_TUPLE, n);
3611 }
3612 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003613 default:
3614 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003615 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003616 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003618 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619}
3620
Thomas Wouters89f507f2006-12-13 04:49:30 +00003621/* End of the compiler section, beginning of the assembler section */
3622
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623/* do depth-first search of basic block graph, starting with block.
3624 post records the block indices in post-order.
3625
3626 XXX must handle implicit jumps from one block to next
3627*/
3628
Thomas Wouters89f507f2006-12-13 04:49:30 +00003629struct assembler {
3630 PyObject *a_bytecode; /* string containing bytecode */
3631 int a_offset; /* offset into bytecode */
3632 int a_nblocks; /* number of reachable blocks */
3633 basicblock **a_postorder; /* list of blocks in dfs postorder */
3634 PyObject *a_lnotab; /* string containing lnotab */
3635 int a_lnotab_off; /* offset into lnotab */
3636 int a_lineno; /* last lineno of emitted instruction */
3637 int a_lineno_off; /* bytecode offset of last lineno */
3638};
3639
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640static void
3641dfs(struct compiler *c, basicblock *b, struct assembler *a)
3642{
3643 int i;
3644 struct instr *instr = NULL;
3645
3646 if (b->b_seen)
3647 return;
3648 b->b_seen = 1;
3649 if (b->b_next != NULL)
3650 dfs(c, b->b_next, a);
3651 for (i = 0; i < b->b_iused; i++) {
3652 instr = &b->b_instr[i];
3653 if (instr->i_jrel || instr->i_jabs)
3654 dfs(c, instr->i_target, a);
3655 }
3656 a->a_postorder[a->a_nblocks++] = b;
3657}
3658
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003659static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3661{
3662 int i;
3663 struct instr *instr;
3664 if (b->b_seen || b->b_startdepth >= depth)
3665 return maxdepth;
3666 b->b_seen = 1;
3667 b->b_startdepth = depth;
3668 for (i = 0; i < b->b_iused; i++) {
3669 instr = &b->b_instr[i];
3670 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3671 if (depth > maxdepth)
3672 maxdepth = depth;
3673 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3674 if (instr->i_jrel || instr->i_jabs) {
3675 maxdepth = stackdepth_walk(c, instr->i_target,
3676 depth, maxdepth);
3677 if (instr->i_opcode == JUMP_ABSOLUTE ||
3678 instr->i_opcode == JUMP_FORWARD) {
3679 goto out; /* remaining code is dead */
3680 }
3681 }
3682 }
3683 if (b->b_next)
3684 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3685out:
3686 b->b_seen = 0;
3687 return maxdepth;
3688}
3689
3690/* Find the flow path that needs the largest stack. We assume that
3691 * cycles in the flow graph have no net effect on the stack depth.
3692 */
3693static int
3694stackdepth(struct compiler *c)
3695{
3696 basicblock *b, *entryblock;
3697 entryblock = NULL;
3698 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3699 b->b_seen = 0;
3700 b->b_startdepth = INT_MIN;
3701 entryblock = b;
3702 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003703 if (!entryblock)
3704 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003705 return stackdepth_walk(c, entryblock, 0, 0);
3706}
3707
3708static int
3709assemble_init(struct assembler *a, int nblocks, int firstlineno)
3710{
3711 memset(a, 0, sizeof(struct assembler));
3712 a->a_lineno = firstlineno;
3713 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3714 if (!a->a_bytecode)
3715 return 0;
3716 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3717 if (!a->a_lnotab)
3718 return 0;
3719 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003720 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003721 if (!a->a_postorder) {
3722 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003724 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725 return 1;
3726}
3727
3728static void
3729assemble_free(struct assembler *a)
3730{
3731 Py_XDECREF(a->a_bytecode);
3732 Py_XDECREF(a->a_lnotab);
3733 if (a->a_postorder)
3734 PyObject_Free(a->a_postorder);
3735}
3736
3737/* Return the size of a basic block in bytes. */
3738
3739static int
3740instrsize(struct instr *instr)
3741{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003742 if (!instr->i_hasarg)
3743 return 1;
3744 if (instr->i_oparg > 0xffff)
3745 return 6;
3746 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747}
3748
3749static int
3750blocksize(basicblock *b)
3751{
3752 int i;
3753 int size = 0;
3754
3755 for (i = 0; i < b->b_iused; i++)
3756 size += instrsize(&b->b_instr[i]);
3757 return size;
3758}
3759
3760/* All about a_lnotab.
3761
3762c_lnotab is an array of unsigned bytes disguised as a Python string.
3763It is used to map bytecode offsets to source code line #s (when needed
3764for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003765
Tim Peters2a7f3842001-06-09 09:26:21 +00003766The array is conceptually a list of
3767 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003768pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003769
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003770 byte code offset source code line number
3771 0 1
3772 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003773 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003774 350 307
3775 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003776
3777The first trick is that these numbers aren't stored, only the increments
3778from one row to the next (this doesn't really work, but it's a start):
3779
3780 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3781
3782The second trick is that an unsigned byte can't hold negative values, or
3783values larger than 255, so (a) there's a deep assumption that byte code
3784offsets and their corresponding line #s both increase monotonically, and (b)
3785if at least one column jumps by more than 255 from one row to the next, more
3786than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003787from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003788part. A user of c_lnotab desiring to find the source line number
3789corresponding to a bytecode address A should do something like this
3790
3791 lineno = addr = 0
3792 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003793 addr += addr_incr
3794 if addr > A:
3795 return lineno
3796 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003797
3798In order for this to work, when the addr field increments by more than 255,
3799the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003800increment is < 256. So, in the example above, assemble_lnotab (it used
3801to be called com_set_lineno) should not (as was actually done until 2.2)
3802expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003803 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003804*/
3805
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003806static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003808{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809 int d_bytecode, d_lineno;
3810 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003811 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812
3813 d_bytecode = a->a_offset - a->a_lineno_off;
3814 d_lineno = i->i_lineno - a->a_lineno;
3815
3816 assert(d_bytecode >= 0);
3817 assert(d_lineno >= 0);
3818
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003819 /* XXX(nnorwitz): is there a better way to handle this?
3820 for loops are special, we want to be able to trace them
3821 each time around, so we need to set an extra line number. */
3822 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003823 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003824
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003826 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 nbytes = a->a_lnotab_off + 2 * ncodes;
3828 len = PyString_GET_SIZE(a->a_lnotab);
3829 if (nbytes >= len) {
3830 if (len * 2 < nbytes)
3831 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003832 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833 len *= 2;
3834 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3835 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003836 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003837 lnotab = (unsigned char *)
3838 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003839 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840 *lnotab++ = 255;
3841 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003842 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 d_bytecode -= ncodes * 255;
3844 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846 assert(d_bytecode <= 255);
3847 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003848 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849 nbytes = a->a_lnotab_off + 2 * ncodes;
3850 len = PyString_GET_SIZE(a->a_lnotab);
3851 if (nbytes >= len) {
3852 if (len * 2 < nbytes)
3853 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003854 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855 len *= 2;
3856 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3857 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003858 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003859 lnotab = (unsigned char *)
3860 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003862 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003864 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003866 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003867 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868 d_lineno -= ncodes * 255;
3869 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003870 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003871
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872 len = PyString_GET_SIZE(a->a_lnotab);
3873 if (a->a_lnotab_off + 2 >= len) {
3874 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003875 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003876 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003877 lnotab = (unsigned char *)
3878 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880 a->a_lnotab_off += 2;
3881 if (d_bytecode) {
3882 *lnotab++ = d_bytecode;
3883 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003884 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003885 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886 *lnotab++ = 0;
3887 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003888 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889 a->a_lineno = i->i_lineno;
3890 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003891 return 1;
3892}
3893
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894/* assemble_emit()
3895 Extend the bytecode with a new instruction.
3896 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003897*/
3898
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003899static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003901{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003902 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003903 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 char *code;
3905
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003906 size = instrsize(i);
3907 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003909 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003910 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003912 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913 if (a->a_offset + size >= len) {
3914 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003915 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003916 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003917 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3918 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003919 if (size == 6) {
3920 assert(i->i_hasarg);
3921 *code++ = (char)EXTENDED_ARG;
3922 *code++ = ext & 0xff;
3923 *code++ = ext >> 8;
3924 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003925 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003926 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003927 if (i->i_hasarg) {
3928 assert(size == 3 || size == 6);
3929 *code++ = arg & 0xff;
3930 *code++ = arg >> 8;
3931 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003933}
3934
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003935static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003937{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003939 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003940 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003941
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942 /* Compute the size of each block and fixup jump args.
3943 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003944start:
3945 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003947 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003948 bsize = blocksize(b);
3949 b->b_offset = totsize;
3950 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003951 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003952 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003953 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3954 bsize = b->b_offset;
3955 for (i = 0; i < b->b_iused; i++) {
3956 struct instr *instr = &b->b_instr[i];
3957 /* Relative jumps are computed relative to
3958 the instruction pointer after fetching
3959 the jump instruction.
3960 */
3961 bsize += instrsize(instr);
3962 if (instr->i_jabs)
3963 instr->i_oparg = instr->i_target->b_offset;
3964 else if (instr->i_jrel) {
3965 int delta = instr->i_target->b_offset - bsize;
3966 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003967 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003968 else
3969 continue;
3970 if (instr->i_oparg > 0xffff)
3971 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003972 }
3973 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003974
3975 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003976 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003977 with a better solution.
3978
3979 In the meantime, should the goto be dropped in favor
3980 of a loop?
3981
3982 The issue is that in the first loop blocksize() is called
3983 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003984 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003985 i_oparg is calculated in the second loop above.
3986
3987 So we loop until we stop seeing new EXTENDED_ARGs.
3988 The only EXTENDED_ARGs that could be popping up are
3989 ones in jump instructions. So this should converge
3990 fairly quickly.
3991 */
3992 if (last_extended_arg_count != extended_arg_count) {
3993 last_extended_arg_count = extended_arg_count;
3994 goto start;
3995 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003996}
3997
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003998static PyObject *
3999dict_keys_inorder(PyObject *dict, int offset)
4000{
4001 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004002 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004003
4004 tuple = PyTuple_New(size);
4005 if (tuple == NULL)
4006 return NULL;
4007 while (PyDict_Next(dict, &pos, &k, &v)) {
4008 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004009 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004010 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004011 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004012 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004013 PyTuple_SET_ITEM(tuple, i - offset, k);
4014 }
4015 return tuple;
4016}
4017
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004018static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004019compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004020{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004021 PySTEntryObject *ste = c->u->u_ste;
4022 int flags = 0, n;
4023 if (ste->ste_type != ModuleBlock)
4024 flags |= CO_NEWLOCALS;
4025 if (ste->ste_type == FunctionBlock) {
4026 if (!ste->ste_unoptimized)
4027 flags |= CO_OPTIMIZED;
4028 if (ste->ste_nested)
4029 flags |= CO_NESTED;
4030 if (ste->ste_generator)
4031 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004032 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004033 if (ste->ste_varargs)
4034 flags |= CO_VARARGS;
4035 if (ste->ste_varkeywords)
4036 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004037 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004038 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004039
4040 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004041 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004043 n = PyDict_Size(c->u->u_freevars);
4044 if (n < 0)
4045 return -1;
4046 if (n == 0) {
4047 n = PyDict_Size(c->u->u_cellvars);
4048 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004049 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004050 if (n == 0) {
4051 flags |= CO_NOFREE;
4052 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004053 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004054
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004055 return flags;
4056}
4057
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004058static PyCodeObject *
4059makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004060{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061 PyObject *tmp;
4062 PyCodeObject *co = NULL;
4063 PyObject *consts = NULL;
4064 PyObject *names = NULL;
4065 PyObject *varnames = NULL;
4066 PyObject *filename = NULL;
4067 PyObject *name = NULL;
4068 PyObject *freevars = NULL;
4069 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004070 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004071 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004072
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073 tmp = dict_keys_inorder(c->u->u_consts, 0);
4074 if (!tmp)
4075 goto error;
4076 consts = PySequence_List(tmp); /* optimize_code requires a list */
4077 Py_DECREF(tmp);
4078
4079 names = dict_keys_inorder(c->u->u_names, 0);
4080 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4081 if (!consts || !names || !varnames)
4082 goto error;
4083
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004084 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4085 if (!cellvars)
4086 goto error;
4087 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4088 if (!freevars)
4089 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090 filename = PyString_FromString(c->c_filename);
4091 if (!filename)
4092 goto error;
4093
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004094 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004095 flags = compute_code_flags(c);
4096 if (flags < 0)
4097 goto error;
4098
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004099 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100 if (!bytecode)
4101 goto error;
4102
4103 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4104 if (!tmp)
4105 goto error;
4106 Py_DECREF(consts);
4107 consts = tmp;
4108
Guido van Rossum4f72a782006-10-27 23:31:49 +00004109 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4110 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111 bytecode, consts, names, varnames,
4112 freevars, cellvars,
4113 filename, c->u->u_name,
4114 c->u->u_firstlineno,
4115 a->a_lnotab);
4116 error:
4117 Py_XDECREF(consts);
4118 Py_XDECREF(names);
4119 Py_XDECREF(varnames);
4120 Py_XDECREF(filename);
4121 Py_XDECREF(name);
4122 Py_XDECREF(freevars);
4123 Py_XDECREF(cellvars);
4124 Py_XDECREF(bytecode);
4125 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004126}
4127
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004128
4129/* For debugging purposes only */
4130#if 0
4131static void
4132dump_instr(const struct instr *i)
4133{
4134 const char *jrel = i->i_jrel ? "jrel " : "";
4135 const char *jabs = i->i_jabs ? "jabs " : "";
4136 char arg[128];
4137
4138 *arg = '\0';
4139 if (i->i_hasarg)
4140 sprintf(arg, "arg: %d ", i->i_oparg);
4141
4142 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4143 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4144}
4145
4146static void
4147dump_basicblock(const basicblock *b)
4148{
4149 const char *seen = b->b_seen ? "seen " : "";
4150 const char *b_return = b->b_return ? "return " : "";
4151 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4152 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4153 if (b->b_instr) {
4154 int i;
4155 for (i = 0; i < b->b_iused; i++) {
4156 fprintf(stderr, " [%02d] ", i);
4157 dump_instr(b->b_instr + i);
4158 }
4159 }
4160}
4161#endif
4162
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004163static PyCodeObject *
4164assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004165{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166 basicblock *b, *entryblock;
4167 struct assembler a;
4168 int i, j, nblocks;
4169 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004170
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004171 /* Make sure every block that falls off the end returns None.
4172 XXX NEXT_BLOCK() isn't quite right, because if the last
4173 block ends with a jump or return b_next shouldn't set.
4174 */
4175 if (!c->u->u_curblock->b_return) {
4176 NEXT_BLOCK(c);
4177 if (addNone)
4178 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4179 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004180 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004181
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004182 nblocks = 0;
4183 entryblock = NULL;
4184 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4185 nblocks++;
4186 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004187 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004188
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004189 /* Set firstlineno if it wasn't explicitly set. */
4190 if (!c->u->u_firstlineno) {
4191 if (entryblock && entryblock->b_instr)
4192 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4193 else
4194 c->u->u_firstlineno = 1;
4195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004196 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4197 goto error;
4198 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004201 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004202
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004203 /* Emit code in reverse postorder from dfs. */
4204 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004205 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206 for (j = 0; j < b->b_iused; j++)
4207 if (!assemble_emit(&a, &b->b_instr[j]))
4208 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004209 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4212 goto error;
4213 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4214 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004215
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004216 co = makecode(c, &a);
4217 error:
4218 assemble_free(&a);
4219 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004220}