blob: b256198546389ae20f794c9de2f670976aeb96e6 [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++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000338 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339 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;
Christian Heimes217cfd12007-12-02 14:31:20 +0000378 assert(PyLong_Check(v));
379 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000380 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) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000383 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000710 case INPLACE_ADD:
711 case INPLACE_SUBTRACT:
712 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000713 case INPLACE_MODULO:
714 return -1;
715 case STORE_SUBSCR:
716 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000717 case STORE_MAP:
718 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000719 case DELETE_SUBSCR:
720 return -2;
721
722 case BINARY_LSHIFT:
723 case BINARY_RSHIFT:
724 case BINARY_AND:
725 case BINARY_XOR:
726 case BINARY_OR:
727 return -1;
728 case INPLACE_POWER:
729 return -1;
730 case GET_ITER:
731 return 0;
732
733 case PRINT_EXPR:
734 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000735 case LOAD_BUILD_CLASS:
736 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737 case INPLACE_LSHIFT:
738 case INPLACE_RSHIFT:
739 case INPLACE_AND:
740 case INPLACE_XOR:
741 case INPLACE_OR:
742 return -1;
743 case BREAK_LOOP:
744 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000745 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000746 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000747 case STORE_LOCALS:
748 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749 case RETURN_VALUE:
750 return -1;
751 case IMPORT_STAR:
752 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753 case YIELD_VALUE:
754 return 0;
755
756 case POP_BLOCK:
757 return 0;
758 case END_FINALLY:
759 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760
761 case STORE_NAME:
762 return -1;
763 case DELETE_NAME:
764 return 0;
765 case UNPACK_SEQUENCE:
766 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000767 case UNPACK_EX:
768 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769 case FOR_ITER:
770 return 1;
771
772 case STORE_ATTR:
773 return -2;
774 case DELETE_ATTR:
775 return -1;
776 case STORE_GLOBAL:
777 return -1;
778 case DELETE_GLOBAL:
779 return 0;
780 case DUP_TOPX:
781 return oparg;
782 case LOAD_CONST:
783 return 1;
784 case LOAD_NAME:
785 return 1;
786 case BUILD_TUPLE:
787 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000788 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789 return 1-oparg;
790 case BUILD_MAP:
791 return 1;
792 case LOAD_ATTR:
793 return 0;
794 case COMPARE_OP:
795 return -1;
796 case IMPORT_NAME:
797 return 0;
798 case IMPORT_FROM:
799 return 1;
800
801 case JUMP_FORWARD:
802 case JUMP_IF_FALSE:
803 case JUMP_IF_TRUE:
804 case JUMP_ABSOLUTE:
805 return 0;
806
807 case LOAD_GLOBAL:
808 return 1;
809
810 case CONTINUE_LOOP:
811 return 0;
812 case SETUP_LOOP:
813 return 0;
814 case SETUP_EXCEPT:
815 case SETUP_FINALLY:
816 return 3; /* actually pushed by an exception */
817
818 case LOAD_FAST:
819 return 1;
820 case STORE_FAST:
821 return -1;
822 case DELETE_FAST:
823 return 0;
824
825 case RAISE_VARARGS:
826 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000827#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000828 case CALL_FUNCTION:
829 return -NARGS(oparg);
830 case CALL_FUNCTION_VAR:
831 case CALL_FUNCTION_KW:
832 return -NARGS(oparg)-1;
833 case CALL_FUNCTION_VAR_KW:
834 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000836 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000837 case MAKE_CLOSURE:
838 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000839#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000840 case BUILD_SLICE:
841 if (oparg == 3)
842 return -2;
843 else
844 return -1;
845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000846 case LOAD_CLOSURE:
847 return 1;
848 case LOAD_DEREF:
849 return 1;
850 case STORE_DEREF:
851 return -1;
852 default:
853 fprintf(stderr, "opcode = %d\n", opcode);
854 Py_FatalError("opcode_stack_effect()");
855
856 }
857 return 0; /* not reachable */
858}
859
860/* Add an opcode with no argument.
861 Returns 0 on failure, 1 on success.
862*/
863
864static int
865compiler_addop(struct compiler *c, int opcode)
866{
867 basicblock *b;
868 struct instr *i;
869 int off;
870 off = compiler_next_instr(c, c->u->u_curblock);
871 if (off < 0)
872 return 0;
873 b = c->u->u_curblock;
874 i = &b->b_instr[off];
875 i->i_opcode = opcode;
876 i->i_hasarg = 0;
877 if (opcode == RETURN_VALUE)
878 b->b_return = 1;
879 compiler_set_lineno(c, off);
880 return 1;
881}
882
883static int
884compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
885{
886 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000887 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000888 unsigned char *p, *q;
889 Py_complex z;
890 double d;
891 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000892
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000893 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000894 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
895 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000896 d = PyFloat_AS_DOUBLE(o);
897 p = (unsigned char*) &d;
898 /* all we need is to make the tuple different in either the 0.0
899 * or -0.0 case from all others, just to avoid the "coercion".
900 */
901 if (*p==0 && p[sizeof(double)-1]==0)
902 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
903 else
904 t = PyTuple_Pack(2, o, o->ob_type);
905 }
906 else if (PyComplex_Check(o)) {
907 /* complex case is even messier: we need to make complex(x,
908 0.) different from complex(x, -0.) and complex(0., y)
909 different from complex(-0., y), for any x and y. In
910 particular, all four complex zeros should be
911 distinguished.*/
912 z = PyComplex_AsCComplex(o);
913 p = (unsigned char*) &(z.real);
914 q = (unsigned char*) &(z.imag);
915 /* all that matters here is that on IEEE platforms
916 real_part_zero will be true if z.real == 0., and false if
917 z.real == -0. In fact, real_part_zero will also be true
918 for some other rarely occurring nonzero floats, but this
919 doesn't matter. Similar comments apply to
920 imag_part_zero. */
921 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
922 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
923 if (real_part_zero && imag_part_zero) {
924 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
925 }
926 else if (real_part_zero && !imag_part_zero) {
927 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
928 }
929 else if (!real_part_zero && imag_part_zero) {
930 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
931 }
932 else {
933 t = PyTuple_Pack(2, o, o->ob_type);
934 }
935 }
936 else {
937 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000938 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000939 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000940 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941
942 v = PyDict_GetItem(dict, t);
943 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000944 if (PyErr_Occurred())
945 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000947 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948 if (!v) {
949 Py_DECREF(t);
950 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000951 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952 if (PyDict_SetItem(dict, t, v) < 0) {
953 Py_DECREF(t);
954 Py_DECREF(v);
955 return -1;
956 }
957 Py_DECREF(v);
958 }
959 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000960 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000962 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963}
964
965static int
966compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
967 PyObject *o)
968{
969 int arg = compiler_add_o(c, dict, o);
970 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000971 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 return compiler_addop_i(c, opcode, arg);
973}
974
975static int
976compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000977 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978{
979 int arg;
980 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
981 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983 arg = compiler_add_o(c, dict, mangled);
984 Py_DECREF(mangled);
985 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987 return compiler_addop_i(c, opcode, arg);
988}
989
990/* Add an opcode with an integer argument.
991 Returns 0 on failure, 1 on success.
992*/
993
994static int
995compiler_addop_i(struct compiler *c, int opcode, int oparg)
996{
997 struct instr *i;
998 int off;
999 off = compiler_next_instr(c, c->u->u_curblock);
1000 if (off < 0)
1001 return 0;
1002 i = &c->u->u_curblock->b_instr[off];
1003 i->i_opcode = opcode;
1004 i->i_oparg = oparg;
1005 i->i_hasarg = 1;
1006 compiler_set_lineno(c, off);
1007 return 1;
1008}
1009
1010static int
1011compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1012{
1013 struct instr *i;
1014 int off;
1015
1016 assert(b != NULL);
1017 off = compiler_next_instr(c, c->u->u_curblock);
1018 if (off < 0)
1019 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020 i = &c->u->u_curblock->b_instr[off];
1021 i->i_opcode = opcode;
1022 i->i_target = b;
1023 i->i_hasarg = 1;
1024 if (absolute)
1025 i->i_jabs = 1;
1026 else
1027 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001028 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029 return 1;
1030}
1031
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001032/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1033 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034 it as the current block. NEXT_BLOCK() also creates an implicit jump
1035 from the current block to the new block.
1036*/
1037
Thomas Wouters89f507f2006-12-13 04:49:30 +00001038/* The returns inside these macros make it impossible to decref objects
1039 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040*/
1041
1042
1043#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001044 if (compiler_use_new_block((C)) == NULL) \
1045 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046}
1047
1048#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001049 if (compiler_next_block((C)) == NULL) \
1050 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051}
1052
1053#define ADDOP(C, OP) { \
1054 if (!compiler_addop((C), (OP))) \
1055 return 0; \
1056}
1057
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001058#define ADDOP_IN_SCOPE(C, OP) { \
1059 if (!compiler_addop((C), (OP))) { \
1060 compiler_exit_scope(c); \
1061 return 0; \
1062 } \
1063}
1064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065#define ADDOP_O(C, OP, O, TYPE) { \
1066 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1067 return 0; \
1068}
1069
1070#define ADDOP_NAME(C, OP, O, TYPE) { \
1071 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1072 return 0; \
1073}
1074
1075#define ADDOP_I(C, OP, O) { \
1076 if (!compiler_addop_i((C), (OP), (O))) \
1077 return 0; \
1078}
1079
1080#define ADDOP_JABS(C, OP, O) { \
1081 if (!compiler_addop_j((C), (OP), (O), 1)) \
1082 return 0; \
1083}
1084
1085#define ADDOP_JREL(C, OP, O) { \
1086 if (!compiler_addop_j((C), (OP), (O), 0)) \
1087 return 0; \
1088}
1089
1090/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1091 the ASDL name to synthesize the name of the C type and the visit function.
1092*/
1093
1094#define VISIT(C, TYPE, V) {\
1095 if (!compiler_visit_ ## TYPE((C), (V))) \
1096 return 0; \
1097}
1098
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001099#define VISIT_IN_SCOPE(C, TYPE, V) {\
1100 if (!compiler_visit_ ## TYPE((C), (V))) { \
1101 compiler_exit_scope(c); \
1102 return 0; \
1103 } \
1104}
1105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106#define VISIT_SLICE(C, V, CTX) {\
1107 if (!compiler_visit_slice((C), (V), (CTX))) \
1108 return 0; \
1109}
1110
1111#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001112 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001114 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001115 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116 if (!compiler_visit_ ## TYPE((C), elt)) \
1117 return 0; \
1118 } \
1119}
1120
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001121#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001122 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001123 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001124 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001126 if (!compiler_visit_ ## TYPE((C), elt)) { \
1127 compiler_exit_scope(c); \
1128 return 0; \
1129 } \
1130 } \
1131}
1132
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133static int
1134compiler_isdocstring(stmt_ty s)
1135{
1136 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001137 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 return s->v.Expr.value->kind == Str_kind;
1139}
1140
1141/* Compile a sequence of statements, checking for a docstring. */
1142
1143static int
1144compiler_body(struct compiler *c, asdl_seq *stmts)
1145{
1146 int i = 0;
1147 stmt_ty st;
1148
1149 if (!asdl_seq_LEN(stmts))
1150 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001151 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001152 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1153 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 i = 1;
1155 VISIT(c, expr, st->v.Expr.value);
1156 if (!compiler_nameop(c, __doc__, Store))
1157 return 0;
1158 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001159 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001160 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 return 1;
1162}
1163
1164static PyCodeObject *
1165compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001166{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001168 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 static PyObject *module;
1170 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001171 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 if (!module)
1173 return NULL;
1174 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001175 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1176 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001177 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 switch (mod->kind) {
1179 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001180 if (!compiler_body(c, mod->v.Module.body)) {
1181 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001183 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 break;
1185 case Interactive_kind:
1186 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001187 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 break;
1190 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001191 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001192 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 break;
1194 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001195 PyErr_SetString(PyExc_SystemError,
1196 "suite should not be possible");
1197 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001198 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001199 PyErr_Format(PyExc_SystemError,
1200 "module kind %d should not be possible",
1201 mod->kind);
1202 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 co = assemble(c, addNone);
1205 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001206 return co;
1207}
1208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209/* The test for LOCAL must come before the test for FREE in order to
1210 handle classes where name is both local and free. The local var is
1211 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001212*/
1213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214static int
1215get_ref_type(struct compiler *c, PyObject *name)
1216{
1217 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001218 if (scope == 0) {
1219 char buf[350];
1220 PyOS_snprintf(buf, sizeof(buf),
1221 "unknown scope for %.100s in %.100s(%s) in %s\n"
1222 "symbols: %s\nlocals: %s\nglobals: %s\n",
1223 PyString_AS_STRING(name),
1224 PyString_AS_STRING(c->u->u_name),
1225 PyObject_REPR(c->u->u_ste->ste_id),
1226 c->c_filename,
1227 PyObject_REPR(c->u->u_ste->ste_symbols),
1228 PyObject_REPR(c->u->u_varnames),
1229 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001231 Py_FatalError(buf);
1232 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001233
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001234 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
1237static int
1238compiler_lookup_arg(PyObject *dict, PyObject *name)
1239{
1240 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001243 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001245 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001248 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
1251static int
1252compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1253{
1254 int i, free = PyCode_GetNumFree(co);
1255 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001256 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1257 ADDOP_I(c, MAKE_FUNCTION, args);
1258 return 1;
1259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 for (i = 0; i < free; ++i) {
1261 /* Bypass com_addop_varname because it will generate
1262 LOAD_DEREF but LOAD_CLOSURE is needed.
1263 */
1264 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1265 int arg, reftype;
1266
1267 /* Special case: If a class contains a method with a
1268 free variable that has the same name as a method,
1269 the name will be considered free *and* local in the
1270 class. It should be handled by the closure, as
1271 well as by the normal name loookup logic.
1272 */
1273 reftype = get_ref_type(c, name);
1274 if (reftype == CELL)
1275 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1276 else /* (reftype == FREE) */
1277 arg = compiler_lookup_arg(c->u->u_freevars, name);
1278 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001279 fprintf(stderr,
1280 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281 "freevars of %s: %s\n",
1282 PyObject_REPR(name),
1283 PyString_AS_STRING(c->u->u_name),
1284 reftype, arg,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001285 PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286 PyObject_REPR(co->co_freevars));
1287 Py_FatalError("compiler_make_closure()");
1288 }
1289 ADDOP_I(c, LOAD_CLOSURE, arg);
1290 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001291 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001293 ADDOP_I(c, MAKE_CLOSURE, args);
1294 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295}
1296
1297static int
1298compiler_decorators(struct compiler *c, asdl_seq* decos)
1299{
1300 int i;
1301
1302 if (!decos)
1303 return 1;
1304
1305 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001306 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307 }
1308 return 1;
1309}
1310
1311static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001312compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1313 asdl_seq *kw_defaults)
1314{
1315 int i, default_count = 0;
1316 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001317 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001318 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1319 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001320 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001321 if (!compiler_visit_expr(c, default_)) {
1322 return -1;
1323 }
1324 default_count++;
1325 }
1326 }
1327 return default_count;
1328}
1329
1330static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001331compiler_visit_argannotation(struct compiler *c, identifier id,
1332 expr_ty annotation, PyObject *names)
1333{
1334 if (annotation) {
1335 VISIT(c, expr, annotation);
1336 if (PyList_Append(names, id))
1337 return -1;
1338 }
1339 return 0;
1340}
1341
1342static int
1343compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1344 PyObject *names)
1345{
1346 int i, error;
1347 for (i = 0; i < asdl_seq_LEN(args); i++) {
1348 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001349 error = compiler_visit_argannotation(
1350 c,
1351 arg->arg,
1352 arg->annotation,
1353 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001354 if (error)
1355 return error;
1356 }
1357 return 0;
1358}
1359
1360static int
1361compiler_visit_annotations(struct compiler *c, arguments_ty args,
1362 expr_ty returns)
1363{
Guido van Rossum0240b922007-02-26 21:23:50 +00001364 /* Push arg annotations and a list of the argument names. Return the #
1365 of items pushed. The expressions are evaluated out-of-order wrt the
1366 source code.
1367
1368 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1369 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001370 static identifier return_str;
1371 PyObject *names;
1372 int len;
1373 names = PyList_New(0);
1374 if (!names)
1375 return -1;
1376
1377 if (compiler_visit_argannotations(c, args->args, names))
1378 goto error;
1379 if (args->varargannotation &&
1380 compiler_visit_argannotation(c, args->vararg,
1381 args->varargannotation, names))
1382 goto error;
1383 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1384 goto error;
1385 if (args->kwargannotation &&
1386 compiler_visit_argannotation(c, args->kwarg,
1387 args->kwargannotation, names))
1388 goto error;
1389
1390 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001391 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001392 if (!return_str)
1393 goto error;
1394 }
1395 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1396 goto error;
1397 }
1398
1399 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001400 if (len > 65534) {
1401 /* len must fit in 16 bits, and len is incremented below */
1402 PyErr_SetString(PyExc_SyntaxError,
1403 "too many annotations");
1404 goto error;
1405 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001406 if (len) {
1407 /* convert names to a tuple and place on stack */
1408 PyObject *elt;
1409 int i;
1410 PyObject *s = PyTuple_New(len);
1411 if (!s)
1412 goto error;
1413 for (i = 0; i < len; i++) {
1414 elt = PyList_GET_ITEM(names, i);
1415 Py_INCREF(elt);
1416 PyTuple_SET_ITEM(s, i, elt);
1417 }
1418 ADDOP_O(c, LOAD_CONST, s, consts);
1419 Py_DECREF(s);
1420 len++; /* include the just-pushed tuple */
1421 }
1422 Py_DECREF(names);
1423 return len;
1424
1425error:
1426 Py_DECREF(names);
1427 return -1;
1428}
1429
1430static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431compiler_function(struct compiler *c, stmt_ty s)
1432{
1433 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001434 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001436 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001437 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001438 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001439 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001440 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
1442 assert(s->kind == FunctionDef_kind);
1443
1444 if (!compiler_decorators(c, decos))
1445 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001446 if (args->kwonlyargs) {
1447 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1448 args->kw_defaults);
1449 if (res < 0)
1450 return 0;
1451 kw_default_count = res;
1452 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 if (args->defaults)
1454 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001455 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001456 if (num_annotations < 0)
1457 return 0;
1458 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001459
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1461 s->lineno))
1462 return 0;
1463
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001464 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001465 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001466 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001467 first_const = st->v.Expr.value->v.Str.s;
1468 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001469 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001470 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001474 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001476 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001478 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1479 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480 }
1481 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001482 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483 if (co == NULL)
1484 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485
Guido van Rossum4f72a782006-10-27 23:31:49 +00001486 arglength = asdl_seq_LEN(args->defaults);
1487 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001488 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001489 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001490 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491
Neal Norwitzc1505362006-12-28 06:47:50 +00001492 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1494 ADDOP_I(c, CALL_FUNCTION, 1);
1495 }
1496
1497 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1498}
1499
1500static int
1501compiler_class(struct compiler *c, stmt_ty s)
1502{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001503 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001505 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001506 PySTEntryObject *ste;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001507 int err, i;
1508 asdl_seq* decos = s->v.ClassDef.decorator_list;
1509
1510 if (!compiler_decorators(c, decos))
1511 return 0;
1512
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001513 /* initialize statics */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001514 if (locals == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001515 locals = PyUnicode_InternFromString("__locals__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001516 if (locals == NULL)
1517 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001518 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001520 /* ultimately generate code for:
1521 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1522 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001523 <func> is a function/closure created from the class body;
1524 it has a single argument (__locals__) where the dict
1525 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001526 <name> is the class name
1527 <bases> is the positional arguments and *varargs argument
1528 <keywords> is the keyword arguments and **kwds argument
1529 This borrows from compiler_call.
1530 */
1531
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001532 /* 0. Create a fake argument named __locals__ */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001533 ste = PySymtable_Lookup(c->c_st, s);
1534 if (ste == NULL)
1535 return 0;
1536 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001537 err = PyList_Append(ste->ste_varnames, locals);
1538 Py_DECREF(ste);
1539 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001540 return 0;
1541
1542 /* 1. compile the class body into a code object */
1543 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1544 return 0;
1545 /* this block represents what we do in the new scope */
1546 {
1547 /* use the class name for name mangling */
1548 Py_INCREF(s->v.ClassDef.name);
1549 c->u->u_private = s->v.ClassDef.name;
1550 /* force it to have one mandatory argument */
1551 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001552 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001553 ADDOP_I(c, LOAD_FAST, 0);
1554 /* ... and store it into f_locals */
1555 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001556 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001557 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001558 if (!str || !compiler_nameop(c, str, Load)) {
1559 Py_XDECREF(str);
1560 compiler_exit_scope(c);
1561 return 0;
1562 }
1563 Py_DECREF(str);
1564 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001565 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001566 if (!str || !compiler_nameop(c, str, Store)) {
1567 Py_XDECREF(str);
1568 compiler_exit_scope(c);
1569 return 0;
1570 }
1571 Py_DECREF(str);
1572 /* compile the body proper */
1573 if (!compiler_body(c, s->v.ClassDef.body)) {
1574 compiler_exit_scope(c);
1575 return 0;
1576 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001577 /* return the (empty) __class__ cell */
1578 str = PyUnicode_InternFromString("__class__");
1579 if (str == NULL) {
1580 compiler_exit_scope(c);
1581 return 0;
1582 }
1583 i = compiler_lookup_arg(c->u->u_cellvars, str);
1584 Py_DECREF(str);
1585 if (i == -1) {
1586 /* This happens when nobody references the cell */
1587 PyErr_Clear();
1588 /* Return None */
1589 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1590 }
1591 else {
1592 /* Return the cell where to store __class__ */
1593 ADDOP_I(c, LOAD_CLOSURE, i);
1594 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001595 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1596 /* create the code object */
1597 co = assemble(c, 1);
1598 }
1599 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001600 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601 if (co == NULL)
1602 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001604 /* 2. load the 'build_class' function */
1605 ADDOP(c, LOAD_BUILD_CLASS);
1606
1607 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001608 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001609 Py_DECREF(co);
1610
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001611 /* 4. load class name */
1612 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1613
1614 /* 5. generate the rest of the code for the call */
1615 if (!compiler_call_helper(c, 2,
1616 s->v.ClassDef.bases,
1617 s->v.ClassDef.keywords,
1618 s->v.ClassDef.starargs,
1619 s->v.ClassDef.kwargs))
1620 return 0;
1621
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001622 /* 6. apply decorators */
1623 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1624 ADDOP_I(c, CALL_FUNCTION, 1);
1625 }
1626
1627 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1629 return 0;
1630 return 1;
1631}
1632
1633static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001634compiler_ifexp(struct compiler *c, expr_ty e)
1635{
1636 basicblock *end, *next;
1637
1638 assert(e->kind == IfExp_kind);
1639 end = compiler_new_block(c);
1640 if (end == NULL)
1641 return 0;
1642 next = compiler_new_block(c);
1643 if (next == NULL)
1644 return 0;
1645 VISIT(c, expr, e->v.IfExp.test);
1646 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1647 ADDOP(c, POP_TOP);
1648 VISIT(c, expr, e->v.IfExp.body);
1649 ADDOP_JREL(c, JUMP_FORWARD, end);
1650 compiler_use_next_block(c, next);
1651 ADDOP(c, POP_TOP);
1652 VISIT(c, expr, e->v.IfExp.orelse);
1653 compiler_use_next_block(c, end);
1654 return 1;
1655}
1656
1657static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658compiler_lambda(struct compiler *c, expr_ty e)
1659{
1660 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001661 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001662 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663 arguments_ty args = e->v.Lambda.args;
1664 assert(e->kind == Lambda_kind);
1665
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001666 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001667 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001668 if (!name)
1669 return 0;
1670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001671
Guido van Rossum4f72a782006-10-27 23:31:49 +00001672 if (args->kwonlyargs) {
1673 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1674 args->kw_defaults);
1675 if (res < 0) return 0;
1676 kw_default_count = res;
1677 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678 if (args->defaults)
1679 VISIT_SEQ(c, expr, args->defaults);
1680 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1681 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001684 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001685 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1686 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001688 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689 if (co == NULL)
1690 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691
Guido van Rossum4f72a782006-10-27 23:31:49 +00001692 arglength = asdl_seq_LEN(args->defaults);
1693 arglength |= kw_default_count << 8;
1694 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001695 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696
1697 return 1;
1698}
1699
1700static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701compiler_if(struct compiler *c, stmt_ty s)
1702{
1703 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001704 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705 assert(s->kind == If_kind);
1706 end = compiler_new_block(c);
1707 if (end == NULL)
1708 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001709 next = compiler_new_block(c);
1710 if (next == NULL)
1711 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001712
1713 constant = expr_constant(s->v.If.test);
1714 /* constant = 0: "if 0"
1715 * constant = 1: "if 1", "if 2", ...
1716 * constant = -1: rest */
1717 if (constant == 0) {
1718 if (s->v.If.orelse)
1719 VISIT_SEQ(c, stmt, s->v.If.orelse);
1720 } else if (constant == 1) {
1721 VISIT_SEQ(c, stmt, s->v.If.body);
1722 } else {
1723 VISIT(c, expr, s->v.If.test);
1724 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1725 ADDOP(c, POP_TOP);
1726 VISIT_SEQ(c, stmt, s->v.If.body);
1727 ADDOP_JREL(c, JUMP_FORWARD, end);
1728 compiler_use_next_block(c, next);
1729 ADDOP(c, POP_TOP);
1730 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001731 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001732 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001733 compiler_use_next_block(c, end);
1734 return 1;
1735}
1736
1737static int
1738compiler_for(struct compiler *c, stmt_ty s)
1739{
1740 basicblock *start, *cleanup, *end;
1741
1742 start = compiler_new_block(c);
1743 cleanup = compiler_new_block(c);
1744 end = compiler_new_block(c);
1745 if (start == NULL || end == NULL || cleanup == NULL)
1746 return 0;
1747 ADDOP_JREL(c, SETUP_LOOP, end);
1748 if (!compiler_push_fblock(c, LOOP, start))
1749 return 0;
1750 VISIT(c, expr, s->v.For.iter);
1751 ADDOP(c, GET_ITER);
1752 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001753 /* XXX(nnorwitz): is there a better way to handle this?
1754 for loops are special, we want to be able to trace them
1755 each time around, so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001756 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757 ADDOP_JREL(c, FOR_ITER, cleanup);
1758 VISIT(c, expr, s->v.For.target);
1759 VISIT_SEQ(c, stmt, s->v.For.body);
1760 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1761 compiler_use_next_block(c, cleanup);
1762 ADDOP(c, POP_BLOCK);
1763 compiler_pop_fblock(c, LOOP, start);
1764 VISIT_SEQ(c, stmt, s->v.For.orelse);
1765 compiler_use_next_block(c, end);
1766 return 1;
1767}
1768
1769static int
1770compiler_while(struct compiler *c, stmt_ty s)
1771{
1772 basicblock *loop, *orelse, *end, *anchor = NULL;
1773 int constant = expr_constant(s->v.While.test);
1774
Christian Heimes969fe572008-01-25 11:23:10 +00001775 if (constant == 0) {
1776 if (s->v.While.orelse)
1777 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001779 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 loop = compiler_new_block(c);
1781 end = compiler_new_block(c);
1782 if (constant == -1) {
1783 anchor = compiler_new_block(c);
1784 if (anchor == NULL)
1785 return 0;
1786 }
1787 if (loop == NULL || end == NULL)
1788 return 0;
1789 if (s->v.While.orelse) {
1790 orelse = compiler_new_block(c);
1791 if (orelse == NULL)
1792 return 0;
1793 }
1794 else
1795 orelse = NULL;
1796
1797 ADDOP_JREL(c, SETUP_LOOP, end);
1798 compiler_use_next_block(c, loop);
1799 if (!compiler_push_fblock(c, LOOP, loop))
1800 return 0;
1801 if (constant == -1) {
1802 VISIT(c, expr, s->v.While.test);
1803 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1804 ADDOP(c, POP_TOP);
1805 }
1806 VISIT_SEQ(c, stmt, s->v.While.body);
1807 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1808
1809 /* XXX should the two POP instructions be in a separate block
1810 if there is no else clause ?
1811 */
1812
1813 if (constant == -1) {
1814 compiler_use_next_block(c, anchor);
1815 ADDOP(c, POP_TOP);
1816 ADDOP(c, POP_BLOCK);
1817 }
1818 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001819 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820 VISIT_SEQ(c, stmt, s->v.While.orelse);
1821 compiler_use_next_block(c, end);
1822
1823 return 1;
1824}
1825
1826static int
1827compiler_continue(struct compiler *c)
1828{
1829 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001830 static const char IN_FINALLY_ERROR_MSG[] =
1831 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 int i;
1833
1834 if (!c->u->u_nfblocks)
1835 return compiler_error(c, LOOP_ERROR_MSG);
1836 i = c->u->u_nfblocks - 1;
1837 switch (c->u->u_fblock[i].fb_type) {
1838 case LOOP:
1839 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1840 break;
1841 case EXCEPT:
1842 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001843 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1844 /* Prevent continue anywhere under a finally
1845 even if hidden in a sub-try or except. */
1846 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1847 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1848 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849 if (i == -1)
1850 return compiler_error(c, LOOP_ERROR_MSG);
1851 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1852 break;
1853 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001854 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855 }
1856
1857 return 1;
1858}
1859
1860/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1861
1862 SETUP_FINALLY L
1863 <code for body>
1864 POP_BLOCK
1865 LOAD_CONST <None>
1866 L: <code for finalbody>
1867 END_FINALLY
1868
1869 The special instructions use the block stack. Each block
1870 stack entry contains the instruction that created it (here
1871 SETUP_FINALLY), the level of the value stack at the time the
1872 block stack entry was created, and a label (here L).
1873
1874 SETUP_FINALLY:
1875 Pushes the current value stack level and the label
1876 onto the block stack.
1877 POP_BLOCK:
1878 Pops en entry from the block stack, and pops the value
1879 stack until its level is the same as indicated on the
1880 block stack. (The label is ignored.)
1881 END_FINALLY:
1882 Pops a variable number of entries from the *value* stack
1883 and re-raises the exception they specify. The number of
1884 entries popped depends on the (pseudo) exception type.
1885
1886 The block stack is unwound when an exception is raised:
1887 when a SETUP_FINALLY entry is found, the exception is pushed
1888 onto the value stack (and the exception condition is cleared),
1889 and the interpreter jumps to the label gotten from the block
1890 stack.
1891*/
1892
1893static int
1894compiler_try_finally(struct compiler *c, stmt_ty s)
1895{
1896 basicblock *body, *end;
1897 body = compiler_new_block(c);
1898 end = compiler_new_block(c);
1899 if (body == NULL || end == NULL)
1900 return 0;
1901
1902 ADDOP_JREL(c, SETUP_FINALLY, end);
1903 compiler_use_next_block(c, body);
1904 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1905 return 0;
1906 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1907 ADDOP(c, POP_BLOCK);
1908 compiler_pop_fblock(c, FINALLY_TRY, body);
1909
1910 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1911 compiler_use_next_block(c, end);
1912 if (!compiler_push_fblock(c, FINALLY_END, end))
1913 return 0;
1914 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1915 ADDOP(c, END_FINALLY);
1916 compiler_pop_fblock(c, FINALLY_END, end);
1917
1918 return 1;
1919}
1920
1921/*
1922 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1923 (The contents of the value stack is shown in [], with the top
1924 at the right; 'tb' is trace-back info, 'val' the exception's
1925 associated value, and 'exc' the exception.)
1926
1927 Value stack Label Instruction Argument
1928 [] SETUP_EXCEPT L1
1929 [] <code for S>
1930 [] POP_BLOCK
1931 [] JUMP_FORWARD L0
1932
1933 [tb, val, exc] L1: DUP )
1934 [tb, val, exc, exc] <evaluate E1> )
1935 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1936 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1937 [tb, val, exc, 1] POP )
1938 [tb, val, exc] POP
1939 [tb, val] <assign to V1> (or POP if no V1)
1940 [tb] POP
1941 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001942 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943
1944 [tb, val, exc, 0] L2: POP
1945 [tb, val, exc] DUP
1946 .............................etc.......................
1947
1948 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001949 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950
1951 [] L0: <next statement>
1952
1953 Of course, parts are not generated if Vi or Ei is not present.
1954*/
1955static int
1956compiler_try_except(struct compiler *c, stmt_ty s)
1957{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001958 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 int i, n;
1960
1961 body = compiler_new_block(c);
1962 except = compiler_new_block(c);
1963 orelse = compiler_new_block(c);
1964 end = compiler_new_block(c);
1965 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1966 return 0;
1967 ADDOP_JREL(c, SETUP_EXCEPT, except);
1968 compiler_use_next_block(c, body);
1969 if (!compiler_push_fblock(c, EXCEPT, body))
1970 return 0;
1971 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1972 ADDOP(c, POP_BLOCK);
1973 compiler_pop_fblock(c, EXCEPT, body);
1974 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1975 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1976 compiler_use_next_block(c, except);
1977 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001978 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979 s->v.TryExcept.handlers, i);
1980 if (!handler->type && i < n-1)
1981 return compiler_error(c, "default 'except:' must be last");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001982 c->u->u_lineno_set = 0;
1983 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 except = compiler_new_block(c);
1985 if (except == NULL)
1986 return 0;
1987 if (handler->type) {
1988 ADDOP(c, DUP_TOP);
1989 VISIT(c, expr, handler->type);
1990 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1991 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1992 ADDOP(c, POP_TOP);
1993 }
1994 ADDOP(c, POP_TOP);
1995 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001996 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001997
1998 cleanup_end = compiler_new_block(c);
1999 cleanup_body = compiler_new_block(c);
2000 if(!(cleanup_end || cleanup_body))
2001 return 0;
2002
Guido van Rossum16be03e2007-01-10 18:51:35 +00002003 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002004 ADDOP(c, POP_TOP);
2005
2006 /*
2007 try:
2008 # body
2009 except type as name:
2010 try:
2011 # body
2012 finally:
2013 name = None
2014 del name
2015 */
2016
2017 /* second try: */
2018 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2019 compiler_use_next_block(c, cleanup_body);
2020 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2021 return 0;
2022
2023 /* second # body */
2024 VISIT_SEQ(c, stmt, handler->body);
2025 ADDOP(c, POP_BLOCK);
2026 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2027
2028 /* finally: */
2029 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2030 compiler_use_next_block(c, cleanup_end);
2031 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2032 return 0;
2033
2034 /* name = None */
2035 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00002036 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002037
Guido van Rossum16be03e2007-01-10 18:51:35 +00002038 /* del name */
2039 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002040
2041 ADDOP(c, END_FINALLY);
2042 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002043 }
2044 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00002045 ADDOP(c, POP_TOP);
2046 ADDOP(c, POP_TOP);
2047 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002049 ADDOP_JREL(c, JUMP_FORWARD, end);
2050 compiler_use_next_block(c, except);
2051 if (handler->type)
2052 ADDOP(c, POP_TOP);
2053 }
2054 ADDOP(c, END_FINALLY);
2055 compiler_use_next_block(c, orelse);
2056 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2057 compiler_use_next_block(c, end);
2058 return 1;
2059}
2060
2061static int
2062compiler_import_as(struct compiler *c, identifier name, identifier asname)
2063{
2064 /* The IMPORT_NAME opcode was already generated. This function
2065 merely needs to bind the result to a name.
2066
2067 If there is a dot in name, we need to split it and emit a
2068 LOAD_ATTR for each name.
2069 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002070 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2071 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 if (dot) {
2073 /* Consume the base module name to get the first attribute */
2074 src = dot + 1;
2075 while (dot) {
2076 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002077 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002078 dot = Py_UNICODE_strchr(src, '.');
2079 attr = PyUnicode_FromUnicode(src,
2080 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002081 if (!attr)
2082 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002084 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 src = dot + 1;
2086 }
2087 }
2088 return compiler_nameop(c, asname, Store);
2089}
2090
2091static int
2092compiler_import(struct compiler *c, stmt_ty s)
2093{
2094 /* The Import node stores a module name like a.b.c as a single
2095 string. This is convenient for all cases except
2096 import a.b.c as d
2097 where we need to parse that string to extract the individual
2098 module names.
2099 XXX Perhaps change the representation to make this case simpler?
2100 */
2101 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002104 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002105 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002106 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107
Christian Heimes217cfd12007-12-02 14:31:20 +00002108 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002109 if (level == NULL)
2110 return 0;
2111
2112 ADDOP_O(c, LOAD_CONST, level, consts);
2113 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2115 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2116
2117 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002118 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002119 if (!r)
2120 return r;
2121 }
2122 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002124 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2125 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002127 tmp = PyUnicode_FromUnicode(base,
2128 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 r = compiler_nameop(c, tmp, Store);
2130 if (dot) {
2131 Py_DECREF(tmp);
2132 }
2133 if (!r)
2134 return r;
2135 }
2136 }
2137 return 1;
2138}
2139
2140static int
2141compiler_from_import(struct compiler *c, stmt_ty s)
2142{
2143 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
2145 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002146 PyObject *level;
2147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148 if (!names)
2149 return 0;
2150
Christian Heimes217cfd12007-12-02 14:31:20 +00002151 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002152 if (!level) {
2153 Py_DECREF(names);
2154 return 0;
2155 }
2156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157 /* build up the names */
2158 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002159 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160 Py_INCREF(alias->name);
2161 PyTuple_SET_ITEM(names, i, alias->name);
2162 }
2163
2164 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002165 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2166 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002167 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168 Py_DECREF(names);
2169 return compiler_error(c,
2170 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002171 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172
2173 }
2174 }
2175
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002176 ADDOP_O(c, LOAD_CONST, level, consts);
2177 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002179 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2181 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002182 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183 identifier store_name;
2184
Martin v. Löwis5b222132007-06-10 09:51:05 +00002185 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 assert(n == 1);
2187 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002188 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189 }
2190
2191 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2192 store_name = alias->name;
2193 if (alias->asname)
2194 store_name = alias->asname;
2195
2196 if (!compiler_nameop(c, store_name, Store)) {
2197 Py_DECREF(names);
2198 return 0;
2199 }
2200 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002201 /* remove imported module */
2202 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203 return 1;
2204}
2205
2206static int
2207compiler_assert(struct compiler *c, stmt_ty s)
2208{
2209 static PyObject *assertion_error = NULL;
2210 basicblock *end;
2211
2212 if (Py_OptimizeFlag)
2213 return 1;
2214 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002215 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002216 if (assertion_error == NULL)
2217 return 0;
2218 }
2219 VISIT(c, expr, s->v.Assert.test);
2220 end = compiler_new_block(c);
2221 if (end == NULL)
2222 return 0;
2223 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2224 ADDOP(c, POP_TOP);
2225 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2226 if (s->v.Assert.msg) {
2227 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002228 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229 }
Collin Winter828f04a2007-08-31 00:04:24 +00002230 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002231 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002232 ADDOP(c, POP_TOP);
2233 return 1;
2234}
2235
2236static int
2237compiler_visit_stmt(struct compiler *c, stmt_ty s)
2238{
2239 int i, n;
2240
Thomas Wouters89f507f2006-12-13 04:49:30 +00002241 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002243 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002246 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002248 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002250 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002251 if (c->u->u_ste->ste_type != FunctionBlock)
2252 return compiler_error(c, "'return' outside function");
2253 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 VISIT(c, expr, s->v.Return.value);
2255 }
2256 else
2257 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2258 ADDOP(c, RETURN_VALUE);
2259 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002260 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 VISIT_SEQ(c, expr, s->v.Delete.targets)
2262 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002263 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264 n = asdl_seq_LEN(s->v.Assign.targets);
2265 VISIT(c, expr, s->v.Assign.value);
2266 for (i = 0; i < n; i++) {
2267 if (i < n - 1)
2268 ADDOP(c, DUP_TOP);
2269 VISIT(c, expr,
2270 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2271 }
2272 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002273 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002275 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002277 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002279 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002281 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002283 if (s->v.Raise.exc) {
2284 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002286 if (s->v.Raise.cause) {
2287 VISIT(c, expr, s->v.Raise.cause);
2288 n++;
2289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 }
2291 ADDOP_I(c, RAISE_VARARGS, n);
2292 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002295 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002297 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002299 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002301 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002303 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002304 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002306 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002308 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 ADDOP(c, PRINT_EXPR);
2310 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002311 else if (s->v.Expr.value->kind != Str_kind &&
2312 s->v.Expr.value->kind != Num_kind) {
2313 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 ADDOP(c, POP_TOP);
2315 }
2316 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002317 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002320 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 return compiler_error(c, "'break' outside loop");
2322 ADDOP(c, BREAK_LOOP);
2323 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002324 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002326 case With_kind:
2327 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 }
2329 return 1;
2330}
2331
2332static int
2333unaryop(unaryop_ty op)
2334{
2335 switch (op) {
2336 case Invert:
2337 return UNARY_INVERT;
2338 case Not:
2339 return UNARY_NOT;
2340 case UAdd:
2341 return UNARY_POSITIVE;
2342 case USub:
2343 return UNARY_NEGATIVE;
2344 }
2345 return 0;
2346}
2347
2348static int
2349binop(struct compiler *c, operator_ty op)
2350{
2351 switch (op) {
2352 case Add:
2353 return BINARY_ADD;
2354 case Sub:
2355 return BINARY_SUBTRACT;
2356 case Mult:
2357 return BINARY_MULTIPLY;
2358 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002359 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 case Mod:
2361 return BINARY_MODULO;
2362 case Pow:
2363 return BINARY_POWER;
2364 case LShift:
2365 return BINARY_LSHIFT;
2366 case RShift:
2367 return BINARY_RSHIFT;
2368 case BitOr:
2369 return BINARY_OR;
2370 case BitXor:
2371 return BINARY_XOR;
2372 case BitAnd:
2373 return BINARY_AND;
2374 case FloorDiv:
2375 return BINARY_FLOOR_DIVIDE;
2376 }
2377 return 0;
2378}
2379
2380static int
2381cmpop(cmpop_ty op)
2382{
2383 switch (op) {
2384 case Eq:
2385 return PyCmp_EQ;
2386 case NotEq:
2387 return PyCmp_NE;
2388 case Lt:
2389 return PyCmp_LT;
2390 case LtE:
2391 return PyCmp_LE;
2392 case Gt:
2393 return PyCmp_GT;
2394 case GtE:
2395 return PyCmp_GE;
2396 case Is:
2397 return PyCmp_IS;
2398 case IsNot:
2399 return PyCmp_IS_NOT;
2400 case In:
2401 return PyCmp_IN;
2402 case NotIn:
2403 return PyCmp_NOT_IN;
2404 }
2405 return PyCmp_BAD;
2406}
2407
2408static int
2409inplace_binop(struct compiler *c, operator_ty op)
2410{
2411 switch (op) {
2412 case Add:
2413 return INPLACE_ADD;
2414 case Sub:
2415 return INPLACE_SUBTRACT;
2416 case Mult:
2417 return INPLACE_MULTIPLY;
2418 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002419 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002420 case Mod:
2421 return INPLACE_MODULO;
2422 case Pow:
2423 return INPLACE_POWER;
2424 case LShift:
2425 return INPLACE_LSHIFT;
2426 case RShift:
2427 return INPLACE_RSHIFT;
2428 case BitOr:
2429 return INPLACE_OR;
2430 case BitXor:
2431 return INPLACE_XOR;
2432 case BitAnd:
2433 return INPLACE_AND;
2434 case FloorDiv:
2435 return INPLACE_FLOOR_DIVIDE;
2436 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002437 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002438 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 return 0;
2440}
2441
2442static int
2443compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2444{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002445 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2447
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002448 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002449 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 /* XXX AugStore isn't used anywhere! */
2451
2452 /* First check for assignment to __debug__. Param? */
2453 if ((ctx == Store || ctx == AugStore || ctx == Del)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002454 && !PyUnicode_CompareWithASCIIString(name, "__debug__")) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 return compiler_error(c, "can not assign to __debug__");
2456 }
2457
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002458 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002459 if (!mangled)
2460 return 0;
2461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 op = 0;
2463 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002464 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 switch (scope) {
2466 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002467 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 optype = OP_DEREF;
2469 break;
2470 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002471 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472 optype = OP_DEREF;
2473 break;
2474 case LOCAL:
2475 if (c->u->u_ste->ste_type == FunctionBlock)
2476 optype = OP_FAST;
2477 break;
2478 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002479 if (c->u->u_ste->ste_type == FunctionBlock &&
2480 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481 optype = OP_GLOBAL;
2482 break;
2483 case GLOBAL_EXPLICIT:
2484 optype = OP_GLOBAL;
2485 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002486 default:
2487 /* scope can be 0 */
2488 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 }
2490
2491 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002492 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493
2494 switch (optype) {
2495 case OP_DEREF:
2496 switch (ctx) {
2497 case Load: op = LOAD_DEREF; break;
2498 case Store: op = STORE_DEREF; break;
2499 case AugLoad:
2500 case AugStore:
2501 break;
2502 case Del:
2503 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002504 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002506 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002507 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002510 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002511 PyErr_SetString(PyExc_SystemError,
2512 "param invalid for deref variable");
2513 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514 }
2515 break;
2516 case OP_FAST:
2517 switch (ctx) {
2518 case Load: op = LOAD_FAST; break;
2519 case Store: op = STORE_FAST; break;
2520 case Del: op = DELETE_FAST; break;
2521 case AugLoad:
2522 case AugStore:
2523 break;
2524 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002525 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002526 PyErr_SetString(PyExc_SystemError,
2527 "param invalid for local variable");
2528 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002530 ADDOP_O(c, op, mangled, varnames);
2531 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 return 1;
2533 case OP_GLOBAL:
2534 switch (ctx) {
2535 case Load: op = LOAD_GLOBAL; break;
2536 case Store: op = STORE_GLOBAL; break;
2537 case Del: op = DELETE_GLOBAL; break;
2538 case AugLoad:
2539 case AugStore:
2540 break;
2541 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002542 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002543 PyErr_SetString(PyExc_SystemError,
2544 "param invalid for global variable");
2545 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002546 }
2547 break;
2548 case OP_NAME:
2549 switch (ctx) {
2550 case Load: op = LOAD_NAME; break;
2551 case Store: op = STORE_NAME; break;
2552 case Del: op = DELETE_NAME; break;
2553 case AugLoad:
2554 case AugStore:
2555 break;
2556 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002557 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002558 PyErr_SetString(PyExc_SystemError,
2559 "param invalid for name variable");
2560 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561 }
2562 break;
2563 }
2564
2565 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002566 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002567 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002568 if (arg < 0)
2569 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002570 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571}
2572
2573static int
2574compiler_boolop(struct compiler *c, expr_ty e)
2575{
2576 basicblock *end;
2577 int jumpi, i, n;
2578 asdl_seq *s;
2579
2580 assert(e->kind == BoolOp_kind);
2581 if (e->v.BoolOp.op == And)
2582 jumpi = JUMP_IF_FALSE;
2583 else
2584 jumpi = JUMP_IF_TRUE;
2585 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002586 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587 return 0;
2588 s = e->v.BoolOp.values;
2589 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002590 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002592 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593 ADDOP_JREL(c, jumpi, end);
2594 ADDOP(c, POP_TOP)
2595 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002596 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597 compiler_use_next_block(c, end);
2598 return 1;
2599}
2600
2601static int
2602compiler_list(struct compiler *c, expr_ty e)
2603{
2604 int n = asdl_seq_LEN(e->v.List.elts);
2605 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002606 int i, seen_star = 0;
2607 for (i = 0; i < n; i++) {
2608 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2609 if (elt->kind == Starred_kind && !seen_star) {
2610 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2611 seen_star = 1;
2612 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2613 } else if (elt->kind == Starred_kind) {
2614 return compiler_error(c,
2615 "two starred expressions in assignment");
2616 }
2617 }
2618 if (!seen_star) {
2619 ADDOP_I(c, UNPACK_SEQUENCE, n);
2620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 }
2622 VISIT_SEQ(c, expr, e->v.List.elts);
2623 if (e->v.List.ctx == Load) {
2624 ADDOP_I(c, BUILD_LIST, n);
2625 }
2626 return 1;
2627}
2628
2629static int
2630compiler_tuple(struct compiler *c, expr_ty e)
2631{
2632 int n = asdl_seq_LEN(e->v.Tuple.elts);
2633 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002634 int i, seen_star = 0;
2635 for (i = 0; i < n; i++) {
2636 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2637 if (elt->kind == Starred_kind && !seen_star) {
2638 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2639 seen_star = 1;
2640 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2641 } else if (elt->kind == Starred_kind) {
2642 return compiler_error(c,
2643 "two starred expressions in assignment");
2644 }
2645 }
2646 if (!seen_star) {
2647 ADDOP_I(c, UNPACK_SEQUENCE, n);
2648 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 }
2650 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2651 if (e->v.Tuple.ctx == Load) {
2652 ADDOP_I(c, BUILD_TUPLE, n);
2653 }
2654 return 1;
2655}
2656
2657static int
2658compiler_compare(struct compiler *c, expr_ty e)
2659{
2660 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662
2663 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2664 VISIT(c, expr, e->v.Compare.left);
2665 n = asdl_seq_LEN(e->v.Compare.ops);
2666 assert(n > 0);
2667 if (n > 1) {
2668 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 if (cleanup == NULL)
2670 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002671 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002672 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 }
2674 for (i = 1; i < n; i++) {
2675 ADDOP(c, DUP_TOP);
2676 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002678 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002679 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2681 NEXT_BLOCK(c);
2682 ADDOP(c, POP_TOP);
2683 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002684 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002685 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002687 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002689 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 if (n > 1) {
2691 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002692 if (end == NULL)
2693 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 ADDOP_JREL(c, JUMP_FORWARD, end);
2695 compiler_use_next_block(c, cleanup);
2696 ADDOP(c, ROT_TWO);
2697 ADDOP(c, POP_TOP);
2698 compiler_use_next_block(c, end);
2699 }
2700 return 1;
2701}
2702
2703static int
2704compiler_call(struct compiler *c, expr_ty e)
2705{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002707 return compiler_call_helper(c, 0,
2708 e->v.Call.args,
2709 e->v.Call.keywords,
2710 e->v.Call.starargs,
2711 e->v.Call.kwargs);
2712}
2713
2714/* shared code between compiler_call and compiler_class */
2715static int
2716compiler_call_helper(struct compiler *c,
2717 int n, /* Args already pushed */
2718 asdl_seq *args,
2719 asdl_seq *keywords,
2720 expr_ty starargs,
2721 expr_ty kwargs)
2722{
2723 int code = 0;
2724
2725 n += asdl_seq_LEN(args);
2726 VISIT_SEQ(c, expr, args);
2727 if (keywords) {
2728 VISIT_SEQ(c, keyword, keywords);
2729 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002731 if (starargs) {
2732 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 code |= 1;
2734 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002735 if (kwargs) {
2736 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737 code |= 2;
2738 }
2739 switch (code) {
2740 case 0:
2741 ADDOP_I(c, CALL_FUNCTION, n);
2742 break;
2743 case 1:
2744 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2745 break;
2746 case 2:
2747 ADDOP_I(c, CALL_FUNCTION_KW, n);
2748 break;
2749 case 3:
2750 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2751 break;
2752 }
2753 return 1;
2754}
2755
Nick Coghlan650f0d02007-04-15 12:05:43 +00002756
2757/* List and set comprehensions and generator expressions work by creating a
2758 nested function to perform the actual iteration. This means that the
2759 iteration variables don't leak into the current scope.
2760 The defined function is called immediately following its definition, with the
2761 result of that call being the result of the expression.
2762 The LC/SC version returns the populated container, while the GE version is
2763 flagged in symtable.c as a generator, so it returns the generator object
2764 when the function is called.
2765 This code *knows* that the loop cannot contain break, continue, or return,
2766 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2767
2768 Possible cleanups:
2769 - iterate over the generator sequence instead of using recursion
2770*/
2771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002773compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
2774 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002775 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776{
2777 /* generate code for the iterator, then each of the ifs,
2778 and then write to the element */
2779
Nick Coghlan650f0d02007-04-15 12:05:43 +00002780 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002781 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002782 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002783
2784 start = compiler_new_block(c);
2785 skip = compiler_new_block(c);
2786 if_cleanup = compiler_new_block(c);
2787 anchor = compiler_new_block(c);
2788
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002789 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002790 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792
Nick Coghlan650f0d02007-04-15 12:05:43 +00002793 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795 if (gen_index == 0) {
2796 /* Receive outermost iter as an implicit argument */
2797 c->u->u_argcount = 1;
2798 ADDOP_I(c, LOAD_FAST, 0);
2799 }
2800 else {
2801 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002802 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002803 ADDOP(c, GET_ITER);
2804 }
2805 compiler_use_next_block(c, start);
2806 ADDOP_JREL(c, FOR_ITER, anchor);
2807 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002808 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002810 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002811 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002812 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002813 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814 VISIT(c, expr, e);
2815 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2816 NEXT_BLOCK(c);
2817 ADDOP(c, POP_TOP);
2818 }
2819
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 if (++gen_index < asdl_seq_LEN(generators))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002821 if (!compiler_comprehension_generator(c, tmpname,
2822 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002823 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002824 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825
Nick Coghlan650f0d02007-04-15 12:05:43 +00002826 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002827 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002828 /* comprehension specific code */
2829 switch (type) {
2830 case COMP_GENEXP:
2831 VISIT(c, expr, elt);
2832 ADDOP(c, YIELD_VALUE);
2833 ADDOP(c, POP_TOP);
2834 break;
2835 case COMP_LISTCOMP:
2836 if (!compiler_nameop(c, tmpname, Load))
2837 return 0;
2838 VISIT(c, expr, elt);
2839 ADDOP(c, LIST_APPEND);
2840 break;
2841 case COMP_SETCOMP:
2842 if (!compiler_nameop(c, tmpname, Load))
2843 return 0;
2844 VISIT(c, expr, elt);
2845 ADDOP(c, SET_ADD);
2846 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002847 case COMP_DICTCOMP:
2848 if (!compiler_nameop(c, tmpname, Load))
2849 return 0;
2850 /* With 'd[k] = v', v is evaluated before k, so we do
2851 the same. STORE_SUBSCR requires (item, map, key),
2852 so we still end up ROTing once. */
2853 VISIT(c, expr, val);
2854 ADDOP(c, ROT_TWO);
2855 VISIT(c, expr, elt);
2856 ADDOP(c, STORE_SUBSCR);
2857 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002858 default:
2859 return 0;
2860 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861
2862 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 for (i = 0; i < n; i++) {
2865 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002866 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869 ADDOP(c, POP_TOP);
2870 }
2871 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2872 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873
2874 return 1;
2875}
2876
2877static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002878compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002879 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002880{
2881 PyCodeObject *co = NULL;
2882 identifier tmp = NULL;
2883 expr_ty outermost_iter;
2884
2885 outermost_iter = ((comprehension_ty)
2886 asdl_seq_GET(generators, 0))->iter;
2887
2888 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2889 goto error;
2890
2891 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002892 int op;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002893 tmp = compiler_new_tmpname(c);
2894 if (!tmp)
2895 goto error_in_scope;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002896 switch (type) {
2897 case COMP_LISTCOMP:
2898 op = BUILD_LIST;
2899 break;
2900 case COMP_SETCOMP:
2901 op = BUILD_SET;
2902 break;
2903 case COMP_DICTCOMP:
2904 op = BUILD_MAP;
2905 break;
2906 default:
2907 PyErr_Format(PyExc_SystemError,
2908 "unknown comprehension type %d", type);
2909 goto error_in_scope;
2910 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002911
Guido van Rossum992d4a32007-07-11 13:09:30 +00002912 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002913 ADDOP(c, DUP_TOP);
2914 if (!compiler_nameop(c, tmp, Store))
2915 goto error_in_scope;
2916 }
2917
Guido van Rossum992d4a32007-07-11 13:09:30 +00002918 if (!compiler_comprehension_generator(c, tmp, generators, 0, elt,
2919 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002920 goto error_in_scope;
2921
2922 if (type != COMP_GENEXP) {
2923 ADDOP(c, RETURN_VALUE);
2924 }
2925
2926 co = assemble(c, 1);
2927 compiler_exit_scope(c);
2928 if (co == NULL)
2929 goto error;
2930
2931 if (!compiler_make_closure(c, co, 0))
2932 goto error;
2933 Py_DECREF(co);
2934 Py_XDECREF(tmp);
2935
2936 VISIT(c, expr, outermost_iter);
2937 ADDOP(c, GET_ITER);
2938 ADDOP_I(c, CALL_FUNCTION, 1);
2939 return 1;
2940error_in_scope:
2941 compiler_exit_scope(c);
2942error:
2943 Py_XDECREF(co);
2944 Py_XDECREF(tmp);
2945 return 0;
2946}
2947
2948static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949compiler_genexp(struct compiler *c, expr_ty e)
2950{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002951 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002952 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002953 name = PyUnicode_FromString("<genexp>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002954 if (!name)
2955 return 0;
2956 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002957 assert(e->kind == GeneratorExp_kind);
2958 return compiler_comprehension(c, e, COMP_GENEXP, name,
2959 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002960 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961}
2962
2963static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002964compiler_listcomp(struct compiler *c, expr_ty e)
2965{
2966 static identifier name;
2967 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002968 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002969 if (!name)
2970 return 0;
2971 }
2972 assert(e->kind == ListComp_kind);
2973 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2974 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002975 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002976}
2977
2978static int
2979compiler_setcomp(struct compiler *c, expr_ty e)
2980{
2981 static identifier name;
2982 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002983 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002984 if (!name)
2985 return 0;
2986 }
2987 assert(e->kind == SetComp_kind);
2988 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2989 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002990 e->v.SetComp.elt, NULL);
2991}
2992
2993
2994static int
2995compiler_dictcomp(struct compiler *c, expr_ty e)
2996{
2997 static identifier name;
2998 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00002999 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003000 if (!name)
3001 return 0;
3002 }
3003 assert(e->kind == DictComp_kind);
3004 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3005 e->v.DictComp.generators,
3006 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003007}
3008
3009
3010static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011compiler_visit_keyword(struct compiler *c, keyword_ty k)
3012{
3013 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3014 VISIT(c, expr, k->value);
3015 return 1;
3016}
3017
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003018/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 whether they are true or false.
3020
3021 Return values: 1 for true, 0 for false, -1 for non-constant.
3022 */
3023
3024static int
3025expr_constant(expr_ty e)
3026{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003027 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003029 case Ellipsis_kind:
3030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031 case Num_kind:
3032 return PyObject_IsTrue(e->v.Num.n);
3033 case Str_kind:
3034 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003035 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003036 /* optimize away names that can't be reassigned */
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003037 id = PyString_AS_STRING(
3038 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003039 if (strcmp(id, "True") == 0) return 1;
3040 if (strcmp(id, "False") == 0) return 0;
3041 if (strcmp(id, "None") == 0) return 0;
3042 if (strcmp(id, "__debug__") == 0)
3043 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003044 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 default:
3046 return -1;
3047 }
3048}
3049
Guido van Rossumc2e20742006-02-27 22:32:47 +00003050/*
3051 Implements the with statement from PEP 343.
3052
3053 The semantics outlined in that PEP are as follows:
3054
3055 with EXPR as VAR:
3056 BLOCK
3057
3058 It is implemented roughly as:
3059
Thomas Wouters477c8d52006-05-27 19:21:47 +00003060 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003061 exit = context.__exit__ # not calling it
3062 value = context.__enter__()
3063 try:
3064 VAR = value # if VAR present in the syntax
3065 BLOCK
3066 finally:
3067 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003068 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003069 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 exit(*exc)
3072 */
3073static int
3074compiler_with(struct compiler *c, stmt_ty s)
3075{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003076 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003077 basicblock *block, *finally;
3078 identifier tmpexit, tmpvalue = NULL;
3079
3080 assert(s->kind == With_kind);
3081
Guido van Rossumc2e20742006-02-27 22:32:47 +00003082 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003083 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003084 if (!enter_attr)
3085 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003086 }
3087 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003088 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003089 if (!exit_attr)
3090 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003091 }
3092
3093 block = compiler_new_block(c);
3094 finally = compiler_new_block(c);
3095 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003096 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003097
3098 /* Create a temporary variable to hold context.__exit__ */
3099 tmpexit = compiler_new_tmpname(c);
3100 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003101 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003102 PyArena_AddPyObject(c->c_arena, tmpexit);
3103
3104 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003105 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003106 We need to do this rather than preserving it on the stack
3107 because SETUP_FINALLY remembers the stack level.
3108 We need to do the assignment *inside* the try/finally
3109 so that context.__exit__() is called when the assignment
3110 fails. But we need to call context.__enter__() *before*
3111 the try/finally so that if it fails we won't call
3112 context.__exit__().
3113 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003114 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003115 if (tmpvalue == NULL)
3116 return 0;
3117 PyArena_AddPyObject(c->c_arena, tmpvalue);
3118 }
3119
Thomas Wouters477c8d52006-05-27 19:21:47 +00003120 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003121 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003122
3123 /* Squirrel away context.__exit__ */
3124 ADDOP(c, DUP_TOP);
3125 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3126 if (!compiler_nameop(c, tmpexit, Store))
3127 return 0;
3128
3129 /* Call context.__enter__() */
3130 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3131 ADDOP_I(c, CALL_FUNCTION, 0);
3132
3133 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 /* Store it in tmpvalue */
3135 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003136 return 0;
3137 }
3138 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003139 /* Discard result from context.__enter__() */
3140 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003141 }
3142
3143 /* Start the try block */
3144 ADDOP_JREL(c, SETUP_FINALLY, finally);
3145
3146 compiler_use_next_block(c, block);
3147 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003149 }
3150
3151 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003152 /* Bind saved result of context.__enter__() to VAR */
3153 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003154 !compiler_nameop(c, tmpvalue, Del))
3155 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003157 }
3158
3159 /* BLOCK code */
3160 VISIT_SEQ(c, stmt, s->v.With.body);
3161
3162 /* End of try block; start the finally block */
3163 ADDOP(c, POP_BLOCK);
3164 compiler_pop_fblock(c, FINALLY_TRY, block);
3165
3166 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3167 compiler_use_next_block(c, finally);
3168 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003170
3171 /* Finally block starts; push tmpexit and issue our magic opcode. */
3172 if (!compiler_nameop(c, tmpexit, Load) ||
3173 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003174 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003175 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003176
3177 /* Finally block ends. */
3178 ADDOP(c, END_FINALLY);
3179 compiler_pop_fblock(c, FINALLY_END, finally);
3180 return 1;
3181}
3182
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183static int
3184compiler_visit_expr(struct compiler *c, expr_ty e)
3185{
3186 int i, n;
3187
Thomas Wouters89f507f2006-12-13 04:49:30 +00003188 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003189 set a new line number for the next instruction.
3190 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191 if (e->lineno > c->u->u_lineno) {
3192 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003193 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 }
3195 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 VISIT(c, expr, e->v.BinOp.left);
3200 VISIT(c, expr, e->v.BinOp.right);
3201 ADDOP(c, binop(c, e->v.BinOp.op));
3202 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 VISIT(c, expr, e->v.UnaryOp.operand);
3205 ADDOP(c, unaryop(e->v.UnaryOp.op));
3206 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003207 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003209 case IfExp_kind:
3210 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003213 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003215 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003216 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
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));
Christian Heimes99170a52007-12-19 02:07:34 +00003219 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 }
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);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003258 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003259 case Ellipsis_kind:
3260 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3261 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 if (e->v.Attribute.ctx != AugStore)
3265 VISIT(c, expr, e->v.Attribute.value);
3266 switch (e->v.Attribute.ctx) {
3267 case AugLoad:
3268 ADDOP(c, DUP_TOP);
3269 /* Fall through to load */
3270 case Load:
3271 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3272 break;
3273 case AugStore:
3274 ADDOP(c, ROT_TWO);
3275 /* Fall through to save */
3276 case Store:
3277 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3278 break;
3279 case Del:
3280 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3281 break;
3282 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003283 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003284 PyErr_SetString(PyExc_SystemError,
3285 "param invalid in attribute expression");
3286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 }
3288 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003289 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290 switch (e->v.Subscript.ctx) {
3291 case AugLoad:
3292 VISIT(c, expr, e->v.Subscript.value);
3293 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3294 break;
3295 case Load:
3296 VISIT(c, expr, e->v.Subscript.value);
3297 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3298 break;
3299 case AugStore:
3300 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3301 break;
3302 case Store:
3303 VISIT(c, expr, e->v.Subscript.value);
3304 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3305 break;
3306 case Del:
3307 VISIT(c, expr, e->v.Subscript.value);
3308 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3309 break;
3310 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003311 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003312 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003313 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003314 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315 }
3316 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003317 case Starred_kind:
3318 switch (e->v.Starred.ctx) {
3319 case Store:
3320 /* In all legitimate cases, the Starred node was already replaced
3321 * by compiler_list/compiler_tuple. XXX: is that okay? */
3322 return compiler_error(c,
3323 "starred assignment target must be in a list or tuple");
3324 default:
3325 return compiler_error(c,
3326 "can use starred expression only as assignment target");
3327 }
3328 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003329 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3331 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003332 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003334 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335 return compiler_tuple(c, e);
3336 }
3337 return 1;
3338}
3339
3340static int
3341compiler_augassign(struct compiler *c, stmt_ty s)
3342{
3343 expr_ty e = s->v.AugAssign.target;
3344 expr_ty auge;
3345
3346 assert(s->kind == AugAssign_kind);
3347
3348 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003349 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003350 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003351 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003352 if (auge == NULL)
3353 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003354 VISIT(c, expr, auge);
3355 VISIT(c, expr, s->v.AugAssign.value);
3356 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3357 auge->v.Attribute.ctx = AugStore;
3358 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359 break;
3360 case Subscript_kind:
3361 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003362 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003363 if (auge == NULL)
3364 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365 VISIT(c, expr, auge);
3366 VISIT(c, expr, s->v.AugAssign.value);
3367 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003368 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003370 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003372 if (!compiler_nameop(c, e->v.Name.id, Load))
3373 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003374 VISIT(c, expr, s->v.AugAssign.value);
3375 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3376 return compiler_nameop(c, e->v.Name.id, Store);
3377 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003378 PyErr_Format(PyExc_SystemError,
3379 "invalid node type (%d) for augmented assignment",
3380 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003381 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382 }
3383 return 1;
3384}
3385
3386static int
3387compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3388{
3389 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003390 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3391 PyErr_SetString(PyExc_SystemError,
3392 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003395 f = &c->u->u_fblock[c->u->u_nfblocks++];
3396 f->fb_type = t;
3397 f->fb_block = b;
3398 return 1;
3399}
3400
3401static void
3402compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3403{
3404 struct compiler_unit *u = c->u;
3405 assert(u->u_nfblocks > 0);
3406 u->u_nfblocks--;
3407 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3408 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3409}
3410
Thomas Wouters89f507f2006-12-13 04:49:30 +00003411static int
3412compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003413 int i;
3414 struct compiler_unit *u = c->u;
3415 for (i = 0; i < u->u_nfblocks; ++i) {
3416 if (u->u_fblock[i].fb_type == LOOP)
3417 return 1;
3418 }
3419 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003420}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421/* Raises a SyntaxError and returns 0.
3422 If something goes wrong, a different exception may be raised.
3423*/
3424
3425static int
3426compiler_error(struct compiler *c, const char *errstr)
3427{
3428 PyObject *loc;
3429 PyObject *u = NULL, *v = NULL;
3430
3431 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3432 if (!loc) {
3433 Py_INCREF(Py_None);
3434 loc = Py_None;
3435 }
3436 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3437 Py_None, loc);
3438 if (!u)
3439 goto exit;
3440 v = Py_BuildValue("(zO)", errstr, u);
3441 if (!v)
3442 goto exit;
3443 PyErr_SetObject(PyExc_SyntaxError, v);
3444 exit:
3445 Py_DECREF(loc);
3446 Py_XDECREF(u);
3447 Py_XDECREF(v);
3448 return 0;
3449}
3450
3451static int
3452compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003453 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457 /* XXX this code is duplicated */
3458 switch (ctx) {
3459 case AugLoad: /* fall through to Load */
3460 case Load: op = BINARY_SUBSCR; break;
3461 case AugStore:/* fall through to Store */
3462 case Store: op = STORE_SUBSCR; break;
3463 case Del: op = DELETE_SUBSCR; break;
3464 case Param:
3465 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003466 "invalid %s kind %d in subscript\n",
3467 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468 return 0;
3469 }
3470 if (ctx == AugLoad) {
3471 ADDOP_I(c, DUP_TOPX, 2);
3472 }
3473 else if (ctx == AugStore) {
3474 ADDOP(c, ROT_THREE);
3475 }
3476 ADDOP(c, op);
3477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478}
3479
3480static int
3481compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3482{
3483 int n = 2;
3484 assert(s->kind == Slice_kind);
3485
3486 /* only handles the cases where BUILD_SLICE is emitted */
3487 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003488 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489 }
3490 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003491 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496 }
3497 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003498 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499 }
3500
3501 if (s->v.Slice.step) {
3502 n++;
3503 VISIT(c, expr, s->v.Slice.step);
3504 }
3505 ADDOP_I(c, BUILD_SLICE, n);
3506 return 1;
3507}
3508
3509static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3511 expr_context_ty ctx)
3512{
3513 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 case Slice_kind:
3515 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 case Index_kind:
3517 VISIT(c, expr, s->v.Index.value);
3518 break;
3519 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003520 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003521 PyErr_SetString(PyExc_SystemError,
3522 "extended slice invalid in nested slice");
3523 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 }
3525 return 1;
3526}
3527
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528static int
3529compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3530{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003531 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003533 case Index_kind:
3534 kindname = "index";
3535 if (ctx != AugStore) {
3536 VISIT(c, expr, s->v.Index.value);
3537 }
3538 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003540 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003541 if (ctx != AugStore) {
3542 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 return 0;
3544 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003545 break;
3546 case ExtSlice_kind:
3547 kindname = "extended slice";
3548 if (ctx != AugStore) {
3549 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3550 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003551 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003552 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003553 if (!compiler_visit_nested_slice(c, sub, ctx))
3554 return 0;
3555 }
3556 ADDOP_I(c, BUILD_TUPLE, n);
3557 }
3558 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003559 default:
3560 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003561 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003562 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003564 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565}
3566
Thomas Wouters89f507f2006-12-13 04:49:30 +00003567/* End of the compiler section, beginning of the assembler section */
3568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569/* do depth-first search of basic block graph, starting with block.
3570 post records the block indices in post-order.
3571
3572 XXX must handle implicit jumps from one block to next
3573*/
3574
Thomas Wouters89f507f2006-12-13 04:49:30 +00003575struct assembler {
3576 PyObject *a_bytecode; /* string containing bytecode */
3577 int a_offset; /* offset into bytecode */
3578 int a_nblocks; /* number of reachable blocks */
3579 basicblock **a_postorder; /* list of blocks in dfs postorder */
3580 PyObject *a_lnotab; /* string containing lnotab */
3581 int a_lnotab_off; /* offset into lnotab */
3582 int a_lineno; /* last lineno of emitted instruction */
3583 int a_lineno_off; /* bytecode offset of last lineno */
3584};
3585
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586static void
3587dfs(struct compiler *c, basicblock *b, struct assembler *a)
3588{
3589 int i;
3590 struct instr *instr = NULL;
3591
3592 if (b->b_seen)
3593 return;
3594 b->b_seen = 1;
3595 if (b->b_next != NULL)
3596 dfs(c, b->b_next, a);
3597 for (i = 0; i < b->b_iused; i++) {
3598 instr = &b->b_instr[i];
3599 if (instr->i_jrel || instr->i_jabs)
3600 dfs(c, instr->i_target, a);
3601 }
3602 a->a_postorder[a->a_nblocks++] = b;
3603}
3604
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003605static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3607{
3608 int i;
3609 struct instr *instr;
3610 if (b->b_seen || b->b_startdepth >= depth)
3611 return maxdepth;
3612 b->b_seen = 1;
3613 b->b_startdepth = depth;
3614 for (i = 0; i < b->b_iused; i++) {
3615 instr = &b->b_instr[i];
3616 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3617 if (depth > maxdepth)
3618 maxdepth = depth;
3619 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3620 if (instr->i_jrel || instr->i_jabs) {
3621 maxdepth = stackdepth_walk(c, instr->i_target,
3622 depth, maxdepth);
3623 if (instr->i_opcode == JUMP_ABSOLUTE ||
3624 instr->i_opcode == JUMP_FORWARD) {
3625 goto out; /* remaining code is dead */
3626 }
3627 }
3628 }
3629 if (b->b_next)
3630 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3631out:
3632 b->b_seen = 0;
3633 return maxdepth;
3634}
3635
3636/* Find the flow path that needs the largest stack. We assume that
3637 * cycles in the flow graph have no net effect on the stack depth.
3638 */
3639static int
3640stackdepth(struct compiler *c)
3641{
3642 basicblock *b, *entryblock;
3643 entryblock = NULL;
3644 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3645 b->b_seen = 0;
3646 b->b_startdepth = INT_MIN;
3647 entryblock = b;
3648 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003649 if (!entryblock)
3650 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 return stackdepth_walk(c, entryblock, 0, 0);
3652}
3653
3654static int
3655assemble_init(struct assembler *a, int nblocks, int firstlineno)
3656{
3657 memset(a, 0, sizeof(struct assembler));
3658 a->a_lineno = firstlineno;
3659 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3660 if (!a->a_bytecode)
3661 return 0;
3662 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3663 if (!a->a_lnotab)
3664 return 0;
3665 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003666 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003667 if (!a->a_postorder) {
3668 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671 return 1;
3672}
3673
3674static void
3675assemble_free(struct assembler *a)
3676{
3677 Py_XDECREF(a->a_bytecode);
3678 Py_XDECREF(a->a_lnotab);
3679 if (a->a_postorder)
3680 PyObject_Free(a->a_postorder);
3681}
3682
3683/* Return the size of a basic block in bytes. */
3684
3685static int
3686instrsize(struct instr *instr)
3687{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003688 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003689 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003690 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003691 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3692 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003693}
3694
3695static int
3696blocksize(basicblock *b)
3697{
3698 int i;
3699 int size = 0;
3700
3701 for (i = 0; i < b->b_iused; i++)
3702 size += instrsize(&b->b_instr[i]);
3703 return size;
3704}
3705
3706/* All about a_lnotab.
3707
3708c_lnotab is an array of unsigned bytes disguised as a Python string.
3709It is used to map bytecode offsets to source code line #s (when needed
3710for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003711
Tim Peters2a7f3842001-06-09 09:26:21 +00003712The array is conceptually a list of
3713 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003714pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003715
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003716 byte code offset source code line number
3717 0 1
3718 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003719 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003720 350 307
3721 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003722
3723The first trick is that these numbers aren't stored, only the increments
3724from one row to the next (this doesn't really work, but it's a start):
3725
3726 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3727
3728The second trick is that an unsigned byte can't hold negative values, or
3729values larger than 255, so (a) there's a deep assumption that byte code
3730offsets and their corresponding line #s both increase monotonically, and (b)
3731if at least one column jumps by more than 255 from one row to the next, more
3732than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003733from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003734part. A user of c_lnotab desiring to find the source line number
3735corresponding to a bytecode address A should do something like this
3736
3737 lineno = addr = 0
3738 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003739 addr += addr_incr
3740 if addr > A:
3741 return lineno
3742 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003743
3744In order for this to work, when the addr field increments by more than 255,
3745the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003746increment is < 256. So, in the example above, assemble_lnotab (it used
3747to be called com_set_lineno) should not (as was actually done until 2.2)
3748expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003749 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003750*/
3751
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003752static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003754{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755 int d_bytecode, d_lineno;
3756 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003757 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758
3759 d_bytecode = a->a_offset - a->a_lineno_off;
3760 d_lineno = i->i_lineno - a->a_lineno;
3761
3762 assert(d_bytecode >= 0);
3763 assert(d_lineno >= 0);
3764
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003765 /* XXX(nnorwitz): is there a better way to handle this?
3766 for loops are special, we want to be able to trace them
3767 each time around, so we need to set an extra line number. */
3768 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003769 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003770
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003772 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 nbytes = a->a_lnotab_off + 2 * ncodes;
3774 len = PyString_GET_SIZE(a->a_lnotab);
3775 if (nbytes >= len) {
3776 if (len * 2 < nbytes)
3777 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003778 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779 len *= 2;
3780 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3781 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003782 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003783 lnotab = (unsigned char *)
3784 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003785 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 *lnotab++ = 255;
3787 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003788 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789 d_bytecode -= ncodes * 255;
3790 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003791 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792 assert(d_bytecode <= 255);
3793 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003794 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795 nbytes = a->a_lnotab_off + 2 * ncodes;
3796 len = PyString_GET_SIZE(a->a_lnotab);
3797 if (nbytes >= len) {
3798 if (len * 2 < nbytes)
3799 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003800 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801 len *= 2;
3802 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3803 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003804 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003805 lnotab = (unsigned char *)
3806 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003808 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003810 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003811 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003812 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003813 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 d_lineno -= ncodes * 255;
3815 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003816 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003817
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 len = PyString_GET_SIZE(a->a_lnotab);
3819 if (a->a_lnotab_off + 2 >= len) {
3820 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003821 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003822 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003823 lnotab = (unsigned char *)
3824 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003825
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826 a->a_lnotab_off += 2;
3827 if (d_bytecode) {
3828 *lnotab++ = d_bytecode;
3829 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003830 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003831 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832 *lnotab++ = 0;
3833 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003834 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 a->a_lineno = i->i_lineno;
3836 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003837 return 1;
3838}
3839
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840/* assemble_emit()
3841 Extend the bytecode with a new instruction.
3842 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003843*/
3844
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003845static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003847{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003848 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003849 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850 char *code;
3851
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003852 size = instrsize(i);
3853 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003855 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003858 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 if (a->a_offset + size >= len) {
3860 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003861 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003862 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3864 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003865 if (size == 6) {
3866 assert(i->i_hasarg);
3867 *code++ = (char)EXTENDED_ARG;
3868 *code++ = ext & 0xff;
3869 *code++ = ext >> 8;
3870 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003871 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003873 if (i->i_hasarg) {
3874 assert(size == 3 || size == 6);
3875 *code++ = arg & 0xff;
3876 *code++ = arg >> 8;
3877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003879}
3880
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003881static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003883{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003885 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003886 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 /* Compute the size of each block and fixup jump args.
3889 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003890start:
3891 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003892 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003893 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894 bsize = blocksize(b);
3895 b->b_offset = totsize;
3896 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003897 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003898 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3900 bsize = b->b_offset;
3901 for (i = 0; i < b->b_iused; i++) {
3902 struct instr *instr = &b->b_instr[i];
3903 /* Relative jumps are computed relative to
3904 the instruction pointer after fetching
3905 the jump instruction.
3906 */
3907 bsize += instrsize(instr);
3908 if (instr->i_jabs)
3909 instr->i_oparg = instr->i_target->b_offset;
3910 else if (instr->i_jrel) {
3911 int delta = instr->i_target->b_offset - bsize;
3912 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003913 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003914 else
3915 continue;
3916 if (instr->i_oparg > 0xffff)
3917 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003918 }
3919 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003920
3921 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003922 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003923 with a better solution.
3924
3925 In the meantime, should the goto be dropped in favor
3926 of a loop?
3927
3928 The issue is that in the first loop blocksize() is called
3929 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003930 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003931 i_oparg is calculated in the second loop above.
3932
3933 So we loop until we stop seeing new EXTENDED_ARGs.
3934 The only EXTENDED_ARGs that could be popping up are
3935 ones in jump instructions. So this should converge
3936 fairly quickly.
3937 */
3938 if (last_extended_arg_count != extended_arg_count) {
3939 last_extended_arg_count = extended_arg_count;
3940 goto start;
3941 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003942}
3943
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003944static PyObject *
3945dict_keys_inorder(PyObject *dict, int offset)
3946{
3947 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003948 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003949
3950 tuple = PyTuple_New(size);
3951 if (tuple == NULL)
3952 return NULL;
3953 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003954 i = PyLong_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003955 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003956 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003957 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003958 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003959 PyTuple_SET_ITEM(tuple, i - offset, k);
3960 }
3961 return tuple;
3962}
3963
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003964static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003965compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003966{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003967 PySTEntryObject *ste = c->u->u_ste;
3968 int flags = 0, n;
3969 if (ste->ste_type != ModuleBlock)
3970 flags |= CO_NEWLOCALS;
3971 if (ste->ste_type == FunctionBlock) {
3972 if (!ste->ste_unoptimized)
3973 flags |= CO_OPTIMIZED;
3974 if (ste->ste_nested)
3975 flags |= CO_NESTED;
3976 if (ste->ste_generator)
3977 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003978 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003979 if (ste->ste_varargs)
3980 flags |= CO_VARARGS;
3981 if (ste->ste_varkeywords)
3982 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003983 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003984 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003985
3986 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003987 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003988
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003989 n = PyDict_Size(c->u->u_freevars);
3990 if (n < 0)
3991 return -1;
3992 if (n == 0) {
3993 n = PyDict_Size(c->u->u_cellvars);
3994 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003995 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003996 if (n == 0) {
3997 flags |= CO_NOFREE;
3998 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003999 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004000
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004001 return flags;
4002}
4003
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004004static PyCodeObject *
4005makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004006{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004007 PyObject *tmp;
4008 PyCodeObject *co = NULL;
4009 PyObject *consts = NULL;
4010 PyObject *names = NULL;
4011 PyObject *varnames = NULL;
4012 PyObject *filename = NULL;
4013 PyObject *name = NULL;
4014 PyObject *freevars = NULL;
4015 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004016 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004018
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004019 tmp = dict_keys_inorder(c->u->u_consts, 0);
4020 if (!tmp)
4021 goto error;
4022 consts = PySequence_List(tmp); /* optimize_code requires a list */
4023 Py_DECREF(tmp);
4024
4025 names = dict_keys_inorder(c->u->u_names, 0);
4026 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4027 if (!consts || !names || !varnames)
4028 goto error;
4029
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004030 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4031 if (!cellvars)
4032 goto error;
4033 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4034 if (!freevars)
4035 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004036 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004037 if (!filename)
4038 goto error;
4039
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004040 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004041 flags = compute_code_flags(c);
4042 if (flags < 0)
4043 goto error;
4044
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004045 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004046 if (!bytecode)
4047 goto error;
4048
4049 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4050 if (!tmp)
4051 goto error;
4052 Py_DECREF(consts);
4053 consts = tmp;
4054
Guido van Rossum4f72a782006-10-27 23:31:49 +00004055 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4056 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057 bytecode, consts, names, varnames,
4058 freevars, cellvars,
4059 filename, c->u->u_name,
4060 c->u->u_firstlineno,
4061 a->a_lnotab);
4062 error:
4063 Py_XDECREF(consts);
4064 Py_XDECREF(names);
4065 Py_XDECREF(varnames);
4066 Py_XDECREF(filename);
4067 Py_XDECREF(name);
4068 Py_XDECREF(freevars);
4069 Py_XDECREF(cellvars);
4070 Py_XDECREF(bytecode);
4071 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004072}
4073
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004074
4075/* For debugging purposes only */
4076#if 0
4077static void
4078dump_instr(const struct instr *i)
4079{
4080 const char *jrel = i->i_jrel ? "jrel " : "";
4081 const char *jabs = i->i_jabs ? "jabs " : "";
4082 char arg[128];
4083
4084 *arg = '\0';
4085 if (i->i_hasarg)
4086 sprintf(arg, "arg: %d ", i->i_oparg);
4087
4088 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4089 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4090}
4091
4092static void
4093dump_basicblock(const basicblock *b)
4094{
4095 const char *seen = b->b_seen ? "seen " : "";
4096 const char *b_return = b->b_return ? "return " : "";
4097 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4098 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4099 if (b->b_instr) {
4100 int i;
4101 for (i = 0; i < b->b_iused; i++) {
4102 fprintf(stderr, " [%02d] ", i);
4103 dump_instr(b->b_instr + i);
4104 }
4105 }
4106}
4107#endif
4108
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109static PyCodeObject *
4110assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004111{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004112 basicblock *b, *entryblock;
4113 struct assembler a;
4114 int i, j, nblocks;
4115 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004116
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117 /* Make sure every block that falls off the end returns None.
4118 XXX NEXT_BLOCK() isn't quite right, because if the last
4119 block ends with a jump or return b_next shouldn't set.
4120 */
4121 if (!c->u->u_curblock->b_return) {
4122 NEXT_BLOCK(c);
4123 if (addNone)
4124 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4125 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004126 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004127
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128 nblocks = 0;
4129 entryblock = NULL;
4130 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4131 nblocks++;
4132 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004133 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004134
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004135 /* Set firstlineno if it wasn't explicitly set. */
4136 if (!c->u->u_firstlineno) {
4137 if (entryblock && entryblock->b_instr)
4138 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4139 else
4140 c->u->u_firstlineno = 1;
4141 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004142 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4143 goto error;
4144 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004147 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004149 /* Emit code in reverse postorder from dfs. */
4150 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004151 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152 for (j = 0; j < b->b_iused; j++)
4153 if (!assemble_emit(&a, &b->b_instr[j]))
4154 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004155 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4158 goto error;
4159 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4160 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 co = makecode(c, &a);
4163 error:
4164 assemble_free(&a);
4165 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004166}