blob: 374cf1c4ef5457d50d77c8d75ff696f7dd85d3c4 [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.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000146 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
194static int expr_constant(expr_ty e);
195
Guido van Rossumc2e20742006-02-27 22:32:47 +0000196static int compiler_with(struct compiler *, stmt_ty);
197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198static PyCodeObject *assemble(struct compiler *, int addNone);
199static PyObject *__doc__;
200
201PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000202_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000203{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204 /* Name mangling: __private becomes _classname__private.
205 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206 const char *p, *name = PyString_AsString(ident);
207 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208 size_t nlen, plen;
Neal Norwitz84167d02006-08-12 01:45:47 +0000209 if (privateobj == NULL || !PyString_Check(privateobj) ||
210 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000213 }
Anthony Baxter7b782b62006-04-11 12:01:56 +0000214 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215 nlen = strlen(name);
216 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 /* Strip leading underscores from class name */
221 while (*p == '_')
222 p++;
223 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
229 if (!ident)
230 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000231 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000232 buffer = PyString_AS_STRING(ident);
233 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234 strncpy(buffer+1, p, plen);
235 strcpy(buffer+1+plen, name);
236 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000237}
238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239static int
240compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244 c->c_stack = PyList_New(0);
245 if (!c->c_stack)
246 return 0;
247
248 return 1;
249}
250
251PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000252PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000253 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254{
255 struct compiler c;
256 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000257 PyCompilerFlags local_flags;
258 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000260 if (!__doc__) {
261 __doc__ = PyString_InternFromString("__doc__");
262 if (!__doc__)
263 return NULL;
264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265
266 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000267 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000269 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 c.c_future = PyFuture_FromAST(mod, filename);
271 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000272 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000274 local_flags.cf_flags = 0;
275 flags = &local_flags;
276 }
277 merged = c.c_future->ff_features | flags->cf_flags;
278 c.c_future->ff_features = merged;
279 flags->cf_flags = merged;
280 c.c_flags = flags;
281 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000282
283 c.c_st = PySymtable_Build(mod, filename, c.c_future);
284 if (c.c_st == NULL) {
285 if (!PyErr_Occurred())
286 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000287 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288 }
289
290 /* XXX initialize to NULL for now, need to handle */
291 c.c_encoding = NULL;
292
293 co = compiler_mod(&c, mod);
294
Thomas Wouters1175c432006-02-27 22:49:54 +0000295 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000297 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298 return co;
299}
300
301PyCodeObject *
302PyNode_Compile(struct _node *n, const char *filename)
303{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000304 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000305 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000306 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000307 if (!arena)
308 return NULL;
309 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000310 if (mod)
311 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000312 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000313 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000314}
315
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319 if (c->c_st)
320 PySymtable_Free(c->c_st);
321 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000322 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000324}
325
Guido van Rossum79f25d91997-04-29 20:08:16 +0000326static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000328{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000330 PyObject *v, *k;
331 PyObject *dict = PyDict_New();
332 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000333
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 n = PyList_Size(list);
335 for (i = 0; i < n; i++) {
336 v = PyInt_FromLong(i);
337 if (!v) {
338 Py_DECREF(dict);
339 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000340 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000341 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000342 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
344 Py_XDECREF(k);
345 Py_DECREF(v);
346 Py_DECREF(dict);
347 return NULL;
348 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000349 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000351 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352 return dict;
353}
354
355/* Return new dict containing names from src that match scope(s).
356
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000357src is a symbol table dictionary. If the scope of a name matches
358either scope_type or flag is set, insert it into the new dict. The
359values are integers, starting at offset and increasing by one for
360each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361*/
362
363static PyObject *
364dictbytype(PyObject *src, int scope_type, int flag, int offset)
365{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000366 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367 PyObject *k, *v, *dest = PyDict_New();
368
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 assert(offset >= 0);
370 if (dest == NULL)
371 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
373 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000374 /* XXX this should probably be a macro in symtable.h */
375 assert(PyInt_Check(v));
376 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000378 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
379 PyObject *tuple, *item = PyInt_FromLong(i);
380 if (item == NULL) {
381 Py_DECREF(dest);
382 return NULL;
383 }
384 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000385 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000386 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
387 Py_DECREF(item);
388 Py_DECREF(dest);
389 Py_XDECREF(tuple);
390 return NULL;
391 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000393 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395 }
396 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000397}
398
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399/*
400
401Leave this debugging code for just a little longer.
402
403static void
404compiler_display_symbols(PyObject *name, PyObject *symbols)
405{
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406PyObject *key, *value;
407int flags;
408Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
411while (PyDict_Next(symbols, &pos, &key, &value)) {
412flags = PyInt_AsLong(value);
413fprintf(stderr, "var %s:", PyString_AS_STRING(key));
414if (flags & DEF_GLOBAL)
415fprintf(stderr, " declared_global");
416if (flags & DEF_LOCAL)
417fprintf(stderr, " local");
418if (flags & DEF_PARAM)
419fprintf(stderr, " param");
420if (flags & DEF_STAR)
421fprintf(stderr, " stararg");
422if (flags & DEF_DOUBLESTAR)
423fprintf(stderr, " starstar");
424if (flags & DEF_INTUPLE)
425fprintf(stderr, " tuple");
426if (flags & DEF_FREE)
427fprintf(stderr, " free");
428if (flags & DEF_FREE_GLOBAL)
429fprintf(stderr, " global");
430if (flags & DEF_FREE_CLASS)
431fprintf(stderr, " free/class");
432if (flags & DEF_IMPORT)
433fprintf(stderr, " import");
434fprintf(stderr, "\n");
435}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436 fprintf(stderr, "\n");
437}
438*/
439
440static void
441compiler_unit_check(struct compiler_unit *u)
442{
443 basicblock *block;
444 for (block = u->u_blocks; block != NULL; block = block->b_list) {
445 assert(block != (void *)0xcbcbcbcb);
446 assert(block != (void *)0xfbfbfbfb);
447 assert(block != (void *)0xdbdbdbdb);
448 if (block->b_instr != NULL) {
449 assert(block->b_ialloc > 0);
450 assert(block->b_iused > 0);
451 assert(block->b_ialloc >= block->b_iused);
452 }
453 else {
454 assert (block->b_iused == 0);
455 assert (block->b_ialloc == 0);
456 }
457 }
458}
459
460static void
461compiler_unit_free(struct compiler_unit *u)
462{
463 basicblock *b, *next;
464
465 compiler_unit_check(u);
466 b = u->u_blocks;
467 while (b != NULL) {
468 if (b->b_instr)
469 PyObject_Free((void *)b->b_instr);
470 next = b->b_list;
471 PyObject_Free((void *)b);
472 b = next;
473 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000474 Py_CLEAR(u->u_ste);
475 Py_CLEAR(u->u_name);
476 Py_CLEAR(u->u_consts);
477 Py_CLEAR(u->u_names);
478 Py_CLEAR(u->u_varnames);
479 Py_CLEAR(u->u_freevars);
480 Py_CLEAR(u->u_cellvars);
481 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000482 PyObject_Free(u);
483}
484
485static int
486compiler_enter_scope(struct compiler *c, identifier name, void *key,
487 int lineno)
488{
489 struct compiler_unit *u;
490
Anthony Baxter7b782b62006-04-11 12:01:56 +0000491 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
492 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000493 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000494 PyErr_NoMemory();
495 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000496 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000497 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498 u->u_argcount = 0;
499 u->u_ste = PySymtable_Lookup(c->c_st, key);
500 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000501 compiler_unit_free(u);
502 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503 }
504 Py_INCREF(name);
505 u->u_name = name;
506 u->u_varnames = list2dict(u->u_ste->ste_varnames);
507 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000508 if (!u->u_varnames || !u->u_cellvars) {
509 compiler_unit_free(u);
510 return 0;
511 }
512
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000514 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000515 if (!u->u_freevars) {
516 compiler_unit_free(u);
517 return 0;
518 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519
520 u->u_blocks = NULL;
521 u->u_tmpname = 0;
522 u->u_nfblocks = 0;
523 u->u_firstlineno = lineno;
524 u->u_lineno = 0;
525 u->u_lineno_set = false;
526 u->u_consts = PyDict_New();
527 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000528 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529 return 0;
530 }
531 u->u_names = PyDict_New();
532 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000533 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534 return 0;
535 }
536
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000537 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538
539 /* Push the old compiler_unit on the stack. */
540 if (c->u) {
541 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000542 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
543 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000544 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545 return 0;
546 }
547 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000548 u->u_private = c->u->u_private;
549 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550 }
551 c->u = u;
552
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000553 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000554 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555 return 0;
556
557 return 1;
558}
559
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000560static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561compiler_exit_scope(struct compiler *c)
562{
563 int n;
564 PyObject *wrapper;
565
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000566 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567 compiler_unit_free(c->u);
568 /* Restore c->u to the parent unit. */
569 n = PyList_GET_SIZE(c->c_stack) - 1;
570 if (n >= 0) {
571 wrapper = PyList_GET_ITEM(c->c_stack, n);
572 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000573 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000574 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000576 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000577 compiler_unit_check(c->u);
578 }
579 else
580 c->u = NULL;
581
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582}
583
Guido van Rossumc2e20742006-02-27 22:32:47 +0000584/* Allocate a new "anonymous" local variable.
585 Used by list comprehensions and with statements.
586*/
587
588static PyObject *
589compiler_new_tmpname(struct compiler *c)
590{
591 char tmpname[256];
592 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
593 return PyString_FromString(tmpname);
594}
595
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000596/* Allocate a new block and return a pointer to it.
597 Returns NULL on error.
598*/
599
600static basicblock *
601compiler_new_block(struct compiler *c)
602{
603 basicblock *b;
604 struct compiler_unit *u;
605
606 u = c->u;
607 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000608 if (b == NULL) {
609 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000611 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +0000613 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000614 b->b_list = u->u_blocks;
615 u->u_blocks = b;
616 return b;
617}
618
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619static basicblock *
620compiler_use_new_block(struct compiler *c)
621{
622 basicblock *block = compiler_new_block(c);
623 if (block == NULL)
624 return NULL;
625 c->u->u_curblock = block;
626 return block;
627}
628
629static basicblock *
630compiler_next_block(struct compiler *c)
631{
632 basicblock *block = compiler_new_block(c);
633 if (block == NULL)
634 return NULL;
635 c->u->u_curblock->b_next = block;
636 c->u->u_curblock = block;
637 return block;
638}
639
640static basicblock *
641compiler_use_next_block(struct compiler *c, basicblock *block)
642{
643 assert(block != NULL);
644 c->u->u_curblock->b_next = block;
645 c->u->u_curblock = block;
646 return block;
647}
648
649/* Returns the offset of the next instruction in the current block's
650 b_instr array. Resizes the b_instr as necessary.
651 Returns -1 on failure.
652 */
653
654static int
655compiler_next_instr(struct compiler *c, basicblock *b)
656{
657 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000658 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000659 b->b_instr = (struct instr *)PyObject_Malloc(
660 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000661 if (b->b_instr == NULL) {
662 PyErr_NoMemory();
663 return -1;
664 }
665 b->b_ialloc = DEFAULT_BLOCK_SIZE;
666 memset((char *)b->b_instr, 0,
667 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000670 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000671 size_t oldsize, newsize;
672 oldsize = b->b_ialloc * sizeof(struct instr);
673 newsize = oldsize << 1;
674 if (newsize == 0) {
675 PyErr_NoMemory();
676 return -1;
677 }
678 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000679 tmp = (struct instr *)PyObject_Realloc(
Anthony Baxter7b782b62006-04-11 12:01:56 +0000680 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000681 if (tmp == NULL) {
682 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000684 }
685 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
687 }
688 return b->b_iused++;
689}
690
Jeremy Hylton12603c42006-04-01 16:18:02 +0000691/* Set the i_lineno member of the instruction at offse off if the
692 line number for the current expression/statement (?) has not
693 already been set. If it has been set, the call has no effect.
694
695 Every time a new node is b
696 */
697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000698static void
699compiler_set_lineno(struct compiler *c, int off)
700{
701 basicblock *b;
702 if (c->u->u_lineno_set)
703 return;
704 c->u->u_lineno_set = true;
705 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000706 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000707}
708
709static int
710opcode_stack_effect(int opcode, int oparg)
711{
712 switch (opcode) {
713 case POP_TOP:
714 return -1;
715 case ROT_TWO:
716 case ROT_THREE:
717 return 0;
718 case DUP_TOP:
719 return 1;
720 case ROT_FOUR:
721 return 0;
722
723 case UNARY_POSITIVE:
724 case UNARY_NEGATIVE:
725 case UNARY_NOT:
726 case UNARY_CONVERT:
727 case UNARY_INVERT:
728 return 0;
729
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000730 case LIST_APPEND:
731 return -2;
732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733 case BINARY_POWER:
734 case BINARY_MULTIPLY:
735 case BINARY_DIVIDE:
736 case BINARY_MODULO:
737 case BINARY_ADD:
738 case BINARY_SUBTRACT:
739 case BINARY_SUBSCR:
740 case BINARY_FLOOR_DIVIDE:
741 case BINARY_TRUE_DIVIDE:
742 return -1;
743 case INPLACE_FLOOR_DIVIDE:
744 case INPLACE_TRUE_DIVIDE:
745 return -1;
746
747 case SLICE+0:
748 return 1;
749 case SLICE+1:
750 return 0;
751 case SLICE+2:
752 return 0;
753 case SLICE+3:
754 return -1;
755
756 case STORE_SLICE+0:
757 return -2;
758 case STORE_SLICE+1:
759 return -3;
760 case STORE_SLICE+2:
761 return -3;
762 case STORE_SLICE+3:
763 return -4;
764
765 case DELETE_SLICE+0:
766 return -1;
767 case DELETE_SLICE+1:
768 return -2;
769 case DELETE_SLICE+2:
770 return -2;
771 case DELETE_SLICE+3:
772 return -3;
773
774 case INPLACE_ADD:
775 case INPLACE_SUBTRACT:
776 case INPLACE_MULTIPLY:
777 case INPLACE_DIVIDE:
778 case INPLACE_MODULO:
779 return -1;
780 case STORE_SUBSCR:
781 return -3;
782 case DELETE_SUBSCR:
783 return -2;
784
785 case BINARY_LSHIFT:
786 case BINARY_RSHIFT:
787 case BINARY_AND:
788 case BINARY_XOR:
789 case BINARY_OR:
790 return -1;
791 case INPLACE_POWER:
792 return -1;
793 case GET_ITER:
794 return 0;
795
796 case PRINT_EXPR:
797 return -1;
798 case PRINT_ITEM:
799 return -1;
800 case PRINT_NEWLINE:
801 return 0;
802 case PRINT_ITEM_TO:
803 return -2;
804 case PRINT_NEWLINE_TO:
805 return -1;
806 case INPLACE_LSHIFT:
807 case INPLACE_RSHIFT:
808 case INPLACE_AND:
809 case INPLACE_XOR:
810 case INPLACE_OR:
811 return -1;
812 case BREAK_LOOP:
813 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000814 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000815 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816 case LOAD_LOCALS:
817 return 1;
818 case RETURN_VALUE:
819 return -1;
820 case IMPORT_STAR:
821 return -1;
822 case EXEC_STMT:
823 return -3;
824 case YIELD_VALUE:
825 return 0;
826
827 case POP_BLOCK:
828 return 0;
829 case END_FINALLY:
830 return -1; /* or -2 or -3 if exception occurred */
831 case BUILD_CLASS:
832 return -2;
833
834 case STORE_NAME:
835 return -1;
836 case DELETE_NAME:
837 return 0;
838 case UNPACK_SEQUENCE:
839 return oparg-1;
840 case FOR_ITER:
841 return 1;
842
843 case STORE_ATTR:
844 return -2;
845 case DELETE_ATTR:
846 return -1;
847 case STORE_GLOBAL:
848 return -1;
849 case DELETE_GLOBAL:
850 return 0;
851 case DUP_TOPX:
852 return oparg;
853 case LOAD_CONST:
854 return 1;
855 case LOAD_NAME:
856 return 1;
857 case BUILD_TUPLE:
858 case BUILD_LIST:
859 return 1-oparg;
860 case BUILD_MAP:
861 return 1;
862 case LOAD_ATTR:
863 return 0;
864 case COMPARE_OP:
865 return -1;
866 case IMPORT_NAME:
867 return 0;
868 case IMPORT_FROM:
869 return 1;
870
871 case JUMP_FORWARD:
872 case JUMP_IF_FALSE:
873 case JUMP_IF_TRUE:
874 case JUMP_ABSOLUTE:
875 return 0;
876
877 case LOAD_GLOBAL:
878 return 1;
879
880 case CONTINUE_LOOP:
881 return 0;
882 case SETUP_LOOP:
883 return 0;
884 case SETUP_EXCEPT:
885 case SETUP_FINALLY:
886 return 3; /* actually pushed by an exception */
887
888 case LOAD_FAST:
889 return 1;
890 case STORE_FAST:
891 return -1;
892 case DELETE_FAST:
893 return 0;
894
895 case RAISE_VARARGS:
896 return -oparg;
897#define NARGS(o) (((o) % 256) + 2*((o) / 256))
898 case CALL_FUNCTION:
899 return -NARGS(oparg);
900 case CALL_FUNCTION_VAR:
901 case CALL_FUNCTION_KW:
902 return -NARGS(oparg)-1;
903 case CALL_FUNCTION_VAR_KW:
904 return -NARGS(oparg)-2;
905#undef NARGS
906 case MAKE_FUNCTION:
907 return -oparg;
908 case BUILD_SLICE:
909 if (oparg == 3)
910 return -2;
911 else
912 return -1;
913
914 case MAKE_CLOSURE:
915 return -oparg;
916 case LOAD_CLOSURE:
917 return 1;
918 case LOAD_DEREF:
919 return 1;
920 case STORE_DEREF:
921 return -1;
922 default:
923 fprintf(stderr, "opcode = %d\n", opcode);
924 Py_FatalError("opcode_stack_effect()");
925
926 }
927 return 0; /* not reachable */
928}
929
930/* Add an opcode with no argument.
931 Returns 0 on failure, 1 on success.
932*/
933
934static int
935compiler_addop(struct compiler *c, int opcode)
936{
937 basicblock *b;
938 struct instr *i;
939 int off;
940 off = compiler_next_instr(c, c->u->u_curblock);
941 if (off < 0)
942 return 0;
943 b = c->u->u_curblock;
944 i = &b->b_instr[off];
945 i->i_opcode = opcode;
946 i->i_hasarg = 0;
947 if (opcode == RETURN_VALUE)
948 b->b_return = 1;
949 compiler_set_lineno(c, off);
950 return 1;
951}
952
953static int
954compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
955{
956 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000957 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000958
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000959 /* necessary to make sure types aren't coerced (e.g., int and long) */
960 t = PyTuple_Pack(2, o, o->ob_type);
961 if (t == NULL)
962 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
964 v = PyDict_GetItem(dict, t);
965 if (!v) {
966 arg = PyDict_Size(dict);
967 v = PyInt_FromLong(arg);
968 if (!v) {
969 Py_DECREF(t);
970 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000971 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 if (PyDict_SetItem(dict, t, v) < 0) {
973 Py_DECREF(t);
974 Py_DECREF(v);
975 return -1;
976 }
977 Py_DECREF(v);
978 }
979 else
980 arg = PyInt_AsLong(v);
981 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983}
984
985static int
986compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
987 PyObject *o)
988{
989 int arg = compiler_add_o(c, dict, o);
990 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992 return compiler_addop_i(c, opcode, arg);
993}
994
995static int
996compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000997 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998{
999 int arg;
1000 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1001 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 arg = compiler_add_o(c, dict, mangled);
1004 Py_DECREF(mangled);
1005 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007 return compiler_addop_i(c, opcode, arg);
1008}
1009
1010/* Add an opcode with an integer argument.
1011 Returns 0 on failure, 1 on success.
1012*/
1013
1014static int
1015compiler_addop_i(struct compiler *c, int opcode, int oparg)
1016{
1017 struct instr *i;
1018 int off;
1019 off = compiler_next_instr(c, c->u->u_curblock);
1020 if (off < 0)
1021 return 0;
1022 i = &c->u->u_curblock->b_instr[off];
1023 i->i_opcode = opcode;
1024 i->i_oparg = oparg;
1025 i->i_hasarg = 1;
1026 compiler_set_lineno(c, off);
1027 return 1;
1028}
1029
1030static int
1031compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1032{
1033 struct instr *i;
1034 int off;
1035
1036 assert(b != NULL);
1037 off = compiler_next_instr(c, c->u->u_curblock);
1038 if (off < 0)
1039 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040 i = &c->u->u_curblock->b_instr[off];
1041 i->i_opcode = opcode;
1042 i->i_target = b;
1043 i->i_hasarg = 1;
1044 if (absolute)
1045 i->i_jabs = 1;
1046 else
1047 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001048 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049 return 1;
1050}
1051
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001052/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1053 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054 it as the current block. NEXT_BLOCK() also creates an implicit jump
1055 from the current block to the new block.
1056*/
1057
1058/* XXX The returns inside these macros make it impossible to decref
1059 objects created in the local function.
1060*/
1061
1062
1063#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001064 if (compiler_use_new_block((C)) == NULL) \
1065 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066}
1067
1068#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001069 if (compiler_next_block((C)) == NULL) \
1070 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
1073#define ADDOP(C, OP) { \
1074 if (!compiler_addop((C), (OP))) \
1075 return 0; \
1076}
1077
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001078#define ADDOP_IN_SCOPE(C, OP) { \
1079 if (!compiler_addop((C), (OP))) { \
1080 compiler_exit_scope(c); \
1081 return 0; \
1082 } \
1083}
1084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085#define ADDOP_O(C, OP, O, TYPE) { \
1086 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1087 return 0; \
1088}
1089
1090#define ADDOP_NAME(C, OP, O, TYPE) { \
1091 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1092 return 0; \
1093}
1094
1095#define ADDOP_I(C, OP, O) { \
1096 if (!compiler_addop_i((C), (OP), (O))) \
1097 return 0; \
1098}
1099
1100#define ADDOP_JABS(C, OP, O) { \
1101 if (!compiler_addop_j((C), (OP), (O), 1)) \
1102 return 0; \
1103}
1104
1105#define ADDOP_JREL(C, OP, O) { \
1106 if (!compiler_addop_j((C), (OP), (O), 0)) \
1107 return 0; \
1108}
1109
1110/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1111 the ASDL name to synthesize the name of the C type and the visit function.
1112*/
1113
1114#define VISIT(C, TYPE, V) {\
1115 if (!compiler_visit_ ## TYPE((C), (V))) \
1116 return 0; \
1117}
1118
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001119#define VISIT_IN_SCOPE(C, TYPE, V) {\
1120 if (!compiler_visit_ ## TYPE((C), (V))) { \
1121 compiler_exit_scope(c); \
1122 return 0; \
1123 } \
1124}
1125
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126#define VISIT_SLICE(C, V, CTX) {\
1127 if (!compiler_visit_slice((C), (V), (CTX))) \
1128 return 0; \
1129}
1130
1131#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001134 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001135 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001136 if (!compiler_visit_ ## TYPE((C), elt)) \
1137 return 0; \
1138 } \
1139}
1140
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001141#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001143 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001144 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001145 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001146 if (!compiler_visit_ ## TYPE((C), elt)) { \
1147 compiler_exit_scope(c); \
1148 return 0; \
1149 } \
1150 } \
1151}
1152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153static int
1154compiler_isdocstring(stmt_ty s)
1155{
1156 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001157 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 return s->v.Expr.value->kind == Str_kind;
1159}
1160
1161/* Compile a sequence of statements, checking for a docstring. */
1162
1163static int
1164compiler_body(struct compiler *c, asdl_seq *stmts)
1165{
1166 int i = 0;
1167 stmt_ty st;
1168
1169 if (!asdl_seq_LEN(stmts))
1170 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001171 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 if (compiler_isdocstring(st)) {
1173 i = 1;
1174 VISIT(c, expr, st->v.Expr.value);
1175 if (!compiler_nameop(c, __doc__, Store))
1176 return 0;
1177 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001178 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001179 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180 return 1;
1181}
1182
1183static PyCodeObject *
1184compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001185{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001186 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001187 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188 static PyObject *module;
1189 if (!module) {
1190 module = PyString_FromString("<module>");
1191 if (!module)
1192 return NULL;
1193 }
Neal Norwitzed657552006-07-10 00:04:44 +00001194 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1195 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001196 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 switch (mod->kind) {
1198 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001199 if (!compiler_body(c, mod->v.Module.body)) {
1200 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001202 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 break;
1204 case Interactive_kind:
1205 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001206 VISIT_SEQ_IN_SCOPE(c, stmt,
1207 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 break;
1209 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001210 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001211 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 break;
1213 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001214 PyErr_SetString(PyExc_SystemError,
1215 "suite should not be possible");
1216 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001217 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001218 PyErr_Format(PyExc_SystemError,
1219 "module kind %d should not be possible",
1220 mod->kind);
1221 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001222 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223 co = assemble(c, addNone);
1224 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001225 return co;
1226}
1227
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228/* The test for LOCAL must come before the test for FREE in order to
1229 handle classes where name is both local and free. The local var is
1230 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001231*/
1232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233static int
1234get_ref_type(struct compiler *c, PyObject *name)
1235{
1236 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001237 if (scope == 0) {
1238 char buf[350];
1239 PyOS_snprintf(buf, sizeof(buf),
1240 "unknown scope for %.100s in %.100s(%s) in %s\n"
1241 "symbols: %s\nlocals: %s\nglobals: %s\n",
1242 PyString_AS_STRING(name),
1243 PyString_AS_STRING(c->u->u_name),
1244 PyObject_REPR(c->u->u_ste->ste_id),
1245 c->c_filename,
1246 PyObject_REPR(c->u->u_ste->ste_symbols),
1247 PyObject_REPR(c->u->u_varnames),
1248 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 Py_FatalError(buf);
1251 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001252
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001253 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254}
1255
1256static int
1257compiler_lookup_arg(PyObject *dict, PyObject *name)
1258{
1259 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001260 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001262 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001264 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001266 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267 return PyInt_AS_LONG(v);
1268}
1269
1270static int
1271compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1272{
1273 int i, free = PyCode_GetNumFree(co);
1274 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001275 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1276 ADDOP_I(c, MAKE_FUNCTION, args);
1277 return 1;
1278 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279 for (i = 0; i < free; ++i) {
1280 /* Bypass com_addop_varname because it will generate
1281 LOAD_DEREF but LOAD_CLOSURE is needed.
1282 */
1283 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1284 int arg, reftype;
1285
1286 /* Special case: If a class contains a method with a
1287 free variable that has the same name as a method,
1288 the name will be considered free *and* local in the
1289 class. It should be handled by the closure, as
1290 well as by the normal name loookup logic.
1291 */
1292 reftype = get_ref_type(c, name);
1293 if (reftype == CELL)
1294 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1295 else /* (reftype == FREE) */
1296 arg = compiler_lookup_arg(c->u->u_freevars, name);
1297 if (arg == -1) {
1298 printf("lookup %s in %s %d %d\n"
1299 "freevars of %s: %s\n",
1300 PyObject_REPR(name),
1301 PyString_AS_STRING(c->u->u_name),
1302 reftype, arg,
1303 PyString_AS_STRING(co->co_name),
1304 PyObject_REPR(co->co_freevars));
1305 Py_FatalError("compiler_make_closure()");
1306 }
1307 ADDOP_I(c, LOAD_CLOSURE, arg);
1308 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001309 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001311 ADDOP_I(c, MAKE_CLOSURE, args);
1312 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313}
1314
1315static int
1316compiler_decorators(struct compiler *c, asdl_seq* decos)
1317{
1318 int i;
1319
1320 if (!decos)
1321 return 1;
1322
1323 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001324 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325 }
1326 return 1;
1327}
1328
1329static int
1330compiler_arguments(struct compiler *c, arguments_ty args)
1331{
1332 int i;
1333 int n = asdl_seq_LEN(args->args);
1334 /* Correctly handle nested argument lists */
1335 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001336 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337 if (arg->kind == Tuple_kind) {
1338 PyObject *id = PyString_FromFormat(".%d", i);
1339 if (id == NULL) {
1340 return 0;
1341 }
1342 if (!compiler_nameop(c, id, Load)) {
1343 Py_DECREF(id);
1344 return 0;
1345 }
1346 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001347 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348 }
1349 }
1350 return 1;
1351}
1352
1353static int
1354compiler_function(struct compiler *c, stmt_ty s)
1355{
1356 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001357 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358 arguments_ty args = s->v.FunctionDef.args;
1359 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001360 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361 int i, n, docstring;
1362
1363 assert(s->kind == FunctionDef_kind);
1364
1365 if (!compiler_decorators(c, decos))
1366 return 0;
1367 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001368 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1370 s->lineno))
1371 return 0;
1372
Anthony Baxter7b782b62006-04-11 12:01:56 +00001373 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001374 docstring = compiler_isdocstring(st);
1375 if (docstring)
1376 first_const = st->v.Expr.value->v.Str.s;
1377 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001378 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001379 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001380 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001382 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 compiler_arguments(c, args);
1384
1385 c->u->u_argcount = asdl_seq_LEN(args->args);
1386 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001387 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001389 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1390 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 }
1392 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001393 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394 if (co == NULL)
1395 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001397 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001398 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399
1400 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1401 ADDOP_I(c, CALL_FUNCTION, 1);
1402 }
1403
1404 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1405}
1406
1407static int
1408compiler_class(struct compiler *c, stmt_ty s)
1409{
1410 int n;
1411 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001412 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413 /* push class name on stack, needed by BUILD_CLASS */
1414 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1415 /* push the tuple of base classes on the stack */
1416 n = asdl_seq_LEN(s->v.ClassDef.bases);
1417 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001418 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419 ADDOP_I(c, BUILD_TUPLE, n);
1420 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1421 s->lineno))
1422 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001423 c->u->u_private = s->v.ClassDef.name;
1424 Py_INCREF(c->u->u_private);
1425 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426 if (!str || !compiler_nameop(c, str, Load)) {
1427 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001428 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001430 }
1431
1432 Py_DECREF(str);
1433 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434 if (!str || !compiler_nameop(c, str, Store)) {
1435 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001436 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001438 }
1439 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001441 if (!compiler_body(c, s->v.ClassDef.body)) {
1442 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001444 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001446 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1447 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001449 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450 if (co == NULL)
1451 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001453 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001454 Py_DECREF(co);
1455
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456 ADDOP_I(c, CALL_FUNCTION, 0);
1457 ADDOP(c, BUILD_CLASS);
1458 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1459 return 0;
1460 return 1;
1461}
1462
1463static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001464compiler_ifexp(struct compiler *c, expr_ty e)
1465{
1466 basicblock *end, *next;
1467
1468 assert(e->kind == IfExp_kind);
1469 end = compiler_new_block(c);
1470 if (end == NULL)
1471 return 0;
1472 next = compiler_new_block(c);
1473 if (next == NULL)
1474 return 0;
1475 VISIT(c, expr, e->v.IfExp.test);
1476 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1477 ADDOP(c, POP_TOP);
1478 VISIT(c, expr, e->v.IfExp.body);
1479 ADDOP_JREL(c, JUMP_FORWARD, end);
1480 compiler_use_next_block(c, next);
1481 ADDOP(c, POP_TOP);
1482 VISIT(c, expr, e->v.IfExp.orelse);
1483 compiler_use_next_block(c, end);
1484 return 1;
1485}
1486
1487static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488compiler_lambda(struct compiler *c, expr_ty e)
1489{
1490 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001491 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492 arguments_ty args = e->v.Lambda.args;
1493 assert(e->kind == Lambda_kind);
1494
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001495 if (!name) {
1496 name = PyString_InternFromString("<lambda>");
1497 if (!name)
1498 return 0;
1499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500
1501 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001502 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1504 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001505
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001506 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507 compiler_arguments(c, args);
1508
1509 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001510 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1511 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512 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
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001517 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001518 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519
1520 return 1;
1521}
1522
1523static int
1524compiler_print(struct compiler *c, stmt_ty s)
1525{
1526 int i, n;
1527 bool dest;
1528
1529 assert(s->kind == Print_kind);
1530 n = asdl_seq_LEN(s->v.Print.values);
1531 dest = false;
1532 if (s->v.Print.dest) {
1533 VISIT(c, expr, s->v.Print.dest);
1534 dest = true;
1535 }
1536 for (i = 0; i < n; i++) {
1537 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1538 if (dest) {
1539 ADDOP(c, DUP_TOP);
1540 VISIT(c, expr, e);
1541 ADDOP(c, ROT_TWO);
1542 ADDOP(c, PRINT_ITEM_TO);
1543 }
1544 else {
1545 VISIT(c, expr, e);
1546 ADDOP(c, PRINT_ITEM);
1547 }
1548 }
1549 if (s->v.Print.nl) {
1550 if (dest)
1551 ADDOP(c, PRINT_NEWLINE_TO)
1552 else
1553 ADDOP(c, PRINT_NEWLINE)
1554 }
1555 else if (dest)
1556 ADDOP(c, POP_TOP);
1557 return 1;
1558}
1559
1560static int
1561compiler_if(struct compiler *c, stmt_ty s)
1562{
1563 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001564 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565 assert(s->kind == If_kind);
1566 end = compiler_new_block(c);
1567 if (end == NULL)
1568 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001569 next = compiler_new_block(c);
1570 if (next == NULL)
1571 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001572
1573 constant = expr_constant(s->v.If.test);
1574 /* constant = 0: "if 0"
1575 * constant = 1: "if 1", "if 2", ...
1576 * constant = -1: rest */
1577 if (constant == 0) {
1578 if (s->v.If.orelse)
1579 VISIT_SEQ(c, stmt, s->v.If.orelse);
1580 } else if (constant == 1) {
1581 VISIT_SEQ(c, stmt, s->v.If.body);
1582 } else {
1583 VISIT(c, expr, s->v.If.test);
1584 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1585 ADDOP(c, POP_TOP);
1586 VISIT_SEQ(c, stmt, s->v.If.body);
1587 ADDOP_JREL(c, JUMP_FORWARD, end);
1588 compiler_use_next_block(c, next);
1589 ADDOP(c, POP_TOP);
1590 if (s->v.If.orelse)
1591 VISIT_SEQ(c, stmt, s->v.If.orelse);
1592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001593 compiler_use_next_block(c, end);
1594 return 1;
1595}
1596
1597static int
1598compiler_for(struct compiler *c, stmt_ty s)
1599{
1600 basicblock *start, *cleanup, *end;
1601
1602 start = compiler_new_block(c);
1603 cleanup = compiler_new_block(c);
1604 end = compiler_new_block(c);
1605 if (start == NULL || end == NULL || cleanup == NULL)
1606 return 0;
1607 ADDOP_JREL(c, SETUP_LOOP, end);
1608 if (!compiler_push_fblock(c, LOOP, start))
1609 return 0;
1610 VISIT(c, expr, s->v.For.iter);
1611 ADDOP(c, GET_ITER);
1612 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001613 /* XXX(nnorwitz): is there a better way to handle this?
1614 for loops are special, we want to be able to trace them
1615 each time around, so we need to set an extra line number. */
1616 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001617 ADDOP_JREL(c, FOR_ITER, cleanup);
1618 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001619 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001620 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1621 compiler_use_next_block(c, cleanup);
1622 ADDOP(c, POP_BLOCK);
1623 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001624 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001625 compiler_use_next_block(c, end);
1626 return 1;
1627}
1628
1629static int
1630compiler_while(struct compiler *c, stmt_ty s)
1631{
1632 basicblock *loop, *orelse, *end, *anchor = NULL;
1633 int constant = expr_constant(s->v.While.test);
1634
1635 if (constant == 0)
1636 return 1;
1637 loop = compiler_new_block(c);
1638 end = compiler_new_block(c);
1639 if (constant == -1) {
1640 anchor = compiler_new_block(c);
1641 if (anchor == NULL)
1642 return 0;
1643 }
1644 if (loop == NULL || end == NULL)
1645 return 0;
1646 if (s->v.While.orelse) {
1647 orelse = compiler_new_block(c);
1648 if (orelse == NULL)
1649 return 0;
1650 }
1651 else
1652 orelse = NULL;
1653
1654 ADDOP_JREL(c, SETUP_LOOP, end);
1655 compiler_use_next_block(c, loop);
1656 if (!compiler_push_fblock(c, LOOP, loop))
1657 return 0;
1658 if (constant == -1) {
1659 VISIT(c, expr, s->v.While.test);
1660 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1661 ADDOP(c, POP_TOP);
1662 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001663 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001664 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1665
1666 /* XXX should the two POP instructions be in a separate block
1667 if there is no else clause ?
1668 */
1669
1670 if (constant == -1) {
1671 compiler_use_next_block(c, anchor);
1672 ADDOP(c, POP_TOP);
1673 ADDOP(c, POP_BLOCK);
1674 }
1675 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001676 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001677 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678 compiler_use_next_block(c, end);
1679
1680 return 1;
1681}
1682
1683static int
1684compiler_continue(struct compiler *c)
1685{
1686 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001687 static const char IN_FINALLY_ERROR_MSG[] =
1688 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689 int i;
1690
1691 if (!c->u->u_nfblocks)
1692 return compiler_error(c, LOOP_ERROR_MSG);
1693 i = c->u->u_nfblocks - 1;
1694 switch (c->u->u_fblock[i].fb_type) {
1695 case LOOP:
1696 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1697 break;
1698 case EXCEPT:
1699 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001700 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1701 /* Prevent continue anywhere under a finally
1702 even if hidden in a sub-try or except. */
1703 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1704 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1705 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 if (i == -1)
1707 return compiler_error(c, LOOP_ERROR_MSG);
1708 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1709 break;
1710 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001711 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001712 }
1713
1714 return 1;
1715}
1716
1717/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1718
1719 SETUP_FINALLY L
1720 <code for body>
1721 POP_BLOCK
1722 LOAD_CONST <None>
1723 L: <code for finalbody>
1724 END_FINALLY
1725
1726 The special instructions use the block stack. Each block
1727 stack entry contains the instruction that created it (here
1728 SETUP_FINALLY), the level of the value stack at the time the
1729 block stack entry was created, and a label (here L).
1730
1731 SETUP_FINALLY:
1732 Pushes the current value stack level and the label
1733 onto the block stack.
1734 POP_BLOCK:
1735 Pops en entry from the block stack, and pops the value
1736 stack until its level is the same as indicated on the
1737 block stack. (The label is ignored.)
1738 END_FINALLY:
1739 Pops a variable number of entries from the *value* stack
1740 and re-raises the exception they specify. The number of
1741 entries popped depends on the (pseudo) exception type.
1742
1743 The block stack is unwound when an exception is raised:
1744 when a SETUP_FINALLY entry is found, the exception is pushed
1745 onto the value stack (and the exception condition is cleared),
1746 and the interpreter jumps to the label gotten from the block
1747 stack.
1748*/
1749
1750static int
1751compiler_try_finally(struct compiler *c, stmt_ty s)
1752{
1753 basicblock *body, *end;
1754 body = compiler_new_block(c);
1755 end = compiler_new_block(c);
1756 if (body == NULL || end == NULL)
1757 return 0;
1758
1759 ADDOP_JREL(c, SETUP_FINALLY, end);
1760 compiler_use_next_block(c, body);
1761 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1762 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001763 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764 ADDOP(c, POP_BLOCK);
1765 compiler_pop_fblock(c, FINALLY_TRY, body);
1766
1767 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1768 compiler_use_next_block(c, end);
1769 if (!compiler_push_fblock(c, FINALLY_END, end))
1770 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001771 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 ADDOP(c, END_FINALLY);
1773 compiler_pop_fblock(c, FINALLY_END, end);
1774
1775 return 1;
1776}
1777
1778/*
1779 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1780 (The contents of the value stack is shown in [], with the top
1781 at the right; 'tb' is trace-back info, 'val' the exception's
1782 associated value, and 'exc' the exception.)
1783
1784 Value stack Label Instruction Argument
1785 [] SETUP_EXCEPT L1
1786 [] <code for S>
1787 [] POP_BLOCK
1788 [] JUMP_FORWARD L0
1789
1790 [tb, val, exc] L1: DUP )
1791 [tb, val, exc, exc] <evaluate E1> )
1792 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1793 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1794 [tb, val, exc, 1] POP )
1795 [tb, val, exc] POP
1796 [tb, val] <assign to V1> (or POP if no V1)
1797 [tb] POP
1798 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001799 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
1801 [tb, val, exc, 0] L2: POP
1802 [tb, val, exc] DUP
1803 .............................etc.......................
1804
1805 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001806 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807
1808 [] L0: <next statement>
1809
1810 Of course, parts are not generated if Vi or Ei is not present.
1811*/
1812static int
1813compiler_try_except(struct compiler *c, stmt_ty s)
1814{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001815 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816 int i, n;
1817
1818 body = compiler_new_block(c);
1819 except = compiler_new_block(c);
1820 orelse = compiler_new_block(c);
1821 end = compiler_new_block(c);
1822 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1823 return 0;
1824 ADDOP_JREL(c, SETUP_EXCEPT, except);
1825 compiler_use_next_block(c, body);
1826 if (!compiler_push_fblock(c, EXCEPT, body))
1827 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001828 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 ADDOP(c, POP_BLOCK);
1830 compiler_pop_fblock(c, EXCEPT, body);
1831 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1832 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1833 compiler_use_next_block(c, except);
1834 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001835 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 s->v.TryExcept.handlers, i);
1837 if (!handler->type && i < n-1)
1838 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00001839 c->u->u_lineno_set = false;
1840 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001841 except = compiler_new_block(c);
1842 if (except == NULL)
1843 return 0;
1844 if (handler->type) {
1845 ADDOP(c, DUP_TOP);
1846 VISIT(c, expr, handler->type);
1847 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1848 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1849 ADDOP(c, POP_TOP);
1850 }
1851 ADDOP(c, POP_TOP);
1852 if (handler->name) {
1853 VISIT(c, expr, handler->name);
1854 }
1855 else {
1856 ADDOP(c, POP_TOP);
1857 }
1858 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001859 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860 ADDOP_JREL(c, JUMP_FORWARD, end);
1861 compiler_use_next_block(c, except);
1862 if (handler->type)
1863 ADDOP(c, POP_TOP);
1864 }
1865 ADDOP(c, END_FINALLY);
1866 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001867 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868 compiler_use_next_block(c, end);
1869 return 1;
1870}
1871
1872static int
1873compiler_import_as(struct compiler *c, identifier name, identifier asname)
1874{
1875 /* The IMPORT_NAME opcode was already generated. This function
1876 merely needs to bind the result to a name.
1877
1878 If there is a dot in name, we need to split it and emit a
1879 LOAD_ATTR for each name.
1880 */
1881 const char *src = PyString_AS_STRING(name);
1882 const char *dot = strchr(src, '.');
1883 if (dot) {
1884 /* Consume the base module name to get the first attribute */
1885 src = dot + 1;
1886 while (dot) {
1887 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001888 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001890 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001892 if (!attr)
1893 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001895 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896 src = dot + 1;
1897 }
1898 }
1899 return compiler_nameop(c, asname, Store);
1900}
1901
1902static int
1903compiler_import(struct compiler *c, stmt_ty s)
1904{
1905 /* The Import node stores a module name like a.b.c as a single
1906 string. This is convenient for all cases except
1907 import a.b.c as d
1908 where we need to parse that string to extract the individual
1909 module names.
1910 XXX Perhaps change the representation to make this case simpler?
1911 */
1912 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001913
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001915 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001917 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918
Neal Norwitzcbce2802006-04-03 06:26:32 +00001919 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001920 level = PyInt_FromLong(0);
1921 else
1922 level = PyInt_FromLong(-1);
1923
1924 if (level == NULL)
1925 return 0;
1926
1927 ADDOP_O(c, LOAD_CONST, level, consts);
1928 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1930 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1931
1932 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001933 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001934 if (!r)
1935 return r;
1936 }
1937 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 identifier tmp = alias->name;
1939 const char *base = PyString_AS_STRING(alias->name);
1940 char *dot = strchr(base, '.');
1941 if (dot)
1942 tmp = PyString_FromStringAndSize(base,
1943 dot - base);
1944 r = compiler_nameop(c, tmp, Store);
1945 if (dot) {
1946 Py_DECREF(tmp);
1947 }
1948 if (!r)
1949 return r;
1950 }
1951 }
1952 return 1;
1953}
1954
1955static int
1956compiler_from_import(struct compiler *c, stmt_ty s)
1957{
1958 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959
1960 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001961 PyObject *level;
1962
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963 if (!names)
1964 return 0;
1965
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001966 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001967 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001968 level = PyInt_FromLong(-1);
1969 else
1970 level = PyInt_FromLong(s->v.ImportFrom.level);
1971
1972 if (!level) {
1973 Py_DECREF(names);
1974 return 0;
1975 }
1976
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001977 /* build up the names */
1978 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001979 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 Py_INCREF(alias->name);
1981 PyTuple_SET_ITEM(names, i, alias->name);
1982 }
1983
1984 if (s->lineno > c->c_future->ff_lineno) {
1985 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1986 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001987 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988 Py_DECREF(names);
1989 return compiler_error(c,
1990 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001991 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992
1993 }
1994 }
1995
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001996 ADDOP_O(c, LOAD_CONST, level, consts);
1997 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001999 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2001 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002002 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002003 identifier store_name;
2004
2005 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2006 assert(n == 1);
2007 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002008 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009 }
2010
2011 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2012 store_name = alias->name;
2013 if (alias->asname)
2014 store_name = alias->asname;
2015
2016 if (!compiler_nameop(c, store_name, Store)) {
2017 Py_DECREF(names);
2018 return 0;
2019 }
2020 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002021 /* remove imported module */
2022 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 return 1;
2024}
2025
2026static int
2027compiler_assert(struct compiler *c, stmt_ty s)
2028{
2029 static PyObject *assertion_error = NULL;
2030 basicblock *end;
2031
2032 if (Py_OptimizeFlag)
2033 return 1;
2034 if (assertion_error == NULL) {
2035 assertion_error = PyString_FromString("AssertionError");
2036 if (assertion_error == NULL)
2037 return 0;
2038 }
2039 VISIT(c, expr, s->v.Assert.test);
2040 end = compiler_new_block(c);
2041 if (end == NULL)
2042 return 0;
2043 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2044 ADDOP(c, POP_TOP);
2045 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2046 if (s->v.Assert.msg) {
2047 VISIT(c, expr, s->v.Assert.msg);
2048 ADDOP_I(c, RAISE_VARARGS, 2);
2049 }
2050 else {
2051 ADDOP_I(c, RAISE_VARARGS, 1);
2052 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002053 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 ADDOP(c, POP_TOP);
2055 return 1;
2056}
2057
2058static int
2059compiler_visit_stmt(struct compiler *c, stmt_ty s)
2060{
2061 int i, n;
2062
Jeremy Hylton12603c42006-04-01 16:18:02 +00002063 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064 c->u->u_lineno = s->lineno;
2065 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002066
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002068 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002070 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002072 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 if (c->u->u_ste->ste_type != FunctionBlock)
2074 return compiler_error(c, "'return' outside function");
2075 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 VISIT(c, expr, s->v.Return.value);
2077 }
2078 else
2079 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2080 ADDOP(c, RETURN_VALUE);
2081 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002082 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002083 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002085 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 n = asdl_seq_LEN(s->v.Assign.targets);
2087 VISIT(c, expr, s->v.Assign.value);
2088 for (i = 0; i < n; i++) {
2089 if (i < n - 1)
2090 ADDOP(c, DUP_TOP);
2091 VISIT(c, expr,
2092 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2093 }
2094 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002101 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 n = 0;
2107 if (s->v.Raise.type) {
2108 VISIT(c, expr, s->v.Raise.type);
2109 n++;
2110 if (s->v.Raise.inst) {
2111 VISIT(c, expr, s->v.Raise.inst);
2112 n++;
2113 if (s->v.Raise.tback) {
2114 VISIT(c, expr, s->v.Raise.tback);
2115 n++;
2116 }
2117 }
2118 }
2119 ADDOP_I(c, RAISE_VARARGS, n);
2120 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002121 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002123 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002125 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002131 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 VISIT(c, expr, s->v.Exec.body);
2133 if (s->v.Exec.globals) {
2134 VISIT(c, expr, s->v.Exec.globals);
2135 if (s->v.Exec.locals) {
2136 VISIT(c, expr, s->v.Exec.locals);
2137 } else {
2138 ADDOP(c, DUP_TOP);
2139 }
2140 } else {
2141 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2142 ADDOP(c, DUP_TOP);
2143 }
2144 ADDOP(c, EXEC_STMT);
2145 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002146 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002147 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002148 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002150 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151 ADDOP(c, PRINT_EXPR);
2152 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002153 else if (s->v.Expr.value->kind != Str_kind &&
2154 s->v.Expr.value->kind != Num_kind) {
2155 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002156 ADDOP(c, POP_TOP);
2157 }
2158 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002159 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002161 case Break_kind:
Jeremy Hylton82271f12006-10-04 02:24:52 +00002162 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 return compiler_error(c, "'break' outside loop");
2164 ADDOP(c, BREAK_LOOP);
2165 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002166 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002168 case With_kind:
2169 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 }
2171 return 1;
2172}
2173
2174static int
2175unaryop(unaryop_ty op)
2176{
2177 switch (op) {
2178 case Invert:
2179 return UNARY_INVERT;
2180 case Not:
2181 return UNARY_NOT;
2182 case UAdd:
2183 return UNARY_POSITIVE;
2184 case USub:
2185 return UNARY_NEGATIVE;
2186 }
2187 return 0;
2188}
2189
2190static int
2191binop(struct compiler *c, operator_ty op)
2192{
2193 switch (op) {
2194 case Add:
2195 return BINARY_ADD;
2196 case Sub:
2197 return BINARY_SUBTRACT;
2198 case Mult:
2199 return BINARY_MULTIPLY;
2200 case Div:
2201 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2202 return BINARY_TRUE_DIVIDE;
2203 else
2204 return BINARY_DIVIDE;
2205 case Mod:
2206 return BINARY_MODULO;
2207 case Pow:
2208 return BINARY_POWER;
2209 case LShift:
2210 return BINARY_LSHIFT;
2211 case RShift:
2212 return BINARY_RSHIFT;
2213 case BitOr:
2214 return BINARY_OR;
2215 case BitXor:
2216 return BINARY_XOR;
2217 case BitAnd:
2218 return BINARY_AND;
2219 case FloorDiv:
2220 return BINARY_FLOOR_DIVIDE;
2221 }
2222 return 0;
2223}
2224
2225static int
2226cmpop(cmpop_ty op)
2227{
2228 switch (op) {
2229 case Eq:
2230 return PyCmp_EQ;
2231 case NotEq:
2232 return PyCmp_NE;
2233 case Lt:
2234 return PyCmp_LT;
2235 case LtE:
2236 return PyCmp_LE;
2237 case Gt:
2238 return PyCmp_GT;
2239 case GtE:
2240 return PyCmp_GE;
2241 case Is:
2242 return PyCmp_IS;
2243 case IsNot:
2244 return PyCmp_IS_NOT;
2245 case In:
2246 return PyCmp_IN;
2247 case NotIn:
2248 return PyCmp_NOT_IN;
2249 }
2250 return PyCmp_BAD;
2251}
2252
2253static int
2254inplace_binop(struct compiler *c, operator_ty op)
2255{
2256 switch (op) {
2257 case Add:
2258 return INPLACE_ADD;
2259 case Sub:
2260 return INPLACE_SUBTRACT;
2261 case Mult:
2262 return INPLACE_MULTIPLY;
2263 case Div:
2264 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2265 return INPLACE_TRUE_DIVIDE;
2266 else
2267 return INPLACE_DIVIDE;
2268 case Mod:
2269 return INPLACE_MODULO;
2270 case Pow:
2271 return INPLACE_POWER;
2272 case LShift:
2273 return INPLACE_LSHIFT;
2274 case RShift:
2275 return INPLACE_RSHIFT;
2276 case BitOr:
2277 return INPLACE_OR;
2278 case BitXor:
2279 return INPLACE_XOR;
2280 case BitAnd:
2281 return INPLACE_AND;
2282 case FloorDiv:
2283 return INPLACE_FLOOR_DIVIDE;
2284 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002285 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002286 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 return 0;
2288}
2289
2290static int
2291compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2292{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002293 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2295
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002296 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002297 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 /* XXX AugStore isn't used anywhere! */
2299
2300 /* First check for assignment to __debug__. Param? */
2301 if ((ctx == Store || ctx == AugStore || ctx == Del)
2302 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2303 return compiler_error(c, "can not assign to __debug__");
2304 }
2305
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002306 mangled = _Py_Mangle(c->u->u_private, name);
2307 if (!mangled)
2308 return 0;
2309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 op = 0;
2311 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002312 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 switch (scope) {
2314 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002315 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 optype = OP_DEREF;
2317 break;
2318 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 optype = OP_DEREF;
2321 break;
2322 case LOCAL:
2323 if (c->u->u_ste->ste_type == FunctionBlock)
2324 optype = OP_FAST;
2325 break;
2326 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002327 if (c->u->u_ste->ste_type == FunctionBlock &&
2328 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 optype = OP_GLOBAL;
2330 break;
2331 case GLOBAL_EXPLICIT:
2332 optype = OP_GLOBAL;
2333 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002334 default:
2335 /* scope can be 0 */
2336 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 }
2338
2339 /* XXX Leave assert here, but handle __doc__ and the like better */
2340 assert(scope || PyString_AS_STRING(name)[0] == '_');
2341
2342 switch (optype) {
2343 case OP_DEREF:
2344 switch (ctx) {
2345 case Load: op = LOAD_DEREF; break;
2346 case Store: op = STORE_DEREF; break;
2347 case AugLoad:
2348 case AugStore:
2349 break;
2350 case Del:
2351 PyErr_Format(PyExc_SyntaxError,
2352 "can not delete variable '%s' referenced "
2353 "in nested scope",
2354 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002355 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002358 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002359 PyErr_SetString(PyExc_SystemError,
2360 "param invalid for deref variable");
2361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362 }
2363 break;
2364 case OP_FAST:
2365 switch (ctx) {
2366 case Load: op = LOAD_FAST; break;
2367 case Store: op = STORE_FAST; break;
2368 case Del: op = DELETE_FAST; break;
2369 case AugLoad:
2370 case AugStore:
2371 break;
2372 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002373 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002374 PyErr_SetString(PyExc_SystemError,
2375 "param invalid for local variable");
2376 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002378 ADDOP_O(c, op, mangled, varnames);
2379 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380 return 1;
2381 case OP_GLOBAL:
2382 switch (ctx) {
2383 case Load: op = LOAD_GLOBAL; break;
2384 case Store: op = STORE_GLOBAL; break;
2385 case Del: op = DELETE_GLOBAL; break;
2386 case AugLoad:
2387 case AugStore:
2388 break;
2389 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002390 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002391 PyErr_SetString(PyExc_SystemError,
2392 "param invalid for global variable");
2393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394 }
2395 break;
2396 case OP_NAME:
2397 switch (ctx) {
2398 case Load: op = LOAD_NAME; break;
2399 case Store: op = STORE_NAME; break;
2400 case Del: op = DELETE_NAME; break;
2401 case AugLoad:
2402 case AugStore:
2403 break;
2404 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002405 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002406 PyErr_SetString(PyExc_SystemError,
2407 "param invalid for name variable");
2408 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409 }
2410 break;
2411 }
2412
2413 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002414 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002415 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002416 if (arg < 0)
2417 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002418 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419}
2420
2421static int
2422compiler_boolop(struct compiler *c, expr_ty e)
2423{
2424 basicblock *end;
2425 int jumpi, i, n;
2426 asdl_seq *s;
2427
2428 assert(e->kind == BoolOp_kind);
2429 if (e->v.BoolOp.op == And)
2430 jumpi = JUMP_IF_FALSE;
2431 else
2432 jumpi = JUMP_IF_TRUE;
2433 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002434 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002435 return 0;
2436 s = e->v.BoolOp.values;
2437 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002438 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002440 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441 ADDOP_JREL(c, jumpi, end);
2442 ADDOP(c, POP_TOP)
2443 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002444 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002445 compiler_use_next_block(c, end);
2446 return 1;
2447}
2448
2449static int
2450compiler_list(struct compiler *c, expr_ty e)
2451{
2452 int n = asdl_seq_LEN(e->v.List.elts);
2453 if (e->v.List.ctx == Store) {
2454 ADDOP_I(c, UNPACK_SEQUENCE, n);
2455 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002456 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002457 if (e->v.List.ctx == Load) {
2458 ADDOP_I(c, BUILD_LIST, n);
2459 }
2460 return 1;
2461}
2462
2463static int
2464compiler_tuple(struct compiler *c, expr_ty e)
2465{
2466 int n = asdl_seq_LEN(e->v.Tuple.elts);
2467 if (e->v.Tuple.ctx == Store) {
2468 ADDOP_I(c, UNPACK_SEQUENCE, n);
2469 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002470 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 if (e->v.Tuple.ctx == Load) {
2472 ADDOP_I(c, BUILD_TUPLE, n);
2473 }
2474 return 1;
2475}
2476
2477static int
2478compiler_compare(struct compiler *c, expr_ty e)
2479{
2480 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002481 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482
2483 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2484 VISIT(c, expr, e->v.Compare.left);
2485 n = asdl_seq_LEN(e->v.Compare.ops);
2486 assert(n > 0);
2487 if (n > 1) {
2488 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002489 if (cleanup == NULL)
2490 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002491 VISIT(c, expr,
2492 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493 }
2494 for (i = 1; i < n; i++) {
2495 ADDOP(c, DUP_TOP);
2496 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002498 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00002499 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2501 NEXT_BLOCK(c);
2502 ADDOP(c, POP_TOP);
2503 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002504 VISIT(c, expr,
2505 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002507 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002509 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510 if (n > 1) {
2511 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002512 if (end == NULL)
2513 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514 ADDOP_JREL(c, JUMP_FORWARD, end);
2515 compiler_use_next_block(c, cleanup);
2516 ADDOP(c, ROT_TWO);
2517 ADDOP(c, POP_TOP);
2518 compiler_use_next_block(c, end);
2519 }
2520 return 1;
2521}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00002522#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
2524static int
2525compiler_call(struct compiler *c, expr_ty e)
2526{
2527 int n, code = 0;
2528
2529 VISIT(c, expr, e->v.Call.func);
2530 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002531 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002533 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2535 }
2536 if (e->v.Call.starargs) {
2537 VISIT(c, expr, e->v.Call.starargs);
2538 code |= 1;
2539 }
2540 if (e->v.Call.kwargs) {
2541 VISIT(c, expr, e->v.Call.kwargs);
2542 code |= 2;
2543 }
2544 switch (code) {
2545 case 0:
2546 ADDOP_I(c, CALL_FUNCTION, n);
2547 break;
2548 case 1:
2549 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2550 break;
2551 case 2:
2552 ADDOP_I(c, CALL_FUNCTION_KW, n);
2553 break;
2554 case 3:
2555 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2556 break;
2557 }
2558 return 1;
2559}
2560
2561static int
2562compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002563 asdl_seq *generators, int gen_index,
2564 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565{
2566 /* generate code for the iterator, then each of the ifs,
2567 and then write to the element */
2568
2569 comprehension_ty l;
2570 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002571 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572
2573 start = compiler_new_block(c);
2574 skip = compiler_new_block(c);
2575 if_cleanup = compiler_new_block(c);
2576 anchor = compiler_new_block(c);
2577
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002578 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2579 anchor == NULL)
2580 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581
Anthony Baxter7b782b62006-04-11 12:01:56 +00002582 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583 VISIT(c, expr, l->iter);
2584 ADDOP(c, GET_ITER);
2585 compiler_use_next_block(c, start);
2586 ADDOP_JREL(c, FOR_ITER, anchor);
2587 NEXT_BLOCK(c);
2588 VISIT(c, expr, l->target);
2589
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002590 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591 n = asdl_seq_LEN(l->ifs);
2592 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002593 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594 VISIT(c, expr, e);
2595 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2596 NEXT_BLOCK(c);
2597 ADDOP(c, POP_TOP);
2598 }
2599
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002600 if (++gen_index < asdl_seq_LEN(generators))
2601 if (!compiler_listcomp_generator(c, tmpname,
2602 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002605 /* only append after the last for generator */
2606 if (gen_index >= asdl_seq_LEN(generators)) {
2607 if (!compiler_nameop(c, tmpname, Load))
2608 return 0;
2609 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002610 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002611
2612 compiler_use_next_block(c, skip);
2613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 for (i = 0; i < n; i++) {
2615 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002616 if (i == 0)
2617 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 ADDOP(c, POP_TOP);
2619 }
2620 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2621 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002622 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002624 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 return 0;
2626
2627 return 1;
2628}
2629
2630static int
2631compiler_listcomp(struct compiler *c, expr_ty e)
2632{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 static identifier append;
2636 asdl_seq *generators = e->v.ListComp.generators;
2637
2638 assert(e->kind == ListComp_kind);
2639 if (!append) {
2640 append = PyString_InternFromString("append");
2641 if (!append)
2642 return 0;
2643 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002644 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 if (!tmp)
2646 return 0;
2647 ADDOP_I(c, BUILD_LIST, 0);
2648 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002650 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2651 e->v.ListComp.elt);
2652 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 return rc;
2654}
2655
2656static int
2657compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002658 asdl_seq *generators, int gen_index,
2659 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660{
2661 /* generate code for the iterator, then each of the ifs,
2662 and then write to the element */
2663
2664 comprehension_ty ge;
2665 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002666 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667
2668 start = compiler_new_block(c);
2669 skip = compiler_new_block(c);
2670 if_cleanup = compiler_new_block(c);
2671 anchor = compiler_new_block(c);
2672 end = compiler_new_block(c);
2673
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002674 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 anchor == NULL || end == NULL)
2676 return 0;
2677
Anthony Baxter7b782b62006-04-11 12:01:56 +00002678 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 ADDOP_JREL(c, SETUP_LOOP, end);
2680 if (!compiler_push_fblock(c, LOOP, start))
2681 return 0;
2682
2683 if (gen_index == 0) {
2684 /* Receive outermost iter as an implicit argument */
2685 c->u->u_argcount = 1;
2686 ADDOP_I(c, LOAD_FAST, 0);
2687 }
2688 else {
2689 /* Sub-iter - calculate on the fly */
2690 VISIT(c, expr, ge->iter);
2691 ADDOP(c, GET_ITER);
2692 }
2693 compiler_use_next_block(c, start);
2694 ADDOP_JREL(c, FOR_ITER, anchor);
2695 NEXT_BLOCK(c);
2696 VISIT(c, expr, ge->target);
2697
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002698 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 n = asdl_seq_LEN(ge->ifs);
2700 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002701 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 VISIT(c, expr, e);
2703 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2704 NEXT_BLOCK(c);
2705 ADDOP(c, POP_TOP);
2706 }
2707
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2710 return 0;
2711
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 /* only append after the last 'for' generator */
2713 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 VISIT(c, expr, elt);
2715 ADDOP(c, YIELD_VALUE);
2716 ADDOP(c, POP_TOP);
2717
2718 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 for (i = 0; i < n; i++) {
2721 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002722 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 compiler_use_next_block(c, if_cleanup);
2724
2725 ADDOP(c, POP_TOP);
2726 }
2727 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2728 compiler_use_next_block(c, anchor);
2729 ADDOP(c, POP_BLOCK);
2730 compiler_pop_fblock(c, LOOP, start);
2731 compiler_use_next_block(c, end);
2732
2733 return 1;
2734}
2735
2736static int
2737compiler_genexp(struct compiler *c, expr_ty e)
2738{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002739 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740 PyCodeObject *co;
2741 expr_ty outermost_iter = ((comprehension_ty)
2742 (asdl_seq_GET(e->v.GeneratorExp.generators,
2743 0)))->iter;
2744
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002745 if (!name) {
2746 name = PyString_FromString("<genexpr>");
2747 if (!name)
2748 return 0;
2749 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750
2751 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2752 return 0;
2753 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2754 e->v.GeneratorExp.elt);
2755 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002756 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 if (co == NULL)
2758 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002760 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002761 Py_DECREF(co);
2762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763 VISIT(c, expr, outermost_iter);
2764 ADDOP(c, GET_ITER);
2765 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766
2767 return 1;
2768}
2769
2770static int
2771compiler_visit_keyword(struct compiler *c, keyword_ty k)
2772{
2773 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2774 VISIT(c, expr, k->value);
2775 return 1;
2776}
2777
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002778/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779 whether they are true or false.
2780
2781 Return values: 1 for true, 0 for false, -1 for non-constant.
2782 */
2783
2784static int
2785expr_constant(expr_ty e)
2786{
2787 switch (e->kind) {
2788 case Num_kind:
2789 return PyObject_IsTrue(e->v.Num.n);
2790 case Str_kind:
2791 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002792 case Name_kind:
2793 /* __debug__ is not assignable, so we can optimize
2794 * it away in if and while statements */
2795 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2796 "__debug__") == 0)
2797 return ! Py_OptimizeFlag;
2798 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799 default:
2800 return -1;
2801 }
2802}
2803
Guido van Rossumc2e20742006-02-27 22:32:47 +00002804/*
2805 Implements the with statement from PEP 343.
2806
2807 The semantics outlined in that PEP are as follows:
2808
2809 with EXPR as VAR:
2810 BLOCK
2811
2812 It is implemented roughly as:
2813
Guido van Rossumda5b7012006-05-02 19:47:52 +00002814 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002815 exit = context.__exit__ # not calling it
2816 value = context.__enter__()
2817 try:
2818 VAR = value # if VAR present in the syntax
2819 BLOCK
2820 finally:
2821 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002822 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002823 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002824 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002825 exit(*exc)
2826 */
2827static int
2828compiler_with(struct compiler *c, stmt_ty s)
2829{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002830 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002831 basicblock *block, *finally;
2832 identifier tmpexit, tmpvalue = NULL;
2833
2834 assert(s->kind == With_kind);
2835
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002837 enter_attr = PyString_InternFromString("__enter__");
2838 if (!enter_attr)
2839 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002840 }
2841 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 exit_attr = PyString_InternFromString("__exit__");
2843 if (!exit_attr)
2844 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002845 }
2846
2847 block = compiler_new_block(c);
2848 finally = compiler_new_block(c);
2849 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002850 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851
2852 /* Create a temporary variable to hold context.__exit__ */
2853 tmpexit = compiler_new_tmpname(c);
2854 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002855 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002856 PyArena_AddPyObject(c->c_arena, tmpexit);
2857
2858 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002859 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002860 We need to do this rather than preserving it on the stack
2861 because SETUP_FINALLY remembers the stack level.
2862 We need to do the assignment *inside* the try/finally
2863 so that context.__exit__() is called when the assignment
2864 fails. But we need to call context.__enter__() *before*
2865 the try/finally so that if it fails we won't call
2866 context.__exit__().
2867 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002868 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869 if (tmpvalue == NULL)
2870 return 0;
2871 PyArena_AddPyObject(c->c_arena, tmpvalue);
2872 }
2873
Guido van Rossumda5b7012006-05-02 19:47:52 +00002874 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002875 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002876
2877 /* Squirrel away context.__exit__ */
2878 ADDOP(c, DUP_TOP);
2879 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2880 if (!compiler_nameop(c, tmpexit, Store))
2881 return 0;
2882
2883 /* Call context.__enter__() */
2884 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2885 ADDOP_I(c, CALL_FUNCTION, 0);
2886
2887 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002888 /* Store it in tmpvalue */
2889 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002890 return 0;
2891 }
2892 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002893 /* Discard result from context.__enter__() */
2894 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002895 }
2896
2897 /* Start the try block */
2898 ADDOP_JREL(c, SETUP_FINALLY, finally);
2899
2900 compiler_use_next_block(c, block);
2901 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002902 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002903 }
2904
2905 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002906 /* Bind saved result of context.__enter__() to VAR */
2907 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908 !compiler_nameop(c, tmpvalue, Del))
2909 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002910 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002911 }
2912
2913 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002914 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002915
2916 /* End of try block; start the finally block */
2917 ADDOP(c, POP_BLOCK);
2918 compiler_pop_fblock(c, FINALLY_TRY, block);
2919
2920 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2921 compiler_use_next_block(c, finally);
2922 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002923 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002924
2925 /* Finally block starts; push tmpexit and issue our magic opcode. */
2926 if (!compiler_nameop(c, tmpexit, Load) ||
2927 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002928 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002929 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002930
2931 /* Finally block ends. */
2932 ADDOP(c, END_FINALLY);
2933 compiler_pop_fblock(c, FINALLY_END, finally);
2934 return 1;
2935}
2936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937static int
2938compiler_visit_expr(struct compiler *c, expr_ty e)
2939{
2940 int i, n;
2941
Jeremy Hylton12603c42006-04-01 16:18:02 +00002942 /* If expr e has a different line number than the last expr/stmt,
2943 set a new line number for the next instruction.
2944 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 if (e->lineno > c->u->u_lineno) {
2946 c->u->u_lineno = e->lineno;
2947 c->u->u_lineno_set = false;
2948 }
2949 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002950 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002952 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953 VISIT(c, expr, e->v.BinOp.left);
2954 VISIT(c, expr, e->v.BinOp.right);
2955 ADDOP(c, binop(c, e->v.BinOp.op));
2956 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002957 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 VISIT(c, expr, e->v.UnaryOp.operand);
2959 ADDOP(c, unaryop(e->v.UnaryOp.op));
2960 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002961 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002963 case IfExp_kind:
2964 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002965 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966 /* XXX get rid of arg? */
2967 ADDOP_I(c, BUILD_MAP, 0);
2968 n = asdl_seq_LEN(e->v.Dict.values);
2969 /* We must arrange things just right for STORE_SUBSCR.
2970 It wants the stack to look like (value) (dict) (key) */
2971 for (i = 0; i < n; i++) {
2972 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002973 VISIT(c, expr,
2974 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002976 VISIT(c, expr,
2977 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978 ADDOP(c, STORE_SUBSCR);
2979 }
2980 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002983 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 return compiler_genexp(c, e);
2985 case Yield_kind:
2986 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002987 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002988 /*
2989 for (i = 0; i < c->u->u_nfblocks; i++) {
2990 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2991 return compiler_error(
2992 c, "'yield' not allowed in a 'try' "
2993 "block with a 'finally' clause");
2994 }
2995 */
2996 if (e->v.Yield.value) {
2997 VISIT(c, expr, e->v.Yield.value);
2998 }
2999 else {
3000 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3001 }
3002 ADDOP(c, YIELD_VALUE);
3003 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003004 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003006 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003008 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009 VISIT(c, expr, e->v.Repr.value);
3010 ADDOP(c, UNARY_CONVERT);
3011 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003012 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3014 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003015 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3017 break;
3018 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003019 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003020 if (e->v.Attribute.ctx != AugStore)
3021 VISIT(c, expr, e->v.Attribute.value);
3022 switch (e->v.Attribute.ctx) {
3023 case AugLoad:
3024 ADDOP(c, DUP_TOP);
3025 /* Fall through to load */
3026 case Load:
3027 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3028 break;
3029 case AugStore:
3030 ADDOP(c, ROT_TWO);
3031 /* Fall through to save */
3032 case Store:
3033 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3034 break;
3035 case Del:
3036 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3037 break;
3038 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003039 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003040 PyErr_SetString(PyExc_SystemError,
3041 "param invalid in attribute expression");
3042 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043 }
3044 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003045 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046 switch (e->v.Subscript.ctx) {
3047 case AugLoad:
3048 VISIT(c, expr, e->v.Subscript.value);
3049 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3050 break;
3051 case Load:
3052 VISIT(c, expr, e->v.Subscript.value);
3053 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3054 break;
3055 case AugStore:
3056 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3057 break;
3058 case Store:
3059 VISIT(c, expr, e->v.Subscript.value);
3060 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3061 break;
3062 case Del:
3063 VISIT(c, expr, e->v.Subscript.value);
3064 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3065 break;
3066 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003067 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003068 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003069 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003070 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 }
3072 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003073 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3075 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003076 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003078 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003079 return compiler_tuple(c, e);
3080 }
3081 return 1;
3082}
3083
3084static int
3085compiler_augassign(struct compiler *c, stmt_ty s)
3086{
3087 expr_ty e = s->v.AugAssign.target;
3088 expr_ty auge;
3089
3090 assert(s->kind == AugAssign_kind);
3091
3092 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003093 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003095 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003096 if (auge == NULL)
3097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003098 VISIT(c, expr, auge);
3099 VISIT(c, expr, s->v.AugAssign.value);
3100 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3101 auge->v.Attribute.ctx = AugStore;
3102 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103 break;
3104 case Subscript_kind:
3105 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003106 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003107 if (auge == NULL)
3108 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003109 VISIT(c, expr, auge);
3110 VISIT(c, expr, s->v.AugAssign.value);
3111 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003112 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003113 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003114 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003116 if (!compiler_nameop(c, e->v.Name.id, Load))
3117 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118 VISIT(c, expr, s->v.AugAssign.value);
3119 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3120 return compiler_nameop(c, e->v.Name.id, Store);
3121 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003122 PyErr_Format(PyExc_SystemError,
3123 "invalid node type (%d) for augmented assignment",
3124 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003125 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126 }
3127 return 1;
3128}
3129
3130static int
3131compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3132{
3133 struct fblockinfo *f;
3134 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3135 return 0;
3136 f = &c->u->u_fblock[c->u->u_nfblocks++];
3137 f->fb_type = t;
3138 f->fb_block = b;
3139 return 1;
3140}
3141
3142static void
3143compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3144{
3145 struct compiler_unit *u = c->u;
3146 assert(u->u_nfblocks > 0);
3147 u->u_nfblocks--;
3148 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3149 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3150}
3151
Jeremy Hylton82271f12006-10-04 02:24:52 +00003152static int
3153compiler_in_loop(struct compiler *c) {
3154 int i;
3155 struct compiler_unit *u = c->u;
3156 for (i = 0; i < u->u_nfblocks; ++i) {
3157 if (u->u_fblock[i].fb_type == LOOP)
3158 return 1;
3159 }
3160 return 0;
3161}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162/* Raises a SyntaxError and returns 0.
3163 If something goes wrong, a different exception may be raised.
3164*/
3165
3166static int
3167compiler_error(struct compiler *c, const char *errstr)
3168{
3169 PyObject *loc;
3170 PyObject *u = NULL, *v = NULL;
3171
3172 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3173 if (!loc) {
3174 Py_INCREF(Py_None);
3175 loc = Py_None;
3176 }
3177 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3178 Py_None, loc);
3179 if (!u)
3180 goto exit;
3181 v = Py_BuildValue("(zO)", errstr, u);
3182 if (!v)
3183 goto exit;
3184 PyErr_SetObject(PyExc_SyntaxError, v);
3185 exit:
3186 Py_DECREF(loc);
3187 Py_XDECREF(u);
3188 Py_XDECREF(v);
3189 return 0;
3190}
3191
3192static int
3193compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003194 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 /* XXX this code is duplicated */
3199 switch (ctx) {
3200 case AugLoad: /* fall through to Load */
3201 case Load: op = BINARY_SUBSCR; break;
3202 case AugStore:/* fall through to Store */
3203 case Store: op = STORE_SUBSCR; break;
3204 case Del: op = DELETE_SUBSCR; break;
3205 case Param:
3206 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003207 "invalid %s kind %d in subscript\n",
3208 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 return 0;
3210 }
3211 if (ctx == AugLoad) {
3212 ADDOP_I(c, DUP_TOPX, 2);
3213 }
3214 else if (ctx == AugStore) {
3215 ADDOP(c, ROT_THREE);
3216 }
3217 ADDOP(c, op);
3218 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219}
3220
3221static int
3222compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3223{
3224 int n = 2;
3225 assert(s->kind == Slice_kind);
3226
3227 /* only handles the cases where BUILD_SLICE is emitted */
3228 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003229 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 }
3231 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003232 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003233 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003234
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003236 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237 }
3238 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003239 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240 }
3241
3242 if (s->v.Slice.step) {
3243 n++;
3244 VISIT(c, expr, s->v.Slice.step);
3245 }
3246 ADDOP_I(c, BUILD_SLICE, n);
3247 return 1;
3248}
3249
3250static int
3251compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3252{
3253 int op = 0, slice_offset = 0, stack_count = 0;
3254
3255 assert(s->v.Slice.step == NULL);
3256 if (s->v.Slice.lower) {
3257 slice_offset++;
3258 stack_count++;
3259 if (ctx != AugStore)
3260 VISIT(c, expr, s->v.Slice.lower);
3261 }
3262 if (s->v.Slice.upper) {
3263 slice_offset += 2;
3264 stack_count++;
3265 if (ctx != AugStore)
3266 VISIT(c, expr, s->v.Slice.upper);
3267 }
3268
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003269 if (ctx == AugLoad) {
3270 switch (stack_count) {
3271 case 0: ADDOP(c, DUP_TOP); break;
3272 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3273 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3274 }
3275 }
3276 else if (ctx == AugStore) {
3277 switch (stack_count) {
3278 case 0: ADDOP(c, ROT_TWO); break;
3279 case 1: ADDOP(c, ROT_THREE); break;
3280 case 2: ADDOP(c, ROT_FOUR); break;
3281 }
3282 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283
3284 switch (ctx) {
3285 case AugLoad: /* fall through to Load */
3286 case Load: op = SLICE; break;
3287 case AugStore:/* fall through to Store */
3288 case Store: op = STORE_SLICE; break;
3289 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003290 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003291 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003292 PyErr_SetString(PyExc_SystemError,
3293 "param invalid in simple slice");
3294 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295 }
3296
3297 ADDOP(c, op + slice_offset);
3298 return 1;
3299}
3300
3301static int
3302compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3303 expr_context_ty ctx)
3304{
3305 switch (s->kind) {
3306 case Ellipsis_kind:
3307 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3308 break;
3309 case Slice_kind:
3310 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311 case Index_kind:
3312 VISIT(c, expr, s->v.Index.value);
3313 break;
3314 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003315 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003316 PyErr_SetString(PyExc_SystemError,
3317 "extended slice invalid in nested slice");
3318 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319 }
3320 return 1;
3321}
3322
3323
3324static int
3325compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3326{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003327 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003329 case Index_kind:
3330 kindname = "index";
3331 if (ctx != AugStore) {
3332 VISIT(c, expr, s->v.Index.value);
3333 }
3334 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003336 kindname = "ellipsis";
3337 if (ctx != AugStore) {
3338 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340 break;
3341 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003342 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343 if (!s->v.Slice.step)
3344 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003345 if (ctx != AugStore) {
3346 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347 return 0;
3348 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003349 break;
3350 case ExtSlice_kind:
3351 kindname = "extended slice";
3352 if (ctx != AugStore) {
3353 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3354 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003355 slice_ty sub = (slice_ty)asdl_seq_GET(
3356 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003357 if (!compiler_visit_nested_slice(c, sub, ctx))
3358 return 0;
3359 }
3360 ADDOP_I(c, BUILD_TUPLE, n);
3361 }
3362 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003363 default:
3364 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003365 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003367 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003368 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369}
3370
3371/* do depth-first search of basic block graph, starting with block.
3372 post records the block indices in post-order.
3373
3374 XXX must handle implicit jumps from one block to next
3375*/
3376
3377static void
3378dfs(struct compiler *c, basicblock *b, struct assembler *a)
3379{
3380 int i;
3381 struct instr *instr = NULL;
3382
3383 if (b->b_seen)
3384 return;
3385 b->b_seen = 1;
3386 if (b->b_next != NULL)
3387 dfs(c, b->b_next, a);
3388 for (i = 0; i < b->b_iused; i++) {
3389 instr = &b->b_instr[i];
3390 if (instr->i_jrel || instr->i_jabs)
3391 dfs(c, instr->i_target, a);
3392 }
3393 a->a_postorder[a->a_nblocks++] = b;
3394}
3395
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003396static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3398{
3399 int i;
3400 struct instr *instr;
3401 if (b->b_seen || b->b_startdepth >= depth)
3402 return maxdepth;
3403 b->b_seen = 1;
3404 b->b_startdepth = depth;
3405 for (i = 0; i < b->b_iused; i++) {
3406 instr = &b->b_instr[i];
3407 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3408 if (depth > maxdepth)
3409 maxdepth = depth;
3410 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3411 if (instr->i_jrel || instr->i_jabs) {
3412 maxdepth = stackdepth_walk(c, instr->i_target,
3413 depth, maxdepth);
3414 if (instr->i_opcode == JUMP_ABSOLUTE ||
3415 instr->i_opcode == JUMP_FORWARD) {
3416 goto out; /* remaining code is dead */
3417 }
3418 }
3419 }
3420 if (b->b_next)
3421 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3422out:
3423 b->b_seen = 0;
3424 return maxdepth;
3425}
3426
3427/* Find the flow path that needs the largest stack. We assume that
3428 * cycles in the flow graph have no net effect on the stack depth.
3429 */
3430static int
3431stackdepth(struct compiler *c)
3432{
3433 basicblock *b, *entryblock;
3434 entryblock = NULL;
3435 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3436 b->b_seen = 0;
3437 b->b_startdepth = INT_MIN;
3438 entryblock = b;
3439 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003440 if (!entryblock)
3441 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442 return stackdepth_walk(c, entryblock, 0, 0);
3443}
3444
3445static int
3446assemble_init(struct assembler *a, int nblocks, int firstlineno)
3447{
3448 memset(a, 0, sizeof(struct assembler));
3449 a->a_lineno = firstlineno;
3450 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3451 if (!a->a_bytecode)
3452 return 0;
3453 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3454 if (!a->a_lnotab)
3455 return 0;
3456 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003458 if (!a->a_postorder) {
3459 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003461 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462 return 1;
3463}
3464
3465static void
3466assemble_free(struct assembler *a)
3467{
3468 Py_XDECREF(a->a_bytecode);
3469 Py_XDECREF(a->a_lnotab);
3470 if (a->a_postorder)
3471 PyObject_Free(a->a_postorder);
3472}
3473
3474/* Return the size of a basic block in bytes. */
3475
3476static int
3477instrsize(struct instr *instr)
3478{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003479 if (!instr->i_hasarg)
3480 return 1;
3481 if (instr->i_oparg > 0xffff)
3482 return 6;
3483 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484}
3485
3486static int
3487blocksize(basicblock *b)
3488{
3489 int i;
3490 int size = 0;
3491
3492 for (i = 0; i < b->b_iused; i++)
3493 size += instrsize(&b->b_instr[i]);
3494 return size;
3495}
3496
3497/* All about a_lnotab.
3498
3499c_lnotab is an array of unsigned bytes disguised as a Python string.
3500It is used to map bytecode offsets to source code line #s (when needed
3501for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003502
Tim Peters2a7f3842001-06-09 09:26:21 +00003503The array is conceptually a list of
3504 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003505pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003506
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003507 byte code offset source code line number
3508 0 1
3509 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003510 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003511 350 307
3512 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003513
3514The first trick is that these numbers aren't stored, only the increments
3515from one row to the next (this doesn't really work, but it's a start):
3516
3517 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3518
3519The second trick is that an unsigned byte can't hold negative values, or
3520values larger than 255, so (a) there's a deep assumption that byte code
3521offsets and their corresponding line #s both increase monotonically, and (b)
3522if at least one column jumps by more than 255 from one row to the next, more
3523than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003524from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003525part. A user of c_lnotab desiring to find the source line number
3526corresponding to a bytecode address A should do something like this
3527
3528 lineno = addr = 0
3529 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003530 addr += addr_incr
3531 if addr > A:
3532 return lineno
3533 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003534
3535In order for this to work, when the addr field increments by more than 255,
3536the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003537increment is < 256. So, in the example above, assemble_lnotab (it used
3538to be called com_set_lineno) should not (as was actually done until 2.2)
3539expand 300, 300 to 255, 255, 45, 45,
3540 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003541*/
3542
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003543static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003545{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 int d_bytecode, d_lineno;
3547 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003548 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549
3550 d_bytecode = a->a_offset - a->a_lineno_off;
3551 d_lineno = i->i_lineno - a->a_lineno;
3552
3553 assert(d_bytecode >= 0);
3554 assert(d_lineno >= 0);
3555
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003556 /* XXX(nnorwitz): is there a better way to handle this?
3557 for loops are special, we want to be able to trace them
3558 each time around, so we need to set an extra line number. */
3559 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003560 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003561
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003563 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 nbytes = a->a_lnotab_off + 2 * ncodes;
3565 len = PyString_GET_SIZE(a->a_lnotab);
3566 if (nbytes >= len) {
3567 if (len * 2 < nbytes)
3568 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003569 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 len *= 2;
3571 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3572 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003573 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003574 lnotab = (unsigned char *)
3575 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003576 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 *lnotab++ = 255;
3578 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 d_bytecode -= ncodes * 255;
3581 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003582 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 assert(d_bytecode <= 255);
3584 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003585 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 nbytes = a->a_lnotab_off + 2 * ncodes;
3587 len = PyString_GET_SIZE(a->a_lnotab);
3588 if (nbytes >= len) {
3589 if (len * 2 < nbytes)
3590 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003591 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 len *= 2;
3593 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3594 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003595 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003596 lnotab = (unsigned char *)
3597 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003599 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003601 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003603 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 d_lineno -= ncodes * 255;
3606 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003607 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003608
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609 len = PyString_GET_SIZE(a->a_lnotab);
3610 if (a->a_lnotab_off + 2 >= len) {
3611 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003612 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003613 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003614 lnotab = (unsigned char *)
3615 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 a->a_lnotab_off += 2;
3618 if (d_bytecode) {
3619 *lnotab++ = d_bytecode;
3620 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003621 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003622 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 *lnotab++ = 0;
3624 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 a->a_lineno = i->i_lineno;
3627 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003628 return 1;
3629}
3630
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631/* assemble_emit()
3632 Extend the bytecode with a new instruction.
3633 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003634*/
3635
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003636static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003638{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003639 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003640 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641 char *code;
3642
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003643 size = instrsize(i);
3644 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003646 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003647 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003649 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650 if (a->a_offset + size >= len) {
3651 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003652 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003653 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3655 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003656 if (size == 6) {
3657 assert(i->i_hasarg);
3658 *code++ = (char)EXTENDED_ARG;
3659 *code++ = ext & 0xff;
3660 *code++ = ext >> 8;
3661 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003662 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003664 if (i->i_hasarg) {
3665 assert(size == 3 || size == 6);
3666 *code++ = arg & 0xff;
3667 *code++ = arg >> 8;
3668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003670}
3671
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003672static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003674{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003676 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003677 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 /* Compute the size of each block and fixup jump args.
3680 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003681start:
3682 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003684 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685 bsize = blocksize(b);
3686 b->b_offset = totsize;
3687 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003688 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003689 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3691 bsize = b->b_offset;
3692 for (i = 0; i < b->b_iused; i++) {
3693 struct instr *instr = &b->b_instr[i];
3694 /* Relative jumps are computed relative to
3695 the instruction pointer after fetching
3696 the jump instruction.
3697 */
3698 bsize += instrsize(instr);
3699 if (instr->i_jabs)
3700 instr->i_oparg = instr->i_target->b_offset;
3701 else if (instr->i_jrel) {
3702 int delta = instr->i_target->b_offset - bsize;
3703 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003704 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003705 else
3706 continue;
3707 if (instr->i_oparg > 0xffff)
3708 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003709 }
3710 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003711
3712 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003713 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003714 with a better solution.
3715
3716 In the meantime, should the goto be dropped in favor
3717 of a loop?
3718
3719 The issue is that in the first loop blocksize() is called
3720 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003721 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003722 i_oparg is calculated in the second loop above.
3723
3724 So we loop until we stop seeing new EXTENDED_ARGs.
3725 The only EXTENDED_ARGs that could be popping up are
3726 ones in jump instructions. So this should converge
3727 fairly quickly.
3728 */
3729 if (last_extended_arg_count != extended_arg_count) {
3730 last_extended_arg_count = extended_arg_count;
3731 goto start;
3732 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003733}
3734
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003735static PyObject *
3736dict_keys_inorder(PyObject *dict, int offset)
3737{
3738 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003739 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003740
3741 tuple = PyTuple_New(size);
3742 if (tuple == NULL)
3743 return NULL;
3744 while (PyDict_Next(dict, &pos, &k, &v)) {
3745 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003746 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003747 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003748 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003749 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003750 PyTuple_SET_ITEM(tuple, i - offset, k);
3751 }
3752 return tuple;
3753}
3754
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003755static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003757{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758 PySTEntryObject *ste = c->u->u_ste;
3759 int flags = 0, n;
3760 if (ste->ste_type != ModuleBlock)
3761 flags |= CO_NEWLOCALS;
3762 if (ste->ste_type == FunctionBlock) {
3763 if (!ste->ste_unoptimized)
3764 flags |= CO_OPTIMIZED;
3765 if (ste->ste_nested)
3766 flags |= CO_NESTED;
3767 if (ste->ste_generator)
3768 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003769 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770 if (ste->ste_varargs)
3771 flags |= CO_VARARGS;
3772 if (ste->ste_varkeywords)
3773 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003774 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003776
3777 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003778 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 n = PyDict_Size(c->u->u_freevars);
3781 if (n < 0)
3782 return -1;
3783 if (n == 0) {
3784 n = PyDict_Size(c->u->u_cellvars);
3785 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003786 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787 if (n == 0) {
3788 flags |= CO_NOFREE;
3789 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003790 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003791
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003792 return flags;
3793}
3794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795static PyCodeObject *
3796makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003797{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798 PyObject *tmp;
3799 PyCodeObject *co = NULL;
3800 PyObject *consts = NULL;
3801 PyObject *names = NULL;
3802 PyObject *varnames = NULL;
3803 PyObject *filename = NULL;
3804 PyObject *name = NULL;
3805 PyObject *freevars = NULL;
3806 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003807 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 tmp = dict_keys_inorder(c->u->u_consts, 0);
3811 if (!tmp)
3812 goto error;
3813 consts = PySequence_List(tmp); /* optimize_code requires a list */
3814 Py_DECREF(tmp);
3815
3816 names = dict_keys_inorder(c->u->u_names, 0);
3817 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3818 if (!consts || !names || !varnames)
3819 goto error;
3820
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003821 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3822 if (!cellvars)
3823 goto error;
3824 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3825 if (!freevars)
3826 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 filename = PyString_FromString(c->c_filename);
3828 if (!filename)
3829 goto error;
3830
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003831 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832 flags = compute_code_flags(c);
3833 if (flags < 0)
3834 goto error;
3835
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003836 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003837 if (!bytecode)
3838 goto error;
3839
3840 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3841 if (!tmp)
3842 goto error;
3843 Py_DECREF(consts);
3844 consts = tmp;
3845
3846 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3847 bytecode, consts, names, varnames,
3848 freevars, cellvars,
3849 filename, c->u->u_name,
3850 c->u->u_firstlineno,
3851 a->a_lnotab);
3852 error:
3853 Py_XDECREF(consts);
3854 Py_XDECREF(names);
3855 Py_XDECREF(varnames);
3856 Py_XDECREF(filename);
3857 Py_XDECREF(name);
3858 Py_XDECREF(freevars);
3859 Py_XDECREF(cellvars);
3860 Py_XDECREF(bytecode);
3861 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003862}
3863
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003864
3865/* For debugging purposes only */
3866#if 0
3867static void
3868dump_instr(const struct instr *i)
3869{
3870 const char *jrel = i->i_jrel ? "jrel " : "";
3871 const char *jabs = i->i_jabs ? "jabs " : "";
3872 char arg[128];
3873
3874 *arg = '\0';
3875 if (i->i_hasarg)
3876 sprintf(arg, "arg: %d ", i->i_oparg);
3877
3878 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3879 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3880}
3881
3882static void
3883dump_basicblock(const basicblock *b)
3884{
3885 const char *seen = b->b_seen ? "seen " : "";
3886 const char *b_return = b->b_return ? "return " : "";
3887 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3888 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3889 if (b->b_instr) {
3890 int i;
3891 for (i = 0; i < b->b_iused; i++) {
3892 fprintf(stderr, " [%02d] ", i);
3893 dump_instr(b->b_instr + i);
3894 }
3895 }
3896}
3897#endif
3898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899static PyCodeObject *
3900assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003901{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 basicblock *b, *entryblock;
3903 struct assembler a;
3904 int i, j, nblocks;
3905 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003906
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003907 /* Make sure every block that falls off the end returns None.
3908 XXX NEXT_BLOCK() isn't quite right, because if the last
3909 block ends with a jump or return b_next shouldn't set.
3910 */
3911 if (!c->u->u_curblock->b_return) {
3912 NEXT_BLOCK(c);
3913 if (addNone)
3914 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3915 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003916 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 nblocks = 0;
3919 entryblock = NULL;
3920 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3921 nblocks++;
3922 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003923 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003924
Neal Norwitzed657552006-07-10 00:04:44 +00003925 /* Set firstlineno if it wasn't explicitly set. */
3926 if (!c->u->u_firstlineno) {
3927 if (entryblock && entryblock->b_instr)
3928 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3929 else
3930 c->u->u_firstlineno = 1;
3931 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3933 goto error;
3934 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003935
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003937 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003939 /* Emit code in reverse postorder from dfs. */
3940 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003941 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942 for (j = 0; j < b->b_iused; j++)
3943 if (!assemble_emit(&a, &b->b_instr[j]))
3944 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003945 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003946
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3948 goto error;
3949 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3950 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003952 co = makecode(c, &a);
3953 error:
3954 assemble_free(&a);
3955 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003956}