blob: 1ddec2c54ddc27d9f71b96d2984f1cbbb8b6f331 [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
45
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000047 unsigned i_jabs : 1;
48 unsigned i_jrel : 1;
49 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 /* Each basicblock in a compilation unit is linked via b_list in the
58 reverse order that the block are allocated. b_list points to the next
59 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060 struct basicblock_ *b_list;
61 /* number of instructions used */
62 int b_iused;
63 /* length of instruction array (b_instr) */
64 int b_ialloc;
65 /* pointer to an array of instructions, initially NULL */
66 struct instr *b_instr;
67 /* If b_next is non-NULL, it is a pointer to the next
68 block reached by normal control flow. */
69 struct basicblock_ *b_next;
70 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000071 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000072 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000073 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074 /* depth of stack upon entry of block, computed by stackdepth() */
75 int b_startdepth;
76 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000077 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078} basicblock;
79
80/* fblockinfo tracks the current frame block.
81
Jeremy Hyltone9357b22006-03-01 15:47:05 +000082A frame block is used to handle loops, try/except, and try/finally.
83It's called a frame block to distinguish it from a basic block in the
84compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085*/
86
87enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
88
89struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000090 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091 basicblock *fb_block;
92};
93
94/* The following items change on entry and exit of code blocks.
95 They must be saved and restored when returning to a block.
96*/
97struct compiler_unit {
98 PySTEntryObject *u_ste;
99
100 PyObject *u_name;
101 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000102 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103 the argument for opcodes that refer to those collections.
104 */
105 PyObject *u_consts; /* all constants */
106 PyObject *u_names; /* all names */
107 PyObject *u_varnames; /* local variables */
108 PyObject *u_cellvars; /* cell variables */
109 PyObject *u_freevars; /* free variables */
110
111 PyObject *u_private; /* for private name mangling */
112
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000113 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000114 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000115 /* Pointer to the most recently allocated block. By following b_list
116 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000117 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000119 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
121 int u_nfblocks;
122 struct fblockinfo u_fblock[CO_MAXBLOCKS];
123
124 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000125 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000126 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127 has been generated with current lineno */
128};
129
130/* This struct captures the global state of a compilation.
131
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000132The u pointer points to the current compilation unit, while units
133for enclosing blocks are stored in c_stack. The u and c_stack are
134managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135*/
136
137struct compiler {
138 const char *c_filename;
139 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141 PyCompilerFlags *c_flags;
142
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146 struct compiler_unit *u; /* compiler state for current block */
147 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150};
151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152static int compiler_enter_scope(struct compiler *, identifier, void *, int);
153static void compiler_free(struct compiler *);
154static basicblock *compiler_new_block(struct compiler *);
155static int compiler_next_instr(struct compiler *, basicblock *);
156static int compiler_addop(struct compiler *, int);
157static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
158static int compiler_addop_i(struct compiler *, int, int);
159static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160static basicblock *compiler_use_new_block(struct compiler *);
161static int compiler_error(struct compiler *, const char *);
162static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
163
164static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
165static int compiler_visit_stmt(struct compiler *, stmt_ty);
166static int compiler_visit_keyword(struct compiler *, keyword_ty);
167static int compiler_visit_expr(struct compiler *, expr_ty);
168static int compiler_augassign(struct compiler *, stmt_ty);
169static int compiler_visit_slice(struct compiler *, slice_ty,
170 expr_context_ty);
171
172static int compiler_push_fblock(struct compiler *, enum fblocktype,
173 basicblock *);
174static void compiler_pop_fblock(struct compiler *, enum fblocktype,
175 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176/* Returns true if there is a loop on the fblock stack. */
177static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178
179static int inplace_binop(struct compiler *, operator_ty);
180static int expr_constant(expr_ty e);
181
Guido van Rossumc2e20742006-02-27 22:32:47 +0000182static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000183static int compiler_call_helper(struct compiler *c, int n,
184 asdl_seq *args,
185 asdl_seq *keywords,
186 expr_ty starargs,
187 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000188
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static PyCodeObject *assemble(struct compiler *, int addNone);
190static PyObject *__doc__;
191
192PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000194{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195 /* Name mangling: __private becomes _classname__private.
196 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000197 const char *p, *name = PyString_AsString(ident);
198 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000200 if (privateobj == NULL || !PyString_Check(privateobj) ||
201 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000202 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000205 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 nlen = strlen(name);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000207 /* Don't mangle __id__ or names with dots.
208
209 The only time a name with a dot can occur is when
210 we are compiling an import statement that has a
211 package name.
212
213 TODO(jhylton): Decide whether we want to support
214 mangling of the module name, e.g. __M.X.
215 */
216 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
217 || strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000218 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000219 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221 /* Strip leading underscores from class name */
222 while (*p == '_')
223 p++;
224 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000225 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000227 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000229 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
230 if (!ident)
231 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000233 buffer = PyString_AS_STRING(ident);
234 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235 strncpy(buffer+1, p, plen);
236 strcpy(buffer+1+plen, name);
237 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000238}
239
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240static int
241compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000242{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000243 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245 c->c_stack = PyList_New(0);
246 if (!c->c_stack)
247 return 0;
248
249 return 1;
250}
251
252PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000253PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000254 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255{
256 struct compiler c;
257 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000258 PyCompilerFlags local_flags;
259 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000261 if (!__doc__) {
262 __doc__ = PyString_InternFromString("__doc__");
263 if (!__doc__)
264 return NULL;
265 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266
267 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000268 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000269 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000270 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271 c.c_future = PyFuture_FromAST(mod, filename);
272 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000273 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000274 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000275 local_flags.cf_flags = 0;
276 flags = &local_flags;
277 }
278 merged = c.c_future->ff_features | flags->cf_flags;
279 c.c_future->ff_features = merged;
280 flags->cf_flags = merged;
281 c.c_flags = flags;
282 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283
284 c.c_st = PySymtable_Build(mod, filename, c.c_future);
285 if (c.c_st == NULL) {
286 if (!PyErr_Occurred())
287 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000288 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289 }
290
291 /* XXX initialize to NULL for now, need to handle */
292 c.c_encoding = NULL;
293
294 co = compiler_mod(&c, mod);
295
Thomas Wouters1175c432006-02-27 22:49:54 +0000296 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000298 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299 return co;
300}
301
302PyCodeObject *
303PyNode_Compile(struct _node *n, const char *filename)
304{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000305 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000306 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000307 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000308 if (!arena)
309 return NULL;
310 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000311 if (mod)
312 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000313 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000314 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000315}
316
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000317static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000319{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320 if (c->c_st)
321 PySymtable_Free(c->c_st);
322 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000323 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000325}
326
Guido van Rossum79f25d91997-04-29 20:08:16 +0000327static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000328list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000329{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000330 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000331 PyObject *v, *k;
332 PyObject *dict = PyDict_New();
333 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000334
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000335 n = PyList_Size(list);
336 for (i = 0; i < n; i++) {
337 v = PyInt_FromLong(i);
338 if (!v) {
339 Py_DECREF(dict);
340 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000341 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000342 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000343 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
345 Py_XDECREF(k);
346 Py_DECREF(v);
347 Py_DECREF(dict);
348 return NULL;
349 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000350 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353 return dict;
354}
355
356/* Return new dict containing names from src that match scope(s).
357
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000358src is a symbol table dictionary. If the scope of a name matches
359either scope_type or flag is set, insert it into the new dict. The
360values are integers, starting at offset and increasing by one for
361each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362*/
363
364static PyObject *
365dictbytype(PyObject *src, int scope_type, int flag, int offset)
366{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368 PyObject *k, *v, *dest = PyDict_New();
369
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000370 assert(offset >= 0);
371 if (dest == NULL)
372 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000373
374 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000375 /* XXX this should probably be a macro in symtable.h */
376 assert(PyInt_Check(v));
Nick Coghlan650f0d02007-04-15 12:05:43 +0000377 scope = (PyInt_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000379 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
380 PyObject *tuple, *item = PyInt_FromLong(i);
381 if (item == NULL) {
382 Py_DECREF(dest);
383 return NULL;
384 }
385 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000386 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000387 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
388 Py_DECREF(item);
389 Py_DECREF(dest);
390 Py_XDECREF(tuple);
391 return NULL;
392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000394 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396 }
397 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000398}
399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400static void
401compiler_unit_check(struct compiler_unit *u)
402{
403 basicblock *block;
404 for (block = u->u_blocks; block != NULL; block = block->b_list) {
405 assert(block != (void *)0xcbcbcbcb);
406 assert(block != (void *)0xfbfbfbfb);
407 assert(block != (void *)0xdbdbdbdb);
408 if (block->b_instr != NULL) {
409 assert(block->b_ialloc > 0);
410 assert(block->b_iused > 0);
411 assert(block->b_ialloc >= block->b_iused);
412 }
413 else {
414 assert (block->b_iused == 0);
415 assert (block->b_ialloc == 0);
416 }
417 }
418}
419
420static void
421compiler_unit_free(struct compiler_unit *u)
422{
423 basicblock *b, *next;
424
425 compiler_unit_check(u);
426 b = u->u_blocks;
427 while (b != NULL) {
428 if (b->b_instr)
429 PyObject_Free((void *)b->b_instr);
430 next = b->b_list;
431 PyObject_Free((void *)b);
432 b = next;
433 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000434 Py_CLEAR(u->u_ste);
435 Py_CLEAR(u->u_name);
436 Py_CLEAR(u->u_consts);
437 Py_CLEAR(u->u_names);
438 Py_CLEAR(u->u_varnames);
439 Py_CLEAR(u->u_freevars);
440 Py_CLEAR(u->u_cellvars);
441 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000442 PyObject_Free(u);
443}
444
445static int
446compiler_enter_scope(struct compiler *c, identifier name, void *key,
447 int lineno)
448{
449 struct compiler_unit *u;
450
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000451 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000453 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000454 PyErr_NoMemory();
455 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000456 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000459 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460 u->u_ste = PySymtable_Lookup(c->c_st, key);
461 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000462 compiler_unit_free(u);
463 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464 }
465 Py_INCREF(name);
466 u->u_name = name;
467 u->u_varnames = list2dict(u->u_ste->ste_varnames);
468 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000469 if (!u->u_varnames || !u->u_cellvars) {
470 compiler_unit_free(u);
471 return 0;
472 }
473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000475 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000476 if (!u->u_freevars) {
477 compiler_unit_free(u);
478 return 0;
479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480
481 u->u_blocks = NULL;
482 u->u_tmpname = 0;
483 u->u_nfblocks = 0;
484 u->u_firstlineno = lineno;
485 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000486 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487 u->u_consts = PyDict_New();
488 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000489 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490 return 0;
491 }
492 u->u_names = PyDict_New();
493 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000494 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000495 return 0;
496 }
497
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499
500 /* Push the old compiler_unit on the stack. */
501 if (c->u) {
502 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000503 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
504 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000505 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000506 return 0;
507 }
508 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000509 u->u_private = c->u->u_private;
510 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511 }
512 c->u = u;
513
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000514 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000515 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516 return 0;
517
518 return 1;
519}
520
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000521static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000522compiler_exit_scope(struct compiler *c)
523{
524 int n;
525 PyObject *wrapper;
526
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000527 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000528 compiler_unit_free(c->u);
529 /* Restore c->u to the parent unit. */
530 n = PyList_GET_SIZE(c->c_stack) - 1;
531 if (n >= 0) {
532 wrapper = PyList_GET_ITEM(c->c_stack, n);
533 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000534 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000535 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000537 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538 compiler_unit_check(c->u);
539 }
540 else
541 c->u = NULL;
542
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543}
544
Guido van Rossumc2e20742006-02-27 22:32:47 +0000545/* Allocate a new "anonymous" local variable.
546 Used by list comprehensions and with statements.
547*/
548
549static PyObject *
550compiler_new_tmpname(struct compiler *c)
551{
552 char tmpname[256];
553 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
554 return PyString_FromString(tmpname);
555}
556
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000557/* Allocate a new block and return a pointer to it.
558 Returns NULL on error.
559*/
560
561static basicblock *
562compiler_new_block(struct compiler *c)
563{
564 basicblock *b;
565 struct compiler_unit *u;
566
567 u = c->u;
568 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000569 if (b == NULL) {
570 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000571 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000572 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000574 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575 b->b_list = u->u_blocks;
576 u->u_blocks = b;
577 return b;
578}
579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580static basicblock *
581compiler_use_new_block(struct compiler *c)
582{
583 basicblock *block = compiler_new_block(c);
584 if (block == NULL)
585 return NULL;
586 c->u->u_curblock = block;
587 return block;
588}
589
590static basicblock *
591compiler_next_block(struct compiler *c)
592{
593 basicblock *block = compiler_new_block(c);
594 if (block == NULL)
595 return NULL;
596 c->u->u_curblock->b_next = block;
597 c->u->u_curblock = block;
598 return block;
599}
600
601static basicblock *
602compiler_use_next_block(struct compiler *c, basicblock *block)
603{
604 assert(block != NULL);
605 c->u->u_curblock->b_next = block;
606 c->u->u_curblock = block;
607 return block;
608}
609
610/* Returns the offset of the next instruction in the current block's
611 b_instr array. Resizes the b_instr as necessary.
612 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000613*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000614
615static int
616compiler_next_instr(struct compiler *c, basicblock *b)
617{
618 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000619 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000620 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000621 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622 if (b->b_instr == NULL) {
623 PyErr_NoMemory();
624 return -1;
625 }
626 b->b_ialloc = DEFAULT_BLOCK_SIZE;
627 memset((char *)b->b_instr, 0,
628 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000629 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000630 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000631 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632 size_t oldsize, newsize;
633 oldsize = b->b_ialloc * sizeof(struct instr);
634 newsize = oldsize << 1;
635 if (newsize == 0) {
636 PyErr_NoMemory();
637 return -1;
638 }
639 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000640 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000642 if (tmp == NULL) {
643 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645 }
646 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
648 }
649 return b->b_iused++;
650}
651
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000652/* Set the i_lineno member of the instruction at offse off if the
653 line number for the current expression/statement (?) has not
654 already been set. If it has been set, the call has no effect.
655
656 Every time a new node is b
Thomas Wouters89f507f2006-12-13 04:49:30 +0000657*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000658
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659static void
660compiler_set_lineno(struct compiler *c, int off)
661{
662 basicblock *b;
663 if (c->u->u_lineno_set)
664 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000665 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000667 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668}
669
670static int
671opcode_stack_effect(int opcode, int oparg)
672{
673 switch (opcode) {
674 case POP_TOP:
675 return -1;
676 case ROT_TWO:
677 case ROT_THREE:
678 return 0;
679 case DUP_TOP:
680 return 1;
681 case ROT_FOUR:
682 return 0;
683
684 case UNARY_POSITIVE:
685 case UNARY_NEGATIVE:
686 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000687 case UNARY_INVERT:
688 return 0;
689
Nick Coghlan650f0d02007-04-15 12:05:43 +0000690 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000691 case LIST_APPEND:
692 return -2;
693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694 case BINARY_POWER:
695 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696 case BINARY_MODULO:
697 case BINARY_ADD:
698 case BINARY_SUBTRACT:
699 case BINARY_SUBSCR:
700 case BINARY_FLOOR_DIVIDE:
701 case BINARY_TRUE_DIVIDE:
702 return -1;
703 case INPLACE_FLOOR_DIVIDE:
704 case INPLACE_TRUE_DIVIDE:
705 return -1;
706
707 case SLICE+0:
708 return 1;
709 case SLICE+1:
710 return 0;
711 case SLICE+2:
712 return 0;
713 case SLICE+3:
714 return -1;
715
716 case STORE_SLICE+0:
717 return -2;
718 case STORE_SLICE+1:
719 return -3;
720 case STORE_SLICE+2:
721 return -3;
722 case STORE_SLICE+3:
723 return -4;
724
725 case DELETE_SLICE+0:
726 return -1;
727 case DELETE_SLICE+1:
728 return -2;
729 case DELETE_SLICE+2:
730 return -2;
731 case DELETE_SLICE+3:
732 return -3;
733
734 case INPLACE_ADD:
735 case INPLACE_SUBTRACT:
736 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737 case INPLACE_MODULO:
738 return -1;
739 case STORE_SUBSCR:
740 return -3;
741 case DELETE_SUBSCR:
742 return -2;
743
744 case BINARY_LSHIFT:
745 case BINARY_RSHIFT:
746 case BINARY_AND:
747 case BINARY_XOR:
748 case BINARY_OR:
749 return -1;
750 case INPLACE_POWER:
751 return -1;
752 case GET_ITER:
753 return 0;
754
755 case PRINT_EXPR:
756 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000757 case LOAD_BUILD_CLASS:
758 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000759 case INPLACE_LSHIFT:
760 case INPLACE_RSHIFT:
761 case INPLACE_AND:
762 case INPLACE_XOR:
763 case INPLACE_OR:
764 return -1;
765 case BREAK_LOOP:
766 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000767 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000768 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000769 case STORE_LOCALS:
770 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000771 case RETURN_VALUE:
772 return -1;
773 case IMPORT_STAR:
774 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775 case YIELD_VALUE:
776 return 0;
777
778 case POP_BLOCK:
779 return 0;
780 case END_FINALLY:
781 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782
783 case STORE_NAME:
784 return -1;
785 case DELETE_NAME:
786 return 0;
787 case UNPACK_SEQUENCE:
788 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000789 case UNPACK_EX:
790 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791 case FOR_ITER:
792 return 1;
793
794 case STORE_ATTR:
795 return -2;
796 case DELETE_ATTR:
797 return -1;
798 case STORE_GLOBAL:
799 return -1;
800 case DELETE_GLOBAL:
801 return 0;
802 case DUP_TOPX:
803 return oparg;
804 case LOAD_CONST:
805 return 1;
806 case LOAD_NAME:
807 return 1;
808 case BUILD_TUPLE:
809 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000810 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000811 return 1-oparg;
812 case BUILD_MAP:
813 return 1;
Thomas Wouters00e41de2007-02-23 19:56:57 +0000814 case MAKE_BYTES:
815 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816 case LOAD_ATTR:
817 return 0;
818 case COMPARE_OP:
819 return -1;
820 case IMPORT_NAME:
821 return 0;
822 case IMPORT_FROM:
823 return 1;
824
825 case JUMP_FORWARD:
826 case JUMP_IF_FALSE:
827 case JUMP_IF_TRUE:
828 case JUMP_ABSOLUTE:
829 return 0;
830
831 case LOAD_GLOBAL:
832 return 1;
833
834 case CONTINUE_LOOP:
835 return 0;
836 case SETUP_LOOP:
837 return 0;
838 case SETUP_EXCEPT:
839 case SETUP_FINALLY:
840 return 3; /* actually pushed by an exception */
841
842 case LOAD_FAST:
843 return 1;
844 case STORE_FAST:
845 return -1;
846 case DELETE_FAST:
847 return 0;
848
849 case RAISE_VARARGS:
850 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000851#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852 case CALL_FUNCTION:
853 return -NARGS(oparg);
854 case CALL_FUNCTION_VAR:
855 case CALL_FUNCTION_KW:
856 return -NARGS(oparg)-1;
857 case CALL_FUNCTION_VAR_KW:
858 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000860 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000861 case MAKE_CLOSURE:
862 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000863#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864 case BUILD_SLICE:
865 if (oparg == 3)
866 return -2;
867 else
868 return -1;
869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870 case LOAD_CLOSURE:
871 return 1;
872 case LOAD_DEREF:
873 return 1;
874 case STORE_DEREF:
875 return -1;
876 default:
877 fprintf(stderr, "opcode = %d\n", opcode);
878 Py_FatalError("opcode_stack_effect()");
879
880 }
881 return 0; /* not reachable */
882}
883
884/* Add an opcode with no argument.
885 Returns 0 on failure, 1 on success.
886*/
887
888static int
889compiler_addop(struct compiler *c, int opcode)
890{
891 basicblock *b;
892 struct instr *i;
893 int off;
894 off = compiler_next_instr(c, c->u->u_curblock);
895 if (off < 0)
896 return 0;
897 b = c->u->u_curblock;
898 i = &b->b_instr[off];
899 i->i_opcode = opcode;
900 i->i_hasarg = 0;
901 if (opcode == RETURN_VALUE)
902 b->b_return = 1;
903 compiler_set_lineno(c, off);
904 return 1;
905}
906
907static int
908compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
909{
910 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000911 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000913 /* necessary to make sure types aren't coerced (e.g., int and long) */
914 t = PyTuple_Pack(2, o, o->ob_type);
915 if (t == NULL)
916 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
918 v = PyDict_GetItem(dict, t);
919 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000920 if (PyErr_Occurred())
921 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000922 arg = PyDict_Size(dict);
923 v = PyInt_FromLong(arg);
924 if (!v) {
925 Py_DECREF(t);
926 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000927 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000928 if (PyDict_SetItem(dict, t, v) < 0) {
929 Py_DECREF(t);
930 Py_DECREF(v);
931 return -1;
932 }
933 Py_DECREF(v);
934 }
935 else
936 arg = PyInt_AsLong(v);
937 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000938 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000939}
940
941static int
942compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
943 PyObject *o)
944{
945 int arg = compiler_add_o(c, dict, o);
946 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000947 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948 return compiler_addop_i(c, opcode, arg);
949}
950
951static int
952compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000953 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954{
955 int arg;
956 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
957 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000958 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959 arg = compiler_add_o(c, dict, mangled);
960 Py_DECREF(mangled);
961 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000962 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963 return compiler_addop_i(c, opcode, arg);
964}
965
966/* Add an opcode with an integer argument.
967 Returns 0 on failure, 1 on success.
968*/
969
970static int
971compiler_addop_i(struct compiler *c, int opcode, int oparg)
972{
973 struct instr *i;
974 int off;
975 off = compiler_next_instr(c, c->u->u_curblock);
976 if (off < 0)
977 return 0;
978 i = &c->u->u_curblock->b_instr[off];
979 i->i_opcode = opcode;
980 i->i_oparg = oparg;
981 i->i_hasarg = 1;
982 compiler_set_lineno(c, off);
983 return 1;
984}
985
986static int
987compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
988{
989 struct instr *i;
990 int off;
991
992 assert(b != NULL);
993 off = compiler_next_instr(c, c->u->u_curblock);
994 if (off < 0)
995 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000996 i = &c->u->u_curblock->b_instr[off];
997 i->i_opcode = opcode;
998 i->i_target = b;
999 i->i_hasarg = 1;
1000 if (absolute)
1001 i->i_jabs = 1;
1002 else
1003 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001004 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005 return 1;
1006}
1007
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001008/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1009 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010 it as the current block. NEXT_BLOCK() also creates an implicit jump
1011 from the current block to the new block.
1012*/
1013
Thomas Wouters89f507f2006-12-13 04:49:30 +00001014/* The returns inside these macros make it impossible to decref objects
1015 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016*/
1017
1018
1019#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001020 if (compiler_use_new_block((C)) == NULL) \
1021 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022}
1023
1024#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001025 if (compiler_next_block((C)) == NULL) \
1026 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027}
1028
1029#define ADDOP(C, OP) { \
1030 if (!compiler_addop((C), (OP))) \
1031 return 0; \
1032}
1033
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001034#define ADDOP_IN_SCOPE(C, OP) { \
1035 if (!compiler_addop((C), (OP))) { \
1036 compiler_exit_scope(c); \
1037 return 0; \
1038 } \
1039}
1040
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041#define ADDOP_O(C, OP, O, TYPE) { \
1042 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1043 return 0; \
1044}
1045
1046#define ADDOP_NAME(C, OP, O, TYPE) { \
1047 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1048 return 0; \
1049}
1050
1051#define ADDOP_I(C, OP, O) { \
1052 if (!compiler_addop_i((C), (OP), (O))) \
1053 return 0; \
1054}
1055
1056#define ADDOP_JABS(C, OP, O) { \
1057 if (!compiler_addop_j((C), (OP), (O), 1)) \
1058 return 0; \
1059}
1060
1061#define ADDOP_JREL(C, OP, O) { \
1062 if (!compiler_addop_j((C), (OP), (O), 0)) \
1063 return 0; \
1064}
1065
1066/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1067 the ASDL name to synthesize the name of the C type and the visit function.
1068*/
1069
1070#define VISIT(C, TYPE, V) {\
1071 if (!compiler_visit_ ## TYPE((C), (V))) \
1072 return 0; \
1073}
1074
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001075#define VISIT_IN_SCOPE(C, TYPE, V) {\
1076 if (!compiler_visit_ ## TYPE((C), (V))) { \
1077 compiler_exit_scope(c); \
1078 return 0; \
1079 } \
1080}
1081
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082#define VISIT_SLICE(C, V, CTX) {\
1083 if (!compiler_visit_slice((C), (V), (CTX))) \
1084 return 0; \
1085}
1086
1087#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001088 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001090 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001091 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092 if (!compiler_visit_ ## TYPE((C), elt)) \
1093 return 0; \
1094 } \
1095}
1096
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001097#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001098 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001099 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001100 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001101 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001102 if (!compiler_visit_ ## TYPE((C), elt)) { \
1103 compiler_exit_scope(c); \
1104 return 0; \
1105 } \
1106 } \
1107}
1108
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109static int
1110compiler_isdocstring(stmt_ty s)
1111{
1112 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001113 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114 return s->v.Expr.value->kind == Str_kind;
1115}
1116
1117/* Compile a sequence of statements, checking for a docstring. */
1118
1119static int
1120compiler_body(struct compiler *c, asdl_seq *stmts)
1121{
1122 int i = 0;
1123 stmt_ty st;
1124
1125 if (!asdl_seq_LEN(stmts))
1126 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001127 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128 if (compiler_isdocstring(st)) {
1129 i = 1;
1130 VISIT(c, expr, st->v.Expr.value);
1131 if (!compiler_nameop(c, __doc__, Store))
1132 return 0;
1133 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001134 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001135 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136 return 1;
1137}
1138
1139static PyCodeObject *
1140compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001141{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001142 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001143 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144 static PyObject *module;
1145 if (!module) {
1146 module = PyString_FromString("<module>");
1147 if (!module)
1148 return NULL;
1149 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001150 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1151 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001152 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 switch (mod->kind) {
1154 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001155 if (!compiler_body(c, mod->v.Module.body)) {
1156 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001158 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 break;
1160 case Interactive_kind:
1161 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001162 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164 break;
1165 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001166 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001167 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 break;
1169 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001170 PyErr_SetString(PyExc_SystemError,
1171 "suite should not be possible");
1172 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001173 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001174 PyErr_Format(PyExc_SystemError,
1175 "module kind %d should not be possible",
1176 mod->kind);
1177 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001178 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179 co = assemble(c, addNone);
1180 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001181 return co;
1182}
1183
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184/* The test for LOCAL must come before the test for FREE in order to
1185 handle classes where name is both local and free. The local var is
1186 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001187*/
1188
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189static int
1190get_ref_type(struct compiler *c, PyObject *name)
1191{
1192 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001193 if (scope == 0) {
1194 char buf[350];
1195 PyOS_snprintf(buf, sizeof(buf),
1196 "unknown scope for %.100s in %.100s(%s) in %s\n"
1197 "symbols: %s\nlocals: %s\nglobals: %s\n",
1198 PyString_AS_STRING(name),
1199 PyString_AS_STRING(c->u->u_name),
1200 PyObject_REPR(c->u->u_ste->ste_id),
1201 c->c_filename,
1202 PyObject_REPR(c->u->u_ste->ste_symbols),
1203 PyObject_REPR(c->u->u_varnames),
1204 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001206 Py_FatalError(buf);
1207 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001208
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210}
1211
1212static int
1213compiler_lookup_arg(PyObject *dict, PyObject *name)
1214{
1215 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001218 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001220 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001222 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223 return PyInt_AS_LONG(v);
1224}
1225
1226static int
1227compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1228{
1229 int i, free = PyCode_GetNumFree(co);
1230 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001231 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1232 ADDOP_I(c, MAKE_FUNCTION, args);
1233 return 1;
1234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235 for (i = 0; i < free; ++i) {
1236 /* Bypass com_addop_varname because it will generate
1237 LOAD_DEREF but LOAD_CLOSURE is needed.
1238 */
1239 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1240 int arg, reftype;
1241
1242 /* Special case: If a class contains a method with a
1243 free variable that has the same name as a method,
1244 the name will be considered free *and* local in the
1245 class. It should be handled by the closure, as
1246 well as by the normal name loookup logic.
1247 */
1248 reftype = get_ref_type(c, name);
1249 if (reftype == CELL)
1250 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1251 else /* (reftype == FREE) */
1252 arg = compiler_lookup_arg(c->u->u_freevars, name);
1253 if (arg == -1) {
1254 printf("lookup %s in %s %d %d\n"
1255 "freevars of %s: %s\n",
1256 PyObject_REPR(name),
1257 PyString_AS_STRING(c->u->u_name),
1258 reftype, arg,
1259 PyString_AS_STRING(co->co_name),
1260 PyObject_REPR(co->co_freevars));
1261 Py_FatalError("compiler_make_closure()");
1262 }
1263 ADDOP_I(c, LOAD_CLOSURE, arg);
1264 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001265 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001267 ADDOP_I(c, MAKE_CLOSURE, args);
1268 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269}
1270
1271static int
1272compiler_decorators(struct compiler *c, asdl_seq* decos)
1273{
1274 int i;
1275
1276 if (!decos)
1277 return 1;
1278
1279 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001280 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281 }
1282 return 1;
1283}
1284
1285static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001286compiler_unpack_nested(struct compiler *c, asdl_seq *args) {
1287 int i, len;
1288 len = asdl_seq_LEN(args);
1289 ADDOP_I(c, UNPACK_SEQUENCE, len);
1290 for (i = 0; i < len; i++) {
1291 arg_ty elt = (arg_ty)asdl_seq_GET(args, i);
1292 switch (elt->kind) {
1293 case SimpleArg_kind:
1294 if (!compiler_nameop(c, elt->v.SimpleArg.arg, Store))
1295 return 0;
1296 break;
1297 case NestedArgs_kind:
1298 if (!compiler_unpack_nested(c, elt->v.NestedArgs.args))
1299 return 0;
1300 break;
1301 default:
1302 return 0;
1303 }
1304 }
1305 return 1;
1306}
1307
1308static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309compiler_arguments(struct compiler *c, arguments_ty args)
1310{
1311 int i;
1312 int n = asdl_seq_LEN(args->args);
Neal Norwitzc1505362006-12-28 06:47:50 +00001313
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314 for (i = 0; i < n; i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001315 arg_ty arg = (arg_ty)asdl_seq_GET(args->args, i);
1316 if (arg->kind == NestedArgs_kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317 PyObject *id = PyString_FromFormat(".%d", i);
1318 if (id == NULL) {
1319 return 0;
1320 }
1321 if (!compiler_nameop(c, id, Load)) {
1322 Py_DECREF(id);
1323 return 0;
1324 }
1325 Py_DECREF(id);
Neal Norwitzc1505362006-12-28 06:47:50 +00001326 if (!compiler_unpack_nested(c, arg->v.NestedArgs.args))
1327 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328 }
1329 }
1330 return 1;
1331}
1332
1333static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001334compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1335 asdl_seq *kw_defaults)
1336{
1337 int i, default_count = 0;
1338 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001339 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001340 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1341 if (default_) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001342 ADDOP_O(c, LOAD_CONST, arg->v.SimpleArg.arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001343 if (!compiler_visit_expr(c, default_)) {
1344 return -1;
1345 }
1346 default_count++;
1347 }
1348 }
1349 return default_count;
1350}
1351
1352static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001353compiler_visit_argannotation(struct compiler *c, identifier id,
1354 expr_ty annotation, PyObject *names)
1355{
1356 if (annotation) {
1357 VISIT(c, expr, annotation);
1358 if (PyList_Append(names, id))
1359 return -1;
1360 }
1361 return 0;
1362}
1363
1364static int
1365compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1366 PyObject *names)
1367{
1368 int i, error;
1369 for (i = 0; i < asdl_seq_LEN(args); i++) {
1370 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1371 if (arg->kind == NestedArgs_kind)
1372 error = compiler_visit_argannotations(
1373 c,
1374 arg->v.NestedArgs.args,
1375 names);
1376 else
1377 error = compiler_visit_argannotation(
1378 c,
1379 arg->v.SimpleArg.arg,
1380 arg->v.SimpleArg.annotation,
1381 names);
1382 if (error)
1383 return error;
1384 }
1385 return 0;
1386}
1387
1388static int
1389compiler_visit_annotations(struct compiler *c, arguments_ty args,
1390 expr_ty returns)
1391{
Guido van Rossum0240b922007-02-26 21:23:50 +00001392 /* Push arg annotations and a list of the argument names. Return the #
1393 of items pushed. The expressions are evaluated out-of-order wrt the
1394 source code.
1395
1396 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1397 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001398 static identifier return_str;
1399 PyObject *names;
1400 int len;
1401 names = PyList_New(0);
1402 if (!names)
1403 return -1;
1404
1405 if (compiler_visit_argannotations(c, args->args, names))
1406 goto error;
1407 if (args->varargannotation &&
1408 compiler_visit_argannotation(c, args->vararg,
1409 args->varargannotation, names))
1410 goto error;
1411 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1412 goto error;
1413 if (args->kwargannotation &&
1414 compiler_visit_argannotation(c, args->kwarg,
1415 args->kwargannotation, names))
1416 goto error;
1417
1418 if (!return_str) {
1419 return_str = PyString_InternFromString("return");
1420 if (!return_str)
1421 goto error;
1422 }
1423 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1424 goto error;
1425 }
1426
1427 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001428 if (len > 65534) {
1429 /* len must fit in 16 bits, and len is incremented below */
1430 PyErr_SetString(PyExc_SyntaxError,
1431 "too many annotations");
1432 goto error;
1433 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001434 if (len) {
1435 /* convert names to a tuple and place on stack */
1436 PyObject *elt;
1437 int i;
1438 PyObject *s = PyTuple_New(len);
1439 if (!s)
1440 goto error;
1441 for (i = 0; i < len; i++) {
1442 elt = PyList_GET_ITEM(names, i);
1443 Py_INCREF(elt);
1444 PyTuple_SET_ITEM(s, i, elt);
1445 }
1446 ADDOP_O(c, LOAD_CONST, s, consts);
1447 Py_DECREF(s);
1448 len++; /* include the just-pushed tuple */
1449 }
1450 Py_DECREF(names);
1451 return len;
1452
1453error:
1454 Py_DECREF(names);
1455 return -1;
1456}
1457
1458static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459compiler_function(struct compiler *c, stmt_ty s)
1460{
1461 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001462 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001464 expr_ty returns = s->v.FunctionDef.returns;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001466 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001467 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001468 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469
1470 assert(s->kind == FunctionDef_kind);
1471
1472 if (!compiler_decorators(c, decos))
1473 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001474 if (args->kwonlyargs) {
1475 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1476 args->kw_defaults);
1477 if (res < 0)
1478 return 0;
1479 kw_default_count = res;
1480 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481 if (args->defaults)
1482 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001483 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001484 if (num_annotations < 0)
1485 return 0;
1486 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001487
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1489 s->lineno))
1490 return 0;
1491
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001492 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001493 docstring = compiler_isdocstring(st);
1494 if (docstring)
1495 first_const = st->v.Expr.value->v.Str.s;
1496 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001497 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001498 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001501 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502 compiler_arguments(c, args);
1503
1504 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001505 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001507 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001509 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1510 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511 }
1512 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001513 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514 if (co == NULL)
1515 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516
Guido van Rossum4f72a782006-10-27 23:31:49 +00001517 arglength = asdl_seq_LEN(args->defaults);
1518 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001519 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001520 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001521 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522
Neal Norwitzc1505362006-12-28 06:47:50 +00001523 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1525 ADDOP_I(c, CALL_FUNCTION, 1);
1526 }
1527
1528 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1529}
1530
1531static int
1532compiler_class(struct compiler *c, stmt_ty s)
1533{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001534 static PyObject *build_class = NULL;
1535 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001537 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001538 PySTEntryObject *ste;
Guido van Rossum3a383622007-03-21 21:26:58 +00001539 int err;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001540
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001541 /* initialize statics */
1542 if (build_class == NULL) {
1543 build_class = PyString_FromString("__build_class__");
1544 if (build_class == NULL)
1545 return 0;
1546 }
1547 if (locals == NULL) {
1548 locals = PyString_FromString("__locals__");
1549 if (locals == NULL)
1550 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001551 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001553 /* ultimately generate code for:
1554 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1555 where:
1556 <func> is a function/closure created from the class body
1557 <name> is the class name
1558 <bases> is the positional arguments and *varargs argument
1559 <keywords> is the keyword arguments and **kwds argument
1560 This borrows from compiler_call.
1561 */
1562
1563 /* 0. Create a fake variable named __locals__ */
1564 ste = PySymtable_Lookup(c->c_st, s);
1565 if (ste == NULL)
1566 return 0;
1567 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001568 err = PyList_Append(ste->ste_varnames, locals);
1569 Py_DECREF(ste);
1570 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001571 return 0;
1572
1573 /* 1. compile the class body into a code object */
1574 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1575 return 0;
1576 /* this block represents what we do in the new scope */
1577 {
1578 /* use the class name for name mangling */
1579 Py_INCREF(s->v.ClassDef.name);
1580 c->u->u_private = s->v.ClassDef.name;
1581 /* force it to have one mandatory argument */
1582 c->u->u_argcount = 1;
1583 /* load the first argument ... */
1584 ADDOP_I(c, LOAD_FAST, 0);
1585 /* ... and store it into f_locals */
1586 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1587 /* load __name__ ... */
1588 str = PyString_InternFromString("__name__");
1589 if (!str || !compiler_nameop(c, str, Load)) {
1590 Py_XDECREF(str);
1591 compiler_exit_scope(c);
1592 return 0;
1593 }
1594 Py_DECREF(str);
1595 /* ... and store it as __module__ */
1596 str = PyString_InternFromString("__module__");
1597 if (!str || !compiler_nameop(c, str, Store)) {
1598 Py_XDECREF(str);
1599 compiler_exit_scope(c);
1600 return 0;
1601 }
1602 Py_DECREF(str);
1603 /* compile the body proper */
1604 if (!compiler_body(c, s->v.ClassDef.body)) {
1605 compiler_exit_scope(c);
1606 return 0;
1607 }
1608 /* return None */
1609 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1610 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1611 /* create the code object */
1612 co = assemble(c, 1);
1613 }
1614 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001615 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616 if (co == NULL)
1617 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001619 /* 2. load the 'build_class' function */
1620 ADDOP(c, LOAD_BUILD_CLASS);
1621
1622 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001623 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001624 Py_DECREF(co);
1625
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001626 /* 4. load class name */
1627 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1628
1629 /* 5. generate the rest of the code for the call */
1630 if (!compiler_call_helper(c, 2,
1631 s->v.ClassDef.bases,
1632 s->v.ClassDef.keywords,
1633 s->v.ClassDef.starargs,
1634 s->v.ClassDef.kwargs))
1635 return 0;
1636
1637 /* 6. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1639 return 0;
1640 return 1;
1641}
1642
1643static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001644compiler_ifexp(struct compiler *c, expr_ty e)
1645{
1646 basicblock *end, *next;
1647
1648 assert(e->kind == IfExp_kind);
1649 end = compiler_new_block(c);
1650 if (end == NULL)
1651 return 0;
1652 next = compiler_new_block(c);
1653 if (next == NULL)
1654 return 0;
1655 VISIT(c, expr, e->v.IfExp.test);
1656 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1657 ADDOP(c, POP_TOP);
1658 VISIT(c, expr, e->v.IfExp.body);
1659 ADDOP_JREL(c, JUMP_FORWARD, end);
1660 compiler_use_next_block(c, next);
1661 ADDOP(c, POP_TOP);
1662 VISIT(c, expr, e->v.IfExp.orelse);
1663 compiler_use_next_block(c, end);
1664 return 1;
1665}
1666
1667static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668compiler_lambda(struct compiler *c, expr_ty e)
1669{
1670 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001671 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001672 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673 arguments_ty args = e->v.Lambda.args;
1674 assert(e->kind == Lambda_kind);
1675
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001676 if (!name) {
1677 name = PyString_InternFromString("<lambda>");
1678 if (!name)
1679 return 0;
1680 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681
Guido van Rossum4f72a782006-10-27 23:31:49 +00001682 if (args->kwonlyargs) {
1683 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1684 args->kw_defaults);
1685 if (res < 0) return 0;
1686 kw_default_count = res;
1687 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 if (args->defaults)
1689 VISIT_SEQ(c, expr, args->defaults);
1690 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1691 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001692
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001693 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694 compiler_arguments(c, args);
1695
1696 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001697 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001698 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1699 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001701 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702 if (co == NULL)
1703 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704
Guido van Rossum4f72a782006-10-27 23:31:49 +00001705 arglength = asdl_seq_LEN(args->defaults);
1706 arglength |= kw_default_count << 8;
1707 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001708 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001709
1710 return 1;
1711}
1712
1713static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714compiler_if(struct compiler *c, stmt_ty s)
1715{
1716 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001717 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001718 assert(s->kind == If_kind);
1719 end = compiler_new_block(c);
1720 if (end == NULL)
1721 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001722 next = compiler_new_block(c);
1723 if (next == NULL)
1724 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001725
1726 constant = expr_constant(s->v.If.test);
1727 /* constant = 0: "if 0"
1728 * constant = 1: "if 1", "if 2", ...
1729 * constant = -1: rest */
1730 if (constant == 0) {
1731 if (s->v.If.orelse)
1732 VISIT_SEQ(c, stmt, s->v.If.orelse);
1733 } else if (constant == 1) {
1734 VISIT_SEQ(c, stmt, s->v.If.body);
1735 } else {
1736 VISIT(c, expr, s->v.If.test);
1737 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1738 ADDOP(c, POP_TOP);
1739 VISIT_SEQ(c, stmt, s->v.If.body);
1740 ADDOP_JREL(c, JUMP_FORWARD, end);
1741 compiler_use_next_block(c, next);
1742 ADDOP(c, POP_TOP);
1743 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001744 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001745 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001746 compiler_use_next_block(c, end);
1747 return 1;
1748}
1749
1750static int
1751compiler_for(struct compiler *c, stmt_ty s)
1752{
1753 basicblock *start, *cleanup, *end;
1754
1755 start = compiler_new_block(c);
1756 cleanup = compiler_new_block(c);
1757 end = compiler_new_block(c);
1758 if (start == NULL || end == NULL || cleanup == NULL)
1759 return 0;
1760 ADDOP_JREL(c, SETUP_LOOP, end);
1761 if (!compiler_push_fblock(c, LOOP, start))
1762 return 0;
1763 VISIT(c, expr, s->v.For.iter);
1764 ADDOP(c, GET_ITER);
1765 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001766 /* XXX(nnorwitz): is there a better way to handle this?
1767 for loops are special, we want to be able to trace them
1768 each time around, so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001769 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 ADDOP_JREL(c, FOR_ITER, cleanup);
1771 VISIT(c, expr, s->v.For.target);
1772 VISIT_SEQ(c, stmt, s->v.For.body);
1773 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1774 compiler_use_next_block(c, cleanup);
1775 ADDOP(c, POP_BLOCK);
1776 compiler_pop_fblock(c, LOOP, start);
1777 VISIT_SEQ(c, stmt, s->v.For.orelse);
1778 compiler_use_next_block(c, end);
1779 return 1;
1780}
1781
1782static int
1783compiler_while(struct compiler *c, stmt_ty s)
1784{
1785 basicblock *loop, *orelse, *end, *anchor = NULL;
1786 int constant = expr_constant(s->v.While.test);
1787
1788 if (constant == 0)
1789 return 1;
1790 loop = compiler_new_block(c);
1791 end = compiler_new_block(c);
1792 if (constant == -1) {
1793 anchor = compiler_new_block(c);
1794 if (anchor == NULL)
1795 return 0;
1796 }
1797 if (loop == NULL || end == NULL)
1798 return 0;
1799 if (s->v.While.orelse) {
1800 orelse = compiler_new_block(c);
1801 if (orelse == NULL)
1802 return 0;
1803 }
1804 else
1805 orelse = NULL;
1806
1807 ADDOP_JREL(c, SETUP_LOOP, end);
1808 compiler_use_next_block(c, loop);
1809 if (!compiler_push_fblock(c, LOOP, loop))
1810 return 0;
1811 if (constant == -1) {
1812 VISIT(c, expr, s->v.While.test);
1813 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1814 ADDOP(c, POP_TOP);
1815 }
1816 VISIT_SEQ(c, stmt, s->v.While.body);
1817 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1818
1819 /* XXX should the two POP instructions be in a separate block
1820 if there is no else clause ?
1821 */
1822
1823 if (constant == -1) {
1824 compiler_use_next_block(c, anchor);
1825 ADDOP(c, POP_TOP);
1826 ADDOP(c, POP_BLOCK);
1827 }
1828 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001829 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830 VISIT_SEQ(c, stmt, s->v.While.orelse);
1831 compiler_use_next_block(c, end);
1832
1833 return 1;
1834}
1835
1836static int
1837compiler_continue(struct compiler *c)
1838{
1839 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001840 static const char IN_FINALLY_ERROR_MSG[] =
1841 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 int i;
1843
1844 if (!c->u->u_nfblocks)
1845 return compiler_error(c, LOOP_ERROR_MSG);
1846 i = c->u->u_nfblocks - 1;
1847 switch (c->u->u_fblock[i].fb_type) {
1848 case LOOP:
1849 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1850 break;
1851 case EXCEPT:
1852 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001853 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1854 /* Prevent continue anywhere under a finally
1855 even if hidden in a sub-try or except. */
1856 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1857 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1858 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 if (i == -1)
1860 return compiler_error(c, LOOP_ERROR_MSG);
1861 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1862 break;
1863 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001864 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 }
1866
1867 return 1;
1868}
1869
1870/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1871
1872 SETUP_FINALLY L
1873 <code for body>
1874 POP_BLOCK
1875 LOAD_CONST <None>
1876 L: <code for finalbody>
1877 END_FINALLY
1878
1879 The special instructions use the block stack. Each block
1880 stack entry contains the instruction that created it (here
1881 SETUP_FINALLY), the level of the value stack at the time the
1882 block stack entry was created, and a label (here L).
1883
1884 SETUP_FINALLY:
1885 Pushes the current value stack level and the label
1886 onto the block stack.
1887 POP_BLOCK:
1888 Pops en entry from the block stack, and pops the value
1889 stack until its level is the same as indicated on the
1890 block stack. (The label is ignored.)
1891 END_FINALLY:
1892 Pops a variable number of entries from the *value* stack
1893 and re-raises the exception they specify. The number of
1894 entries popped depends on the (pseudo) exception type.
1895
1896 The block stack is unwound when an exception is raised:
1897 when a SETUP_FINALLY entry is found, the exception is pushed
1898 onto the value stack (and the exception condition is cleared),
1899 and the interpreter jumps to the label gotten from the block
1900 stack.
1901*/
1902
1903static int
1904compiler_try_finally(struct compiler *c, stmt_ty s)
1905{
1906 basicblock *body, *end;
1907 body = compiler_new_block(c);
1908 end = compiler_new_block(c);
1909 if (body == NULL || end == NULL)
1910 return 0;
1911
1912 ADDOP_JREL(c, SETUP_FINALLY, end);
1913 compiler_use_next_block(c, body);
1914 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1915 return 0;
1916 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1917 ADDOP(c, POP_BLOCK);
1918 compiler_pop_fblock(c, FINALLY_TRY, body);
1919
1920 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1921 compiler_use_next_block(c, end);
1922 if (!compiler_push_fblock(c, FINALLY_END, end))
1923 return 0;
1924 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1925 ADDOP(c, END_FINALLY);
1926 compiler_pop_fblock(c, FINALLY_END, end);
1927
1928 return 1;
1929}
1930
1931/*
1932 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1933 (The contents of the value stack is shown in [], with the top
1934 at the right; 'tb' is trace-back info, 'val' the exception's
1935 associated value, and 'exc' the exception.)
1936
1937 Value stack Label Instruction Argument
1938 [] SETUP_EXCEPT L1
1939 [] <code for S>
1940 [] POP_BLOCK
1941 [] JUMP_FORWARD L0
1942
1943 [tb, val, exc] L1: DUP )
1944 [tb, val, exc, exc] <evaluate E1> )
1945 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1946 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1947 [tb, val, exc, 1] POP )
1948 [tb, val, exc] POP
1949 [tb, val] <assign to V1> (or POP if no V1)
1950 [tb] POP
1951 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001952 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953
1954 [tb, val, exc, 0] L2: POP
1955 [tb, val, exc] DUP
1956 .............................etc.......................
1957
1958 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001959 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
1961 [] L0: <next statement>
1962
1963 Of course, parts are not generated if Vi or Ei is not present.
1964*/
1965static int
1966compiler_try_except(struct compiler *c, stmt_ty s)
1967{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001968 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969 int i, n;
1970
1971 body = compiler_new_block(c);
1972 except = compiler_new_block(c);
1973 orelse = compiler_new_block(c);
1974 end = compiler_new_block(c);
1975 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1976 return 0;
1977 ADDOP_JREL(c, SETUP_EXCEPT, except);
1978 compiler_use_next_block(c, body);
1979 if (!compiler_push_fblock(c, EXCEPT, body))
1980 return 0;
1981 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1982 ADDOP(c, POP_BLOCK);
1983 compiler_pop_fblock(c, EXCEPT, body);
1984 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1985 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1986 compiler_use_next_block(c, except);
1987 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001988 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 s->v.TryExcept.handlers, i);
1990 if (!handler->type && i < n-1)
1991 return compiler_error(c, "default 'except:' must be last");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001992 c->u->u_lineno_set = 0;
1993 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994 except = compiler_new_block(c);
1995 if (except == NULL)
1996 return 0;
1997 if (handler->type) {
1998 ADDOP(c, DUP_TOP);
1999 VISIT(c, expr, handler->type);
2000 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2001 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2002 ADDOP(c, POP_TOP);
2003 }
2004 ADDOP(c, POP_TOP);
2005 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00002006 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002007
2008 cleanup_end = compiler_new_block(c);
2009 cleanup_body = compiler_new_block(c);
2010 if(!(cleanup_end || cleanup_body))
2011 return 0;
2012
Guido van Rossum16be03e2007-01-10 18:51:35 +00002013 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002014 ADDOP(c, POP_TOP);
2015
2016 /*
2017 try:
2018 # body
2019 except type as name:
2020 try:
2021 # body
2022 finally:
2023 name = None
2024 del name
2025 */
2026
2027 /* second try: */
2028 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2029 compiler_use_next_block(c, cleanup_body);
2030 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2031 return 0;
2032
2033 /* second # body */
2034 VISIT_SEQ(c, stmt, handler->body);
2035 ADDOP(c, POP_BLOCK);
2036 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2037
2038 /* finally: */
2039 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2040 compiler_use_next_block(c, cleanup_end);
2041 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2042 return 0;
2043
2044 /* name = None */
2045 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00002046 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002047
Guido van Rossum16be03e2007-01-10 18:51:35 +00002048 /* del name */
2049 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002050
2051 ADDOP(c, END_FINALLY);
2052 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 }
2054 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00002055 ADDOP(c, POP_TOP);
2056 ADDOP(c, POP_TOP);
2057 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 ADDOP_JREL(c, JUMP_FORWARD, end);
2060 compiler_use_next_block(c, except);
2061 if (handler->type)
2062 ADDOP(c, POP_TOP);
2063 }
2064 ADDOP(c, END_FINALLY);
2065 compiler_use_next_block(c, orelse);
2066 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2067 compiler_use_next_block(c, end);
2068 return 1;
2069}
2070
2071static int
2072compiler_import_as(struct compiler *c, identifier name, identifier asname)
2073{
2074 /* The IMPORT_NAME opcode was already generated. This function
2075 merely needs to bind the result to a name.
2076
2077 If there is a dot in name, we need to split it and emit a
2078 LOAD_ATTR for each name.
2079 */
2080 const char *src = PyString_AS_STRING(name);
2081 const char *dot = strchr(src, '.');
2082 if (dot) {
2083 /* Consume the base module name to get the first attribute */
2084 src = dot + 1;
2085 while (dot) {
2086 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002087 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002089 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002091 if (!attr)
2092 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002094 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 src = dot + 1;
2096 }
2097 }
2098 return compiler_nameop(c, asname, Store);
2099}
2100
2101static int
2102compiler_import(struct compiler *c, stmt_ty s)
2103{
2104 /* The Import node stores a module name like a.b.c as a single
2105 string. This is convenient for all cases except
2106 import a.b.c as d
2107 where we need to parse that string to extract the individual
2108 module names.
2109 XXX Perhaps change the representation to make this case simpler?
2110 */
2111 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002112
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002114 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002116 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117
Guido van Rossum45aecf42006-03-15 04:58:47 +00002118 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002119 if (level == NULL)
2120 return 0;
2121
2122 ADDOP_O(c, LOAD_CONST, level, consts);
2123 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2125 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2126
2127 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002128 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 if (!r)
2130 return r;
2131 }
2132 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 identifier tmp = alias->name;
2134 const char *base = PyString_AS_STRING(alias->name);
2135 char *dot = strchr(base, '.');
2136 if (dot)
2137 tmp = PyString_FromStringAndSize(base,
2138 dot - base);
2139 r = compiler_nameop(c, tmp, Store);
2140 if (dot) {
2141 Py_DECREF(tmp);
2142 }
2143 if (!r)
2144 return r;
2145 }
2146 }
2147 return 1;
2148}
2149
2150static int
2151compiler_from_import(struct compiler *c, stmt_ty s)
2152{
2153 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154
2155 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002156 PyObject *level;
2157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 if (!names)
2159 return 0;
2160
Guido van Rossum45aecf42006-03-15 04:58:47 +00002161 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002162 if (!level) {
2163 Py_DECREF(names);
2164 return 0;
2165 }
2166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 /* build up the names */
2168 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002169 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 Py_INCREF(alias->name);
2171 PyTuple_SET_ITEM(names, i, alias->name);
2172 }
2173
2174 if (s->lineno > c->c_future->ff_lineno) {
2175 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2176 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002177 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 Py_DECREF(names);
2179 return compiler_error(c,
2180 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002181 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182
2183 }
2184 }
2185
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002186 ADDOP_O(c, LOAD_CONST, level, consts);
2187 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002189 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2191 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002192 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 identifier store_name;
2194
2195 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2196 assert(n == 1);
2197 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199 }
2200
2201 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2202 store_name = alias->name;
2203 if (alias->asname)
2204 store_name = alias->asname;
2205
2206 if (!compiler_nameop(c, store_name, Store)) {
2207 Py_DECREF(names);
2208 return 0;
2209 }
2210 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002211 /* remove imported module */
2212 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213 return 1;
2214}
2215
2216static int
2217compiler_assert(struct compiler *c, stmt_ty s)
2218{
2219 static PyObject *assertion_error = NULL;
2220 basicblock *end;
2221
2222 if (Py_OptimizeFlag)
2223 return 1;
2224 if (assertion_error == NULL) {
2225 assertion_error = PyString_FromString("AssertionError");
2226 if (assertion_error == NULL)
2227 return 0;
2228 }
2229 VISIT(c, expr, s->v.Assert.test);
2230 end = compiler_new_block(c);
2231 if (end == NULL)
2232 return 0;
2233 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2234 ADDOP(c, POP_TOP);
2235 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2236 if (s->v.Assert.msg) {
2237 VISIT(c, expr, s->v.Assert.msg);
2238 ADDOP_I(c, RAISE_VARARGS, 2);
2239 }
2240 else {
2241 ADDOP_I(c, RAISE_VARARGS, 1);
2242 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002243 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 ADDOP(c, POP_TOP);
2245 return 1;
2246}
2247
2248static int
2249compiler_visit_stmt(struct compiler *c, stmt_ty s)
2250{
2251 int i, n;
2252
Thomas Wouters89f507f2006-12-13 04:49:30 +00002253 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002255 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002258 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002260 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 if (c->u->u_ste->ste_type != FunctionBlock)
2264 return compiler_error(c, "'return' outside function");
2265 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 VISIT(c, expr, s->v.Return.value);
2267 }
2268 else
2269 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2270 ADDOP(c, RETURN_VALUE);
2271 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002272 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273 VISIT_SEQ(c, expr, s->v.Delete.targets)
2274 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002275 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 n = asdl_seq_LEN(s->v.Assign.targets);
2277 VISIT(c, expr, s->v.Assign.value);
2278 for (i = 0; i < n; i++) {
2279 if (i < n - 1)
2280 ADDOP(c, DUP_TOP);
2281 VISIT(c, expr,
2282 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2283 }
2284 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002285 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002287 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002289 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 n = 0;
2295 if (s->v.Raise.type) {
2296 VISIT(c, expr, s->v.Raise.type);
2297 n++;
2298 if (s->v.Raise.inst) {
2299 VISIT(c, expr, s->v.Raise.inst);
2300 n++;
2301 if (s->v.Raise.tback) {
2302 VISIT(c, expr, s->v.Raise.tback);
2303 n++;
2304 }
2305 }
2306 }
2307 ADDOP_I(c, RAISE_VARARGS, n);
2308 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002309 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002311 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002313 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002315 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002317 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002320 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002322 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002324 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 ADDOP(c, PRINT_EXPR);
2326 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002327 else if (s->v.Expr.value->kind != Str_kind &&
2328 s->v.Expr.value->kind != Num_kind) {
2329 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 ADDOP(c, POP_TOP);
2331 }
2332 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002333 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002335 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002336 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 return compiler_error(c, "'break' outside loop");
2338 ADDOP(c, BREAK_LOOP);
2339 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002340 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002342 case With_kind:
2343 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344 }
2345 return 1;
2346}
2347
2348static int
2349unaryop(unaryop_ty op)
2350{
2351 switch (op) {
2352 case Invert:
2353 return UNARY_INVERT;
2354 case Not:
2355 return UNARY_NOT;
2356 case UAdd:
2357 return UNARY_POSITIVE;
2358 case USub:
2359 return UNARY_NEGATIVE;
2360 }
2361 return 0;
2362}
2363
2364static int
2365binop(struct compiler *c, operator_ty op)
2366{
2367 switch (op) {
2368 case Add:
2369 return BINARY_ADD;
2370 case Sub:
2371 return BINARY_SUBTRACT;
2372 case Mult:
2373 return BINARY_MULTIPLY;
2374 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002375 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376 case Mod:
2377 return BINARY_MODULO;
2378 case Pow:
2379 return BINARY_POWER;
2380 case LShift:
2381 return BINARY_LSHIFT;
2382 case RShift:
2383 return BINARY_RSHIFT;
2384 case BitOr:
2385 return BINARY_OR;
2386 case BitXor:
2387 return BINARY_XOR;
2388 case BitAnd:
2389 return BINARY_AND;
2390 case FloorDiv:
2391 return BINARY_FLOOR_DIVIDE;
2392 }
2393 return 0;
2394}
2395
2396static int
2397cmpop(cmpop_ty op)
2398{
2399 switch (op) {
2400 case Eq:
2401 return PyCmp_EQ;
2402 case NotEq:
2403 return PyCmp_NE;
2404 case Lt:
2405 return PyCmp_LT;
2406 case LtE:
2407 return PyCmp_LE;
2408 case Gt:
2409 return PyCmp_GT;
2410 case GtE:
2411 return PyCmp_GE;
2412 case Is:
2413 return PyCmp_IS;
2414 case IsNot:
2415 return PyCmp_IS_NOT;
2416 case In:
2417 return PyCmp_IN;
2418 case NotIn:
2419 return PyCmp_NOT_IN;
2420 }
2421 return PyCmp_BAD;
2422}
2423
2424static int
2425inplace_binop(struct compiler *c, operator_ty op)
2426{
2427 switch (op) {
2428 case Add:
2429 return INPLACE_ADD;
2430 case Sub:
2431 return INPLACE_SUBTRACT;
2432 case Mult:
2433 return INPLACE_MULTIPLY;
2434 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002435 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436 case Mod:
2437 return INPLACE_MODULO;
2438 case Pow:
2439 return INPLACE_POWER;
2440 case LShift:
2441 return INPLACE_LSHIFT;
2442 case RShift:
2443 return INPLACE_RSHIFT;
2444 case BitOr:
2445 return INPLACE_OR;
2446 case BitXor:
2447 return INPLACE_XOR;
2448 case BitAnd:
2449 return INPLACE_AND;
2450 case FloorDiv:
2451 return INPLACE_FLOOR_DIVIDE;
2452 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002453 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002454 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 return 0;
2456}
2457
2458static int
2459compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2460{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002461 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2463
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002464 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002465 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 /* XXX AugStore isn't used anywhere! */
2467
2468 /* First check for assignment to __debug__. Param? */
2469 if ((ctx == Store || ctx == AugStore || ctx == Del)
2470 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2471 return compiler_error(c, "can not assign to __debug__");
2472 }
2473
Guido van Rossumd8faa362007-04-27 19:54:29 +00002474mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002475 if (!mangled)
2476 return 0;
2477
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 op = 0;
2479 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002480 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481 switch (scope) {
2482 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002483 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 optype = OP_DEREF;
2485 break;
2486 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002487 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 optype = OP_DEREF;
2489 break;
2490 case LOCAL:
2491 if (c->u->u_ste->ste_type == FunctionBlock)
2492 optype = OP_FAST;
2493 break;
2494 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002495 if (c->u->u_ste->ste_type == FunctionBlock &&
2496 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497 optype = OP_GLOBAL;
2498 break;
2499 case GLOBAL_EXPLICIT:
2500 optype = OP_GLOBAL;
2501 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002502 default:
2503 /* scope can be 0 */
2504 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505 }
2506
2507 /* XXX Leave assert here, but handle __doc__ and the like better */
2508 assert(scope || PyString_AS_STRING(name)[0] == '_');
2509
2510 switch (optype) {
2511 case OP_DEREF:
2512 switch (ctx) {
2513 case Load: op = LOAD_DEREF; break;
2514 case Store: op = STORE_DEREF; break;
2515 case AugLoad:
2516 case AugStore:
2517 break;
2518 case Del:
2519 PyErr_Format(PyExc_SyntaxError,
2520 "can not delete variable '%s' referenced "
2521 "in nested scope",
2522 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002523 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002526 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002527 PyErr_SetString(PyExc_SystemError,
2528 "param invalid for deref variable");
2529 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 }
2531 break;
2532 case OP_FAST:
2533 switch (ctx) {
2534 case Load: op = LOAD_FAST; break;
2535 case Store: op = STORE_FAST; break;
2536 case Del: op = DELETE_FAST; break;
2537 case AugLoad:
2538 case AugStore:
2539 break;
2540 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002541 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002542 PyErr_SetString(PyExc_SystemError,
2543 "param invalid for local variable");
2544 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002546 ADDOP_O(c, op, mangled, varnames);
2547 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 return 1;
2549 case OP_GLOBAL:
2550 switch (ctx) {
2551 case Load: op = LOAD_GLOBAL; break;
2552 case Store: op = STORE_GLOBAL; break;
2553 case Del: op = DELETE_GLOBAL; break;
2554 case AugLoad:
2555 case AugStore:
2556 break;
2557 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002558 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002559 PyErr_SetString(PyExc_SystemError,
2560 "param invalid for global variable");
2561 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 }
2563 break;
2564 case OP_NAME:
2565 switch (ctx) {
2566 case Load: op = LOAD_NAME; break;
2567 case Store: op = STORE_NAME; break;
2568 case Del: op = DELETE_NAME; break;
2569 case AugLoad:
2570 case AugStore:
2571 break;
2572 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002573 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002574 PyErr_SetString(PyExc_SystemError,
2575 "param invalid for name variable");
2576 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002577 }
2578 break;
2579 }
2580
2581 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002582 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002583 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002584 if (arg < 0)
2585 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002586 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587}
2588
2589static int
2590compiler_boolop(struct compiler *c, expr_ty e)
2591{
2592 basicblock *end;
2593 int jumpi, i, n;
2594 asdl_seq *s;
2595
2596 assert(e->kind == BoolOp_kind);
2597 if (e->v.BoolOp.op == And)
2598 jumpi = JUMP_IF_FALSE;
2599 else
2600 jumpi = JUMP_IF_TRUE;
2601 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002602 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 return 0;
2604 s = e->v.BoolOp.values;
2605 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002606 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002608 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 ADDOP_JREL(c, jumpi, end);
2610 ADDOP(c, POP_TOP)
2611 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002612 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613 compiler_use_next_block(c, end);
2614 return 1;
2615}
2616
2617static int
2618compiler_list(struct compiler *c, expr_ty e)
2619{
2620 int n = asdl_seq_LEN(e->v.List.elts);
2621 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002622 int i, seen_star = 0;
2623 for (i = 0; i < n; i++) {
2624 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2625 if (elt->kind == Starred_kind && !seen_star) {
2626 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2627 seen_star = 1;
2628 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2629 } else if (elt->kind == Starred_kind) {
2630 return compiler_error(c,
2631 "two starred expressions in assignment");
2632 }
2633 }
2634 if (!seen_star) {
2635 ADDOP_I(c, UNPACK_SEQUENCE, n);
2636 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637 }
2638 VISIT_SEQ(c, expr, e->v.List.elts);
2639 if (e->v.List.ctx == Load) {
2640 ADDOP_I(c, BUILD_LIST, n);
2641 }
2642 return 1;
2643}
2644
2645static int
2646compiler_tuple(struct compiler *c, expr_ty e)
2647{
2648 int n = asdl_seq_LEN(e->v.Tuple.elts);
2649 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002650 int i, seen_star = 0;
2651 for (i = 0; i < n; i++) {
2652 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2653 if (elt->kind == Starred_kind && !seen_star) {
2654 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2655 seen_star = 1;
2656 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2657 } else if (elt->kind == Starred_kind) {
2658 return compiler_error(c,
2659 "two starred expressions in assignment");
2660 }
2661 }
2662 if (!seen_star) {
2663 ADDOP_I(c, UNPACK_SEQUENCE, n);
2664 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665 }
2666 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2667 if (e->v.Tuple.ctx == Load) {
2668 ADDOP_I(c, BUILD_TUPLE, n);
2669 }
2670 return 1;
2671}
2672
2673static int
2674compiler_compare(struct compiler *c, expr_ty e)
2675{
2676 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678
2679 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2680 VISIT(c, expr, e->v.Compare.left);
2681 n = asdl_seq_LEN(e->v.Compare.ops);
2682 assert(n > 0);
2683 if (n > 1) {
2684 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002685 if (cleanup == NULL)
2686 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002687 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002688 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 }
2690 for (i = 1; i < n; i++) {
2691 ADDOP(c, DUP_TOP);
2692 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002694 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002695 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2697 NEXT_BLOCK(c);
2698 ADDOP(c, POP_TOP);
2699 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002700 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002701 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002703 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002705 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 if (n > 1) {
2707 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 if (end == NULL)
2709 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710 ADDOP_JREL(c, JUMP_FORWARD, end);
2711 compiler_use_next_block(c, cleanup);
2712 ADDOP(c, ROT_TWO);
2713 ADDOP(c, POP_TOP);
2714 compiler_use_next_block(c, end);
2715 }
2716 return 1;
2717}
2718
2719static int
2720compiler_call(struct compiler *c, expr_ty e)
2721{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002723 return compiler_call_helper(c, 0,
2724 e->v.Call.args,
2725 e->v.Call.keywords,
2726 e->v.Call.starargs,
2727 e->v.Call.kwargs);
2728}
2729
2730/* shared code between compiler_call and compiler_class */
2731static int
2732compiler_call_helper(struct compiler *c,
2733 int n, /* Args already pushed */
2734 asdl_seq *args,
2735 asdl_seq *keywords,
2736 expr_ty starargs,
2737 expr_ty kwargs)
2738{
2739 int code = 0;
2740
2741 n += asdl_seq_LEN(args);
2742 VISIT_SEQ(c, expr, args);
2743 if (keywords) {
2744 VISIT_SEQ(c, keyword, keywords);
2745 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002747 if (starargs) {
2748 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749 code |= 1;
2750 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002751 if (kwargs) {
2752 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753 code |= 2;
2754 }
2755 switch (code) {
2756 case 0:
2757 ADDOP_I(c, CALL_FUNCTION, n);
2758 break;
2759 case 1:
2760 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2761 break;
2762 case 2:
2763 ADDOP_I(c, CALL_FUNCTION_KW, n);
2764 break;
2765 case 3:
2766 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2767 break;
2768 }
2769 return 1;
2770}
2771
Nick Coghlan650f0d02007-04-15 12:05:43 +00002772
2773/* List and set comprehensions and generator expressions work by creating a
2774 nested function to perform the actual iteration. This means that the
2775 iteration variables don't leak into the current scope.
2776 The defined function is called immediately following its definition, with the
2777 result of that call being the result of the expression.
2778 The LC/SC version returns the populated container, while the GE version is
2779 flagged in symtable.c as a generator, so it returns the generator object
2780 when the function is called.
2781 This code *knows* that the loop cannot contain break, continue, or return,
2782 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2783
2784 Possible cleanups:
2785 - iterate over the generator sequence instead of using recursion
2786*/
2787
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002789compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
2790 asdl_seq *generators, int gen_index,
2791 expr_ty elt, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792{
2793 /* generate code for the iterator, then each of the ifs,
2794 and then write to the element */
2795
Nick Coghlan650f0d02007-04-15 12:05:43 +00002796 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002798 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799
2800 start = compiler_new_block(c);
2801 skip = compiler_new_block(c);
2802 if_cleanup = compiler_new_block(c);
2803 anchor = compiler_new_block(c);
2804
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002805 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002806 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002808
Nick Coghlan650f0d02007-04-15 12:05:43 +00002809 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002810
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811 if (gen_index == 0) {
2812 /* Receive outermost iter as an implicit argument */
2813 c->u->u_argcount = 1;
2814 ADDOP_I(c, LOAD_FAST, 0);
2815 }
2816 else {
2817 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002818 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819 ADDOP(c, GET_ITER);
2820 }
2821 compiler_use_next_block(c, start);
2822 ADDOP_JREL(c, FOR_ITER, anchor);
2823 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002824 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002826 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002827 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002829 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830 VISIT(c, expr, e);
2831 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2832 NEXT_BLOCK(c);
2833 ADDOP(c, POP_TOP);
2834 }
2835
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002836 if (++gen_index < asdl_seq_LEN(generators))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002837 if (!compiler_comprehension_generator(c, tmpname,
2838 generators, gen_index,
2839 elt, type))
2840 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841
Nick Coghlan650f0d02007-04-15 12:05:43 +00002842 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002843 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002844 /* comprehension specific code */
2845 switch (type) {
2846 case COMP_GENEXP:
2847 VISIT(c, expr, elt);
2848 ADDOP(c, YIELD_VALUE);
2849 ADDOP(c, POP_TOP);
2850 break;
2851 case COMP_LISTCOMP:
2852 if (!compiler_nameop(c, tmpname, Load))
2853 return 0;
2854 VISIT(c, expr, elt);
2855 ADDOP(c, LIST_APPEND);
2856 break;
2857 case COMP_SETCOMP:
2858 if (!compiler_nameop(c, tmpname, Load))
2859 return 0;
2860 VISIT(c, expr, elt);
2861 ADDOP(c, SET_ADD);
2862 break;
2863 default:
2864 return 0;
2865 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866
2867 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002868 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869 for (i = 0; i < n; i++) {
2870 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002871 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874 ADDOP(c, POP_TOP);
2875 }
2876 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2877 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
2879 return 1;
2880}
2881
2882static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002883compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
2884 asdl_seq *generators, expr_ty elt)
2885{
2886 PyCodeObject *co = NULL;
2887 identifier tmp = NULL;
2888 expr_ty outermost_iter;
2889
2890 outermost_iter = ((comprehension_ty)
2891 asdl_seq_GET(generators, 0))->iter;
2892
2893 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2894 goto error;
2895
2896 if (type != COMP_GENEXP) {
2897 tmp = compiler_new_tmpname(c);
2898 if (!tmp)
2899 goto error_in_scope;
2900
2901 ADDOP_I(c, (type == COMP_LISTCOMP ?
2902 BUILD_LIST : BUILD_SET), 0);
2903 ADDOP(c, DUP_TOP);
2904 if (!compiler_nameop(c, tmp, Store))
2905 goto error_in_scope;
2906 }
2907
2908 if (!compiler_comprehension_generator(c, tmp, generators, 0, elt, type))
2909 goto error_in_scope;
2910
2911 if (type != COMP_GENEXP) {
2912 ADDOP(c, RETURN_VALUE);
2913 }
2914
2915 co = assemble(c, 1);
2916 compiler_exit_scope(c);
2917 if (co == NULL)
2918 goto error;
2919
2920 if (!compiler_make_closure(c, co, 0))
2921 goto error;
2922 Py_DECREF(co);
2923 Py_XDECREF(tmp);
2924
2925 VISIT(c, expr, outermost_iter);
2926 ADDOP(c, GET_ITER);
2927 ADDOP_I(c, CALL_FUNCTION, 1);
2928 return 1;
2929error_in_scope:
2930 compiler_exit_scope(c);
2931error:
2932 Py_XDECREF(co);
2933 Py_XDECREF(tmp);
2934 return 0;
2935}
2936
2937static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938compiler_genexp(struct compiler *c, expr_ty e)
2939{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002940 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002941 if (!name) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002942 name = PyString_FromString("<genexp>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002943 if (!name)
2944 return 0;
2945 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002946 assert(e->kind == GeneratorExp_kind);
2947 return compiler_comprehension(c, e, COMP_GENEXP, name,
2948 e->v.GeneratorExp.generators,
2949 e->v.GeneratorExp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950}
2951
2952static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002953compiler_listcomp(struct compiler *c, expr_ty e)
2954{
2955 static identifier name;
2956 if (!name) {
2957 name = PyString_FromString("<listcomp>");
2958 if (!name)
2959 return 0;
2960 }
2961 assert(e->kind == ListComp_kind);
2962 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2963 e->v.ListComp.generators,
2964 e->v.ListComp.elt);
2965}
2966
2967static int
2968compiler_setcomp(struct compiler *c, expr_ty e)
2969{
2970 static identifier name;
2971 if (!name) {
2972 name = PyString_FromString("<setcomp>");
2973 if (!name)
2974 return 0;
2975 }
2976 assert(e->kind == SetComp_kind);
2977 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2978 e->v.SetComp.generators,
2979 e->v.SetComp.elt);
2980}
2981
2982
2983static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984compiler_visit_keyword(struct compiler *c, keyword_ty k)
2985{
2986 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2987 VISIT(c, expr, k->value);
2988 return 1;
2989}
2990
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002991/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992 whether they are true or false.
2993
2994 Return values: 1 for true, 0 for false, -1 for non-constant.
2995 */
2996
2997static int
2998expr_constant(expr_ty e)
2999{
3000 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003001 case Ellipsis_kind:
3002 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003 case Num_kind:
3004 return PyObject_IsTrue(e->v.Num.n);
3005 case Str_kind:
3006 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003007 case Name_kind:
3008 /* __debug__ is not assignable, so we can optimize
3009 * it away in if and while statements */
3010 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Guido van Rossumd8faa362007-04-27 19:54:29 +00003011 "__debug__") == 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003012 return ! Py_OptimizeFlag;
3013 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 default:
3015 return -1;
3016 }
3017}
3018
Guido van Rossumc2e20742006-02-27 22:32:47 +00003019/*
3020 Implements the with statement from PEP 343.
3021
3022 The semantics outlined in that PEP are as follows:
3023
3024 with EXPR as VAR:
3025 BLOCK
3026
3027 It is implemented roughly as:
3028
Thomas Wouters477c8d52006-05-27 19:21:47 +00003029 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003030 exit = context.__exit__ # not calling it
3031 value = context.__enter__()
3032 try:
3033 VAR = value # if VAR present in the syntax
3034 BLOCK
3035 finally:
3036 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003037 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003038 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003039 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003040 exit(*exc)
3041 */
3042static int
3043compiler_with(struct compiler *c, stmt_ty s)
3044{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003045 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003046 basicblock *block, *finally;
3047 identifier tmpexit, tmpvalue = NULL;
3048
3049 assert(s->kind == With_kind);
3050
Guido van Rossumc2e20742006-02-27 22:32:47 +00003051 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003052 enter_attr = PyString_InternFromString("__enter__");
3053 if (!enter_attr)
3054 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003055 }
3056 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 exit_attr = PyString_InternFromString("__exit__");
3058 if (!exit_attr)
3059 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003060 }
3061
3062 block = compiler_new_block(c);
3063 finally = compiler_new_block(c);
3064 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003065 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003066
3067 /* Create a temporary variable to hold context.__exit__ */
3068 tmpexit = compiler_new_tmpname(c);
3069 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 PyArena_AddPyObject(c->c_arena, tmpexit);
3072
3073 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075 We need to do this rather than preserving it on the stack
3076 because SETUP_FINALLY remembers the stack level.
3077 We need to do the assignment *inside* the try/finally
3078 so that context.__exit__() is called when the assignment
3079 fails. But we need to call context.__enter__() *before*
3080 the try/finally so that if it fails we won't call
3081 context.__exit__().
3082 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003083 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003084 if (tmpvalue == NULL)
3085 return 0;
3086 PyArena_AddPyObject(c->c_arena, tmpvalue);
3087 }
3088
Thomas Wouters477c8d52006-05-27 19:21:47 +00003089 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003090 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003091
3092 /* Squirrel away context.__exit__ */
3093 ADDOP(c, DUP_TOP);
3094 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3095 if (!compiler_nameop(c, tmpexit, Store))
3096 return 0;
3097
3098 /* Call context.__enter__() */
3099 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3100 ADDOP_I(c, CALL_FUNCTION, 0);
3101
3102 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003103 /* Store it in tmpvalue */
3104 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003105 return 0;
3106 }
3107 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003108 /* Discard result from context.__enter__() */
3109 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003110 }
3111
3112 /* Start the try block */
3113 ADDOP_JREL(c, SETUP_FINALLY, finally);
3114
3115 compiler_use_next_block(c, block);
3116 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003117 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003118 }
3119
3120 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003121 /* Bind saved result of context.__enter__() to VAR */
3122 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003123 !compiler_nameop(c, tmpvalue, Del))
3124 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003125 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003126 }
3127
3128 /* BLOCK code */
3129 VISIT_SEQ(c, stmt, s->v.With.body);
3130
3131 /* End of try block; start the finally block */
3132 ADDOP(c, POP_BLOCK);
3133 compiler_pop_fblock(c, FINALLY_TRY, block);
3134
3135 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3136 compiler_use_next_block(c, finally);
3137 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003139
3140 /* Finally block starts; push tmpexit and issue our magic opcode. */
3141 if (!compiler_nameop(c, tmpexit, Load) ||
3142 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003143 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003144 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003145
3146 /* Finally block ends. */
3147 ADDOP(c, END_FINALLY);
3148 compiler_pop_fblock(c, FINALLY_END, finally);
3149 return 1;
3150}
3151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152static int
3153compiler_visit_expr(struct compiler *c, expr_ty e)
3154{
3155 int i, n;
3156
Thomas Wouters89f507f2006-12-13 04:49:30 +00003157 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003158 set a new line number for the next instruction.
3159 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160 if (e->lineno > c->u->u_lineno) {
3161 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003162 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163 }
3164 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003165 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 VISIT(c, expr, e->v.BinOp.left);
3169 VISIT(c, expr, e->v.BinOp.right);
3170 ADDOP(c, binop(c, e->v.BinOp.op));
3171 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003172 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173 VISIT(c, expr, e->v.UnaryOp.operand);
3174 ADDOP(c, unaryop(e->v.UnaryOp.op));
3175 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003176 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003178 case IfExp_kind:
3179 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003180 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181 /* XXX get rid of arg? */
3182 ADDOP_I(c, BUILD_MAP, 0);
3183 n = asdl_seq_LEN(e->v.Dict.values);
3184 /* We must arrange things just right for STORE_SUBSCR.
3185 It wants the stack to look like (value) (dict) (key) */
3186 for (i = 0; i < n; i++) {
3187 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003188 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003189 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003191 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003192 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 ADDOP(c, STORE_SUBSCR);
3194 }
3195 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003196 case Set_kind:
3197 n = asdl_seq_LEN(e->v.Set.elts);
3198 VISIT_SEQ(c, expr, e->v.Set.elts);
3199 ADDOP_I(c, BUILD_SET, n);
3200 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003201 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003203 case ListComp_kind:
3204 return compiler_listcomp(c, e);
3205 case SetComp_kind:
3206 return compiler_setcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207 case Yield_kind:
3208 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 if (e->v.Yield.value) {
3211 VISIT(c, expr, e->v.Yield.value);
3212 }
3213 else {
3214 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3215 }
3216 ADDOP(c, YIELD_VALUE);
3217 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003218 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003220 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003222 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3224 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003225 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3227 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003228 case Bytes_kind:
3229 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3230 ADDOP(c, MAKE_BYTES);
3231 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003232 case Ellipsis_kind:
3233 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3234 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003236 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237 if (e->v.Attribute.ctx != AugStore)
3238 VISIT(c, expr, e->v.Attribute.value);
3239 switch (e->v.Attribute.ctx) {
3240 case AugLoad:
3241 ADDOP(c, DUP_TOP);
3242 /* Fall through to load */
3243 case Load:
3244 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3245 break;
3246 case AugStore:
3247 ADDOP(c, ROT_TWO);
3248 /* Fall through to save */
3249 case Store:
3250 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3251 break;
3252 case Del:
3253 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3254 break;
3255 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003256 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003257 PyErr_SetString(PyExc_SystemError,
3258 "param invalid in attribute expression");
3259 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 }
3261 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003262 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 switch (e->v.Subscript.ctx) {
3264 case AugLoad:
3265 VISIT(c, expr, e->v.Subscript.value);
3266 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3267 break;
3268 case Load:
3269 VISIT(c, expr, e->v.Subscript.value);
3270 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3271 break;
3272 case AugStore:
3273 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3274 break;
3275 case Store:
3276 VISIT(c, expr, e->v.Subscript.value);
3277 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3278 break;
3279 case Del:
3280 VISIT(c, expr, e->v.Subscript.value);
3281 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3282 break;
3283 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003284 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003285 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003286 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003287 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288 }
3289 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003290 case Starred_kind:
3291 switch (e->v.Starred.ctx) {
3292 case Store:
3293 /* In all legitimate cases, the Starred node was already replaced
3294 * by compiler_list/compiler_tuple. XXX: is that okay? */
3295 return compiler_error(c,
3296 "starred assignment target must be in a list or tuple");
3297 default:
3298 return compiler_error(c,
3299 "can use starred expression only as assignment target");
3300 }
3301 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003302 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3304 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003305 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003307 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308 return compiler_tuple(c, e);
3309 }
3310 return 1;
3311}
3312
3313static int
3314compiler_augassign(struct compiler *c, stmt_ty s)
3315{
3316 expr_ty e = s->v.AugAssign.target;
3317 expr_ty auge;
3318
3319 assert(s->kind == AugAssign_kind);
3320
3321 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003322 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003324 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003325 if (auge == NULL)
3326 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327 VISIT(c, expr, auge);
3328 VISIT(c, expr, s->v.AugAssign.value);
3329 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3330 auge->v.Attribute.ctx = AugStore;
3331 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332 break;
3333 case Subscript_kind:
3334 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003335 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003336 if (auge == NULL)
3337 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338 VISIT(c, expr, auge);
3339 VISIT(c, expr, s->v.AugAssign.value);
3340 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003341 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003343 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003345 if (!compiler_nameop(c, e->v.Name.id, Load))
3346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347 VISIT(c, expr, s->v.AugAssign.value);
3348 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3349 return compiler_nameop(c, e->v.Name.id, Store);
3350 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003351 PyErr_Format(PyExc_SystemError,
3352 "invalid node type (%d) for augmented assignment",
3353 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355 }
3356 return 1;
3357}
3358
3359static int
3360compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3361{
3362 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003363 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3364 PyErr_SetString(PyExc_SystemError,
3365 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003367 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368 f = &c->u->u_fblock[c->u->u_nfblocks++];
3369 f->fb_type = t;
3370 f->fb_block = b;
3371 return 1;
3372}
3373
3374static void
3375compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3376{
3377 struct compiler_unit *u = c->u;
3378 assert(u->u_nfblocks > 0);
3379 u->u_nfblocks--;
3380 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3381 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3382}
3383
Thomas Wouters89f507f2006-12-13 04:49:30 +00003384static int
3385compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003386 int i;
3387 struct compiler_unit *u = c->u;
3388 for (i = 0; i < u->u_nfblocks; ++i) {
3389 if (u->u_fblock[i].fb_type == LOOP)
3390 return 1;
3391 }
3392 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003393}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394/* Raises a SyntaxError and returns 0.
3395 If something goes wrong, a different exception may be raised.
3396*/
3397
3398static int
3399compiler_error(struct compiler *c, const char *errstr)
3400{
3401 PyObject *loc;
3402 PyObject *u = NULL, *v = NULL;
3403
3404 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3405 if (!loc) {
3406 Py_INCREF(Py_None);
3407 loc = Py_None;
3408 }
3409 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3410 Py_None, loc);
3411 if (!u)
3412 goto exit;
3413 v = Py_BuildValue("(zO)", errstr, u);
3414 if (!v)
3415 goto exit;
3416 PyErr_SetObject(PyExc_SyntaxError, v);
3417 exit:
3418 Py_DECREF(loc);
3419 Py_XDECREF(u);
3420 Py_XDECREF(v);
3421 return 0;
3422}
3423
3424static int
3425compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003426 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003428 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003429
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003430 /* XXX this code is duplicated */
3431 switch (ctx) {
3432 case AugLoad: /* fall through to Load */
3433 case Load: op = BINARY_SUBSCR; break;
3434 case AugStore:/* fall through to Store */
3435 case Store: op = STORE_SUBSCR; break;
3436 case Del: op = DELETE_SUBSCR; break;
3437 case Param:
3438 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003439 "invalid %s kind %d in subscript\n",
3440 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003441 return 0;
3442 }
3443 if (ctx == AugLoad) {
3444 ADDOP_I(c, DUP_TOPX, 2);
3445 }
3446 else if (ctx == AugStore) {
3447 ADDOP(c, ROT_THREE);
3448 }
3449 ADDOP(c, op);
3450 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003451}
3452
3453static int
3454compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3455{
3456 int n = 2;
3457 assert(s->kind == Slice_kind);
3458
3459 /* only handles the cases where BUILD_SLICE is emitted */
3460 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003461 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462 }
3463 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003464 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003465 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003466
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469 }
3470 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003471 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003472 }
3473
3474 if (s->v.Slice.step) {
3475 n++;
3476 VISIT(c, expr, s->v.Slice.step);
3477 }
3478 ADDOP_I(c, BUILD_SLICE, n);
3479 return 1;
3480}
3481
3482static int
3483compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3484{
3485 int op = 0, slice_offset = 0, stack_count = 0;
3486
3487 assert(s->v.Slice.step == NULL);
3488 if (s->v.Slice.lower) {
3489 slice_offset++;
3490 stack_count++;
3491 if (ctx != AugStore)
3492 VISIT(c, expr, s->v.Slice.lower);
3493 }
3494 if (s->v.Slice.upper) {
3495 slice_offset += 2;
3496 stack_count++;
3497 if (ctx != AugStore)
3498 VISIT(c, expr, s->v.Slice.upper);
3499 }
3500
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003501 if (ctx == AugLoad) {
3502 switch (stack_count) {
3503 case 0: ADDOP(c, DUP_TOP); break;
3504 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3505 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3506 }
3507 }
3508 else if (ctx == AugStore) {
3509 switch (stack_count) {
3510 case 0: ADDOP(c, ROT_TWO); break;
3511 case 1: ADDOP(c, ROT_THREE); break;
3512 case 2: ADDOP(c, ROT_FOUR); break;
3513 }
3514 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515
3516 switch (ctx) {
3517 case AugLoad: /* fall through to Load */
3518 case Load: op = SLICE; break;
3519 case AugStore:/* fall through to Store */
3520 case Store: op = STORE_SLICE; break;
3521 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003522 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003523 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003524 PyErr_SetString(PyExc_SystemError,
3525 "param invalid in simple slice");
3526 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 }
3528
3529 ADDOP(c, op + slice_offset);
3530 return 1;
3531}
3532
3533static int
3534compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3535 expr_context_ty ctx)
3536{
3537 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 case Slice_kind:
3539 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 case Index_kind:
3541 VISIT(c, expr, s->v.Index.value);
3542 break;
3543 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003544 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003545 PyErr_SetString(PyExc_SystemError,
3546 "extended slice invalid in nested slice");
3547 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548 }
3549 return 1;
3550}
3551
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552static int
3553compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3554{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003555 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003557 case Index_kind:
3558 kindname = "index";
3559 if (ctx != AugStore) {
3560 VISIT(c, expr, s->v.Index.value);
3561 }
3562 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003564 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 if (!s->v.Slice.step)
3566 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003567 if (ctx != AugStore) {
3568 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569 return 0;
3570 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003571 break;
3572 case ExtSlice_kind:
3573 kindname = "extended slice";
3574 if (ctx != AugStore) {
3575 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3576 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003577 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003578 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003579 if (!compiler_visit_nested_slice(c, sub, ctx))
3580 return 0;
3581 }
3582 ADDOP_I(c, BUILD_TUPLE, n);
3583 }
3584 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003585 default:
3586 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003587 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003588 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003590 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591}
3592
Thomas Wouters89f507f2006-12-13 04:49:30 +00003593/* End of the compiler section, beginning of the assembler section */
3594
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595/* do depth-first search of basic block graph, starting with block.
3596 post records the block indices in post-order.
3597
3598 XXX must handle implicit jumps from one block to next
3599*/
3600
Thomas Wouters89f507f2006-12-13 04:49:30 +00003601struct assembler {
3602 PyObject *a_bytecode; /* string containing bytecode */
3603 int a_offset; /* offset into bytecode */
3604 int a_nblocks; /* number of reachable blocks */
3605 basicblock **a_postorder; /* list of blocks in dfs postorder */
3606 PyObject *a_lnotab; /* string containing lnotab */
3607 int a_lnotab_off; /* offset into lnotab */
3608 int a_lineno; /* last lineno of emitted instruction */
3609 int a_lineno_off; /* bytecode offset of last lineno */
3610};
3611
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612static void
3613dfs(struct compiler *c, basicblock *b, struct assembler *a)
3614{
3615 int i;
3616 struct instr *instr = NULL;
3617
3618 if (b->b_seen)
3619 return;
3620 b->b_seen = 1;
3621 if (b->b_next != NULL)
3622 dfs(c, b->b_next, a);
3623 for (i = 0; i < b->b_iused; i++) {
3624 instr = &b->b_instr[i];
3625 if (instr->i_jrel || instr->i_jabs)
3626 dfs(c, instr->i_target, a);
3627 }
3628 a->a_postorder[a->a_nblocks++] = b;
3629}
3630
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003631static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3633{
3634 int i;
3635 struct instr *instr;
3636 if (b->b_seen || b->b_startdepth >= depth)
3637 return maxdepth;
3638 b->b_seen = 1;
3639 b->b_startdepth = depth;
3640 for (i = 0; i < b->b_iused; i++) {
3641 instr = &b->b_instr[i];
3642 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3643 if (depth > maxdepth)
3644 maxdepth = depth;
3645 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3646 if (instr->i_jrel || instr->i_jabs) {
3647 maxdepth = stackdepth_walk(c, instr->i_target,
3648 depth, maxdepth);
3649 if (instr->i_opcode == JUMP_ABSOLUTE ||
3650 instr->i_opcode == JUMP_FORWARD) {
3651 goto out; /* remaining code is dead */
3652 }
3653 }
3654 }
3655 if (b->b_next)
3656 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3657out:
3658 b->b_seen = 0;
3659 return maxdepth;
3660}
3661
3662/* Find the flow path that needs the largest stack. We assume that
3663 * cycles in the flow graph have no net effect on the stack depth.
3664 */
3665static int
3666stackdepth(struct compiler *c)
3667{
3668 basicblock *b, *entryblock;
3669 entryblock = NULL;
3670 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3671 b->b_seen = 0;
3672 b->b_startdepth = INT_MIN;
3673 entryblock = b;
3674 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003675 if (!entryblock)
3676 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677 return stackdepth_walk(c, entryblock, 0, 0);
3678}
3679
3680static int
3681assemble_init(struct assembler *a, int nblocks, int firstlineno)
3682{
3683 memset(a, 0, sizeof(struct assembler));
3684 a->a_lineno = firstlineno;
3685 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3686 if (!a->a_bytecode)
3687 return 0;
3688 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3689 if (!a->a_lnotab)
3690 return 0;
3691 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003692 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003693 if (!a->a_postorder) {
3694 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003696 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003697 return 1;
3698}
3699
3700static void
3701assemble_free(struct assembler *a)
3702{
3703 Py_XDECREF(a->a_bytecode);
3704 Py_XDECREF(a->a_lnotab);
3705 if (a->a_postorder)
3706 PyObject_Free(a->a_postorder);
3707}
3708
3709/* Return the size of a basic block in bytes. */
3710
3711static int
3712instrsize(struct instr *instr)
3713{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003714 if (!instr->i_hasarg)
3715 return 1;
3716 if (instr->i_oparg > 0xffff)
3717 return 6;
3718 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719}
3720
3721static int
3722blocksize(basicblock *b)
3723{
3724 int i;
3725 int size = 0;
3726
3727 for (i = 0; i < b->b_iused; i++)
3728 size += instrsize(&b->b_instr[i]);
3729 return size;
3730}
3731
3732/* All about a_lnotab.
3733
3734c_lnotab is an array of unsigned bytes disguised as a Python string.
3735It is used to map bytecode offsets to source code line #s (when needed
3736for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003737
Tim Peters2a7f3842001-06-09 09:26:21 +00003738The array is conceptually a list of
3739 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003740pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003741
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003742 byte code offset source code line number
3743 0 1
3744 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003745 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003746 350 307
3747 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003748
3749The first trick is that these numbers aren't stored, only the increments
3750from one row to the next (this doesn't really work, but it's a start):
3751
3752 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3753
3754The second trick is that an unsigned byte can't hold negative values, or
3755values larger than 255, so (a) there's a deep assumption that byte code
3756offsets and their corresponding line #s both increase monotonically, and (b)
3757if at least one column jumps by more than 255 from one row to the next, more
3758than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003759from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003760part. A user of c_lnotab desiring to find the source line number
3761corresponding to a bytecode address A should do something like this
3762
3763 lineno = addr = 0
3764 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003765 addr += addr_incr
3766 if addr > A:
3767 return lineno
3768 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003769
3770In order for this to work, when the addr field increments by more than 255,
3771the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003772increment is < 256. So, in the example above, assemble_lnotab (it used
3773to be called com_set_lineno) should not (as was actually done until 2.2)
3774expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003775 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003776*/
3777
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003778static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003780{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003781 int d_bytecode, d_lineno;
3782 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003783 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784
3785 d_bytecode = a->a_offset - a->a_lineno_off;
3786 d_lineno = i->i_lineno - a->a_lineno;
3787
3788 assert(d_bytecode >= 0);
3789 assert(d_lineno >= 0);
3790
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003791 /* XXX(nnorwitz): is there a better way to handle this?
3792 for loops are special, we want to be able to trace them
3793 each time around, so we need to set an extra line number. */
3794 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003795 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003796
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003798 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799 nbytes = a->a_lnotab_off + 2 * ncodes;
3800 len = PyString_GET_SIZE(a->a_lnotab);
3801 if (nbytes >= len) {
3802 if (len * 2 < nbytes)
3803 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003804 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805 len *= 2;
3806 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3807 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003808 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003809 lnotab = (unsigned char *)
3810 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003811 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812 *lnotab++ = 255;
3813 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003814 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 d_bytecode -= ncodes * 255;
3816 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 assert(d_bytecode <= 255);
3819 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003820 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003821 nbytes = a->a_lnotab_off + 2 * ncodes;
3822 len = PyString_GET_SIZE(a->a_lnotab);
3823 if (nbytes >= len) {
3824 if (len * 2 < nbytes)
3825 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003826 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 len *= 2;
3828 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3829 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003830 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003831 lnotab = (unsigned char *)
3832 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003834 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003836 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003837 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003838 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003839 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840 d_lineno -= ncodes * 255;
3841 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003842 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003843
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844 len = PyString_GET_SIZE(a->a_lnotab);
3845 if (a->a_lnotab_off + 2 >= len) {
3846 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003847 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003848 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003849 lnotab = (unsigned char *)
3850 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003851
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003852 a->a_lnotab_off += 2;
3853 if (d_bytecode) {
3854 *lnotab++ = d_bytecode;
3855 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003856 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003857 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003858 *lnotab++ = 0;
3859 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003860 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 a->a_lineno = i->i_lineno;
3862 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003863 return 1;
3864}
3865
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003866/* assemble_emit()
3867 Extend the bytecode with a new instruction.
3868 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003869*/
3870
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003871static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003873{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003874 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003875 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 char *code;
3877
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003878 size = instrsize(i);
3879 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003881 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003882 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003884 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 if (a->a_offset + size >= len) {
3886 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003887 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003888 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3890 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003891 if (size == 6) {
3892 assert(i->i_hasarg);
3893 *code++ = (char)EXTENDED_ARG;
3894 *code++ = ext & 0xff;
3895 *code++ = ext >> 8;
3896 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003897 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003899 if (i->i_hasarg) {
3900 assert(size == 3 || size == 6);
3901 *code++ = arg & 0xff;
3902 *code++ = arg >> 8;
3903 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003905}
3906
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003907static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003909{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003911 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003912 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003913
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914 /* Compute the size of each block and fixup jump args.
3915 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003916start:
3917 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003919 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920 bsize = blocksize(b);
3921 b->b_offset = totsize;
3922 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003923 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003924 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003925 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3926 bsize = b->b_offset;
3927 for (i = 0; i < b->b_iused; i++) {
3928 struct instr *instr = &b->b_instr[i];
3929 /* Relative jumps are computed relative to
3930 the instruction pointer after fetching
3931 the jump instruction.
3932 */
3933 bsize += instrsize(instr);
3934 if (instr->i_jabs)
3935 instr->i_oparg = instr->i_target->b_offset;
3936 else if (instr->i_jrel) {
3937 int delta = instr->i_target->b_offset - bsize;
3938 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003939 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003940 else
3941 continue;
3942 if (instr->i_oparg > 0xffff)
3943 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003944 }
3945 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003946
3947 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003948 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003949 with a better solution.
3950
3951 In the meantime, should the goto be dropped in favor
3952 of a loop?
3953
3954 The issue is that in the first loop blocksize() is called
3955 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003956 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003957 i_oparg is calculated in the second loop above.
3958
3959 So we loop until we stop seeing new EXTENDED_ARGs.
3960 The only EXTENDED_ARGs that could be popping up are
3961 ones in jump instructions. So this should converge
3962 fairly quickly.
3963 */
3964 if (last_extended_arg_count != extended_arg_count) {
3965 last_extended_arg_count = extended_arg_count;
3966 goto start;
3967 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003968}
3969
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003970static PyObject *
3971dict_keys_inorder(PyObject *dict, int offset)
3972{
3973 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003974 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003975
3976 tuple = PyTuple_New(size);
3977 if (tuple == NULL)
3978 return NULL;
3979 while (PyDict_Next(dict, &pos, &k, &v)) {
3980 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003981 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003982 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003983 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003984 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003985 PyTuple_SET_ITEM(tuple, i - offset, k);
3986 }
3987 return tuple;
3988}
3989
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003990static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003992{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003993 PySTEntryObject *ste = c->u->u_ste;
3994 int flags = 0, n;
3995 if (ste->ste_type != ModuleBlock)
3996 flags |= CO_NEWLOCALS;
3997 if (ste->ste_type == FunctionBlock) {
3998 if (!ste->ste_unoptimized)
3999 flags |= CO_OPTIMIZED;
4000 if (ste->ste_nested)
4001 flags |= CO_NESTED;
4002 if (ste->ste_generator)
4003 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004004 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005 if (ste->ste_varargs)
4006 flags |= CO_VARARGS;
4007 if (ste->ste_varkeywords)
4008 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004009 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004010 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004011
4012 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004013 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004014
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004015 n = PyDict_Size(c->u->u_freevars);
4016 if (n < 0)
4017 return -1;
4018 if (n == 0) {
4019 n = PyDict_Size(c->u->u_cellvars);
4020 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004021 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004022 if (n == 0) {
4023 flags |= CO_NOFREE;
4024 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004025 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004026
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004027 return flags;
4028}
4029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030static PyCodeObject *
4031makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004032{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004033 PyObject *tmp;
4034 PyCodeObject *co = NULL;
4035 PyObject *consts = NULL;
4036 PyObject *names = NULL;
4037 PyObject *varnames = NULL;
4038 PyObject *filename = NULL;
4039 PyObject *name = NULL;
4040 PyObject *freevars = NULL;
4041 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004042 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004043 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004045 tmp = dict_keys_inorder(c->u->u_consts, 0);
4046 if (!tmp)
4047 goto error;
4048 consts = PySequence_List(tmp); /* optimize_code requires a list */
4049 Py_DECREF(tmp);
4050
4051 names = dict_keys_inorder(c->u->u_names, 0);
4052 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4053 if (!consts || !names || !varnames)
4054 goto error;
4055
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004056 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4057 if (!cellvars)
4058 goto error;
4059 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4060 if (!freevars)
4061 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004062 filename = PyString_FromString(c->c_filename);
4063 if (!filename)
4064 goto error;
4065
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004066 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067 flags = compute_code_flags(c);
4068 if (flags < 0)
4069 goto error;
4070
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004071 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004072 if (!bytecode)
4073 goto error;
4074
4075 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4076 if (!tmp)
4077 goto error;
4078 Py_DECREF(consts);
4079 consts = tmp;
4080
Guido van Rossum4f72a782006-10-27 23:31:49 +00004081 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4082 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083 bytecode, consts, names, varnames,
4084 freevars, cellvars,
4085 filename, c->u->u_name,
4086 c->u->u_firstlineno,
4087 a->a_lnotab);
4088 error:
4089 Py_XDECREF(consts);
4090 Py_XDECREF(names);
4091 Py_XDECREF(varnames);
4092 Py_XDECREF(filename);
4093 Py_XDECREF(name);
4094 Py_XDECREF(freevars);
4095 Py_XDECREF(cellvars);
4096 Py_XDECREF(bytecode);
4097 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004098}
4099
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004100
4101/* For debugging purposes only */
4102#if 0
4103static void
4104dump_instr(const struct instr *i)
4105{
4106 const char *jrel = i->i_jrel ? "jrel " : "";
4107 const char *jabs = i->i_jabs ? "jabs " : "";
4108 char arg[128];
4109
4110 *arg = '\0';
4111 if (i->i_hasarg)
4112 sprintf(arg, "arg: %d ", i->i_oparg);
4113
4114 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4115 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4116}
4117
4118static void
4119dump_basicblock(const basicblock *b)
4120{
4121 const char *seen = b->b_seen ? "seen " : "";
4122 const char *b_return = b->b_return ? "return " : "";
4123 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4124 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4125 if (b->b_instr) {
4126 int i;
4127 for (i = 0; i < b->b_iused; i++) {
4128 fprintf(stderr, " [%02d] ", i);
4129 dump_instr(b->b_instr + i);
4130 }
4131 }
4132}
4133#endif
4134
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004135static PyCodeObject *
4136assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004137{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 basicblock *b, *entryblock;
4139 struct assembler a;
4140 int i, j, nblocks;
4141 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004142
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004143 /* Make sure every block that falls off the end returns None.
4144 XXX NEXT_BLOCK() isn't quite right, because if the last
4145 block ends with a jump or return b_next shouldn't set.
4146 */
4147 if (!c->u->u_curblock->b_return) {
4148 NEXT_BLOCK(c);
4149 if (addNone)
4150 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4151 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004152 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004153
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004154 nblocks = 0;
4155 entryblock = NULL;
4156 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4157 nblocks++;
4158 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004159 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004160
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004161 /* Set firstlineno if it wasn't explicitly set. */
4162 if (!c->u->u_firstlineno) {
4163 if (entryblock && entryblock->b_instr)
4164 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4165 else
4166 c->u->u_firstlineno = 1;
4167 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004168 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4169 goto error;
4170 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004171
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004173 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004174
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004175 /* Emit code in reverse postorder from dfs. */
4176 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004177 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178 for (j = 0; j < b->b_iused; j++)
4179 if (!assemble_emit(&a, &b->b_instr[j]))
4180 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004181 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004182
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4184 goto error;
4185 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4186 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004188 co = makecode(c, &a);
4189 error:
4190 assemble_free(&a);
4191 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004192}