blob: ae734ffe2c79103ae5db48769bc3093d8ab71ecb [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);
Georg Brandl2c4fb8d2006-10-29 08:47:08 +00002622 /* delete the temporary list name 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 asdl_seq *generators = e->v.ListComp.generators;
2636
2637 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002638 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639 if (!tmp)
2640 return 0;
2641 ADDOP_I(c, BUILD_LIST, 0);
2642 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002644 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2645 e->v.ListComp.elt);
2646 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 return rc;
2648}
2649
2650static int
2651compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 asdl_seq *generators, int gen_index,
2653 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654{
2655 /* generate code for the iterator, then each of the ifs,
2656 and then write to the element */
2657
2658 comprehension_ty ge;
2659 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002660 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661
2662 start = compiler_new_block(c);
2663 skip = compiler_new_block(c);
2664 if_cleanup = compiler_new_block(c);
2665 anchor = compiler_new_block(c);
2666 end = compiler_new_block(c);
2667
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002668 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669 anchor == NULL || end == NULL)
2670 return 0;
2671
Anthony Baxter7b782b62006-04-11 12:01:56 +00002672 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 ADDOP_JREL(c, SETUP_LOOP, end);
2674 if (!compiler_push_fblock(c, LOOP, start))
2675 return 0;
2676
2677 if (gen_index == 0) {
2678 /* Receive outermost iter as an implicit argument */
2679 c->u->u_argcount = 1;
2680 ADDOP_I(c, LOAD_FAST, 0);
2681 }
2682 else {
2683 /* Sub-iter - calculate on the fly */
2684 VISIT(c, expr, ge->iter);
2685 ADDOP(c, GET_ITER);
2686 }
2687 compiler_use_next_block(c, start);
2688 ADDOP_JREL(c, FOR_ITER, anchor);
2689 NEXT_BLOCK(c);
2690 VISIT(c, expr, ge->target);
2691
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002692 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693 n = asdl_seq_LEN(ge->ifs);
2694 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002695 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 VISIT(c, expr, e);
2697 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2698 NEXT_BLOCK(c);
2699 ADDOP(c, POP_TOP);
2700 }
2701
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002702 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2704 return 0;
2705
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 /* only append after the last 'for' generator */
2707 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 VISIT(c, expr, elt);
2709 ADDOP(c, YIELD_VALUE);
2710 ADDOP(c, POP_TOP);
2711
2712 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002713 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 for (i = 0; i < n; i++) {
2715 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002716 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 compiler_use_next_block(c, if_cleanup);
2718
2719 ADDOP(c, POP_TOP);
2720 }
2721 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2722 compiler_use_next_block(c, anchor);
2723 ADDOP(c, POP_BLOCK);
2724 compiler_pop_fblock(c, LOOP, start);
2725 compiler_use_next_block(c, end);
2726
2727 return 1;
2728}
2729
2730static int
2731compiler_genexp(struct compiler *c, expr_ty e)
2732{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002733 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734 PyCodeObject *co;
2735 expr_ty outermost_iter = ((comprehension_ty)
2736 (asdl_seq_GET(e->v.GeneratorExp.generators,
2737 0)))->iter;
2738
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002739 if (!name) {
2740 name = PyString_FromString("<genexpr>");
2741 if (!name)
2742 return 0;
2743 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
2745 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2746 return 0;
2747 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2748 e->v.GeneratorExp.elt);
2749 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002750 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751 if (co == NULL)
2752 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002754 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002755 Py_DECREF(co);
2756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 VISIT(c, expr, outermost_iter);
2758 ADDOP(c, GET_ITER);
2759 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760
2761 return 1;
2762}
2763
2764static int
2765compiler_visit_keyword(struct compiler *c, keyword_ty k)
2766{
2767 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2768 VISIT(c, expr, k->value);
2769 return 1;
2770}
2771
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002772/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773 whether they are true or false.
2774
2775 Return values: 1 for true, 0 for false, -1 for non-constant.
2776 */
2777
2778static int
2779expr_constant(expr_ty e)
2780{
2781 switch (e->kind) {
2782 case Num_kind:
2783 return PyObject_IsTrue(e->v.Num.n);
2784 case Str_kind:
2785 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002786 case Name_kind:
2787 /* __debug__ is not assignable, so we can optimize
2788 * it away in if and while statements */
2789 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2790 "__debug__") == 0)
2791 return ! Py_OptimizeFlag;
2792 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002793 default:
2794 return -1;
2795 }
2796}
2797
Guido van Rossumc2e20742006-02-27 22:32:47 +00002798/*
2799 Implements the with statement from PEP 343.
2800
2801 The semantics outlined in that PEP are as follows:
2802
2803 with EXPR as VAR:
2804 BLOCK
2805
2806 It is implemented roughly as:
2807
Guido van Rossumda5b7012006-05-02 19:47:52 +00002808 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002809 exit = context.__exit__ # not calling it
2810 value = context.__enter__()
2811 try:
2812 VAR = value # if VAR present in the syntax
2813 BLOCK
2814 finally:
2815 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002817 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002818 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002819 exit(*exc)
2820 */
2821static int
2822compiler_with(struct compiler *c, stmt_ty s)
2823{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002824 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002825 basicblock *block, *finally;
2826 identifier tmpexit, tmpvalue = NULL;
2827
2828 assert(s->kind == With_kind);
2829
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002831 enter_attr = PyString_InternFromString("__enter__");
2832 if (!enter_attr)
2833 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834 }
2835 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002836 exit_attr = PyString_InternFromString("__exit__");
2837 if (!exit_attr)
2838 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002839 }
2840
2841 block = compiler_new_block(c);
2842 finally = compiler_new_block(c);
2843 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002844 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002845
2846 /* Create a temporary variable to hold context.__exit__ */
2847 tmpexit = compiler_new_tmpname(c);
2848 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002849 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002850 PyArena_AddPyObject(c->c_arena, tmpexit);
2851
2852 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002853 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002854 We need to do this rather than preserving it on the stack
2855 because SETUP_FINALLY remembers the stack level.
2856 We need to do the assignment *inside* the try/finally
2857 so that context.__exit__() is called when the assignment
2858 fails. But we need to call context.__enter__() *before*
2859 the try/finally so that if it fails we won't call
2860 context.__exit__().
2861 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002862 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002863 if (tmpvalue == NULL)
2864 return 0;
2865 PyArena_AddPyObject(c->c_arena, tmpvalue);
2866 }
2867
Guido van Rossumda5b7012006-05-02 19:47:52 +00002868 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002870
2871 /* Squirrel away context.__exit__ */
2872 ADDOP(c, DUP_TOP);
2873 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2874 if (!compiler_nameop(c, tmpexit, Store))
2875 return 0;
2876
2877 /* Call context.__enter__() */
2878 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2879 ADDOP_I(c, CALL_FUNCTION, 0);
2880
2881 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002882 /* Store it in tmpvalue */
2883 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002884 return 0;
2885 }
2886 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002887 /* Discard result from context.__enter__() */
2888 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002889 }
2890
2891 /* Start the try block */
2892 ADDOP_JREL(c, SETUP_FINALLY, finally);
2893
2894 compiler_use_next_block(c, block);
2895 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002897 }
2898
2899 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002900 /* Bind saved result of context.__enter__() to VAR */
2901 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002902 !compiler_nameop(c, tmpvalue, Del))
2903 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002904 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002905 }
2906
2907 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002908 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002909
2910 /* End of try block; start the finally block */
2911 ADDOP(c, POP_BLOCK);
2912 compiler_pop_fblock(c, FINALLY_TRY, block);
2913
2914 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2915 compiler_use_next_block(c, finally);
2916 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002917 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002918
2919 /* Finally block starts; push tmpexit and issue our magic opcode. */
2920 if (!compiler_nameop(c, tmpexit, Load) ||
2921 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002922 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002923 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002924
2925 /* Finally block ends. */
2926 ADDOP(c, END_FINALLY);
2927 compiler_pop_fblock(c, FINALLY_END, finally);
2928 return 1;
2929}
2930
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931static int
2932compiler_visit_expr(struct compiler *c, expr_ty e)
2933{
2934 int i, n;
2935
Jeremy Hylton12603c42006-04-01 16:18:02 +00002936 /* If expr e has a different line number than the last expr/stmt,
2937 set a new line number for the next instruction.
2938 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 if (e->lineno > c->u->u_lineno) {
2940 c->u->u_lineno = e->lineno;
2941 c->u->u_lineno_set = false;
2942 }
2943 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002944 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002946 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947 VISIT(c, expr, e->v.BinOp.left);
2948 VISIT(c, expr, e->v.BinOp.right);
2949 ADDOP(c, binop(c, e->v.BinOp.op));
2950 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002951 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952 VISIT(c, expr, e->v.UnaryOp.operand);
2953 ADDOP(c, unaryop(e->v.UnaryOp.op));
2954 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002955 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002957 case IfExp_kind:
2958 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002959 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 /* XXX get rid of arg? */
2961 ADDOP_I(c, BUILD_MAP, 0);
2962 n = asdl_seq_LEN(e->v.Dict.values);
2963 /* We must arrange things just right for STORE_SUBSCR.
2964 It wants the stack to look like (value) (dict) (key) */
2965 for (i = 0; i < n; i++) {
2966 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002967 VISIT(c, expr,
2968 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002970 VISIT(c, expr,
2971 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972 ADDOP(c, STORE_SUBSCR);
2973 }
2974 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002975 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002977 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978 return compiler_genexp(c, e);
2979 case Yield_kind:
2980 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 /*
2983 for (i = 0; i < c->u->u_nfblocks; i++) {
2984 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2985 return compiler_error(
2986 c, "'yield' not allowed in a 'try' "
2987 "block with a 'finally' clause");
2988 }
2989 */
2990 if (e->v.Yield.value) {
2991 VISIT(c, expr, e->v.Yield.value);
2992 }
2993 else {
2994 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2995 }
2996 ADDOP(c, YIELD_VALUE);
2997 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002998 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003000 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003002 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003 VISIT(c, expr, e->v.Repr.value);
3004 ADDOP(c, UNARY_CONVERT);
3005 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003006 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3008 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003009 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3011 break;
3012 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003013 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 if (e->v.Attribute.ctx != AugStore)
3015 VISIT(c, expr, e->v.Attribute.value);
3016 switch (e->v.Attribute.ctx) {
3017 case AugLoad:
3018 ADDOP(c, DUP_TOP);
3019 /* Fall through to load */
3020 case Load:
3021 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3022 break;
3023 case AugStore:
3024 ADDOP(c, ROT_TWO);
3025 /* Fall through to save */
3026 case Store:
3027 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3028 break;
3029 case Del:
3030 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3031 break;
3032 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003033 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003034 PyErr_SetString(PyExc_SystemError,
3035 "param invalid in attribute expression");
3036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037 }
3038 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003039 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 switch (e->v.Subscript.ctx) {
3041 case AugLoad:
3042 VISIT(c, expr, e->v.Subscript.value);
3043 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3044 break;
3045 case Load:
3046 VISIT(c, expr, e->v.Subscript.value);
3047 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3048 break;
3049 case AugStore:
3050 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3051 break;
3052 case Store:
3053 VISIT(c, expr, e->v.Subscript.value);
3054 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3055 break;
3056 case Del:
3057 VISIT(c, expr, e->v.Subscript.value);
3058 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3059 break;
3060 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003061 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003062 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003063 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003064 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065 }
3066 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003067 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003068 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3069 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 return compiler_tuple(c, e);
3074 }
3075 return 1;
3076}
3077
3078static int
3079compiler_augassign(struct compiler *c, stmt_ty s)
3080{
3081 expr_ty e = s->v.AugAssign.target;
3082 expr_ty auge;
3083
3084 assert(s->kind == AugAssign_kind);
3085
3086 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003087 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003089 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003090 if (auge == NULL)
3091 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092 VISIT(c, expr, auge);
3093 VISIT(c, expr, s->v.AugAssign.value);
3094 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3095 auge->v.Attribute.ctx = AugStore;
3096 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003097 break;
3098 case Subscript_kind:
3099 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003100 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003101 if (auge == NULL)
3102 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103 VISIT(c, expr, auge);
3104 VISIT(c, expr, s->v.AugAssign.value);
3105 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003106 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003108 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003109 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003110 if (!compiler_nameop(c, e->v.Name.id, Load))
3111 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112 VISIT(c, expr, s->v.AugAssign.value);
3113 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3114 return compiler_nameop(c, e->v.Name.id, Store);
3115 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003116 PyErr_Format(PyExc_SystemError,
3117 "invalid node type (%d) for augmented assignment",
3118 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003119 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003120 }
3121 return 1;
3122}
3123
3124static int
3125compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3126{
3127 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003128 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3129 PyErr_SetString(PyExc_SystemError,
3130 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003131 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003132 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003133 f = &c->u->u_fblock[c->u->u_nfblocks++];
3134 f->fb_type = t;
3135 f->fb_block = b;
3136 return 1;
3137}
3138
3139static void
3140compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3141{
3142 struct compiler_unit *u = c->u;
3143 assert(u->u_nfblocks > 0);
3144 u->u_nfblocks--;
3145 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3146 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3147}
3148
Jeremy Hylton82271f12006-10-04 02:24:52 +00003149static int
3150compiler_in_loop(struct compiler *c) {
3151 int i;
3152 struct compiler_unit *u = c->u;
3153 for (i = 0; i < u->u_nfblocks; ++i) {
3154 if (u->u_fblock[i].fb_type == LOOP)
3155 return 1;
3156 }
3157 return 0;
3158}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159/* Raises a SyntaxError and returns 0.
3160 If something goes wrong, a different exception may be raised.
3161*/
3162
3163static int
3164compiler_error(struct compiler *c, const char *errstr)
3165{
3166 PyObject *loc;
3167 PyObject *u = NULL, *v = NULL;
3168
3169 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3170 if (!loc) {
3171 Py_INCREF(Py_None);
3172 loc = Py_None;
3173 }
3174 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3175 Py_None, loc);
3176 if (!u)
3177 goto exit;
3178 v = Py_BuildValue("(zO)", errstr, u);
3179 if (!v)
3180 goto exit;
3181 PyErr_SetObject(PyExc_SyntaxError, v);
3182 exit:
3183 Py_DECREF(loc);
3184 Py_XDECREF(u);
3185 Py_XDECREF(v);
3186 return 0;
3187}
3188
3189static int
3190compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003191 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 /* XXX this code is duplicated */
3196 switch (ctx) {
3197 case AugLoad: /* fall through to Load */
3198 case Load: op = BINARY_SUBSCR; break;
3199 case AugStore:/* fall through to Store */
3200 case Store: op = STORE_SUBSCR; break;
3201 case Del: op = DELETE_SUBSCR; break;
3202 case Param:
3203 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003204 "invalid %s kind %d in subscript\n",
3205 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003206 return 0;
3207 }
3208 if (ctx == AugLoad) {
3209 ADDOP_I(c, DUP_TOPX, 2);
3210 }
3211 else if (ctx == AugStore) {
3212 ADDOP(c, ROT_THREE);
3213 }
3214 ADDOP(c, op);
3215 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216}
3217
3218static int
3219compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3220{
3221 int n = 2;
3222 assert(s->kind == Slice_kind);
3223
3224 /* only handles the cases where BUILD_SLICE is emitted */
3225 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003226 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227 }
3228 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003229 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003231
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003233 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234 }
3235 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003236 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237 }
3238
3239 if (s->v.Slice.step) {
3240 n++;
3241 VISIT(c, expr, s->v.Slice.step);
3242 }
3243 ADDOP_I(c, BUILD_SLICE, n);
3244 return 1;
3245}
3246
3247static int
3248compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3249{
3250 int op = 0, slice_offset = 0, stack_count = 0;
3251
3252 assert(s->v.Slice.step == NULL);
3253 if (s->v.Slice.lower) {
3254 slice_offset++;
3255 stack_count++;
3256 if (ctx != AugStore)
3257 VISIT(c, expr, s->v.Slice.lower);
3258 }
3259 if (s->v.Slice.upper) {
3260 slice_offset += 2;
3261 stack_count++;
3262 if (ctx != AugStore)
3263 VISIT(c, expr, s->v.Slice.upper);
3264 }
3265
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003266 if (ctx == AugLoad) {
3267 switch (stack_count) {
3268 case 0: ADDOP(c, DUP_TOP); break;
3269 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3270 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3271 }
3272 }
3273 else if (ctx == AugStore) {
3274 switch (stack_count) {
3275 case 0: ADDOP(c, ROT_TWO); break;
3276 case 1: ADDOP(c, ROT_THREE); break;
3277 case 2: ADDOP(c, ROT_FOUR); break;
3278 }
3279 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280
3281 switch (ctx) {
3282 case AugLoad: /* fall through to Load */
3283 case Load: op = SLICE; break;
3284 case AugStore:/* fall through to Store */
3285 case Store: op = STORE_SLICE; break;
3286 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003287 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003288 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003289 PyErr_SetString(PyExc_SystemError,
3290 "param invalid in simple slice");
3291 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 }
3293
3294 ADDOP(c, op + slice_offset);
3295 return 1;
3296}
3297
3298static int
3299compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3300 expr_context_ty ctx)
3301{
3302 switch (s->kind) {
3303 case Ellipsis_kind:
3304 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3305 break;
3306 case Slice_kind:
3307 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308 case Index_kind:
3309 VISIT(c, expr, s->v.Index.value);
3310 break;
3311 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003312 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003313 PyErr_SetString(PyExc_SystemError,
3314 "extended slice invalid in nested slice");
3315 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 }
3317 return 1;
3318}
3319
3320
3321static int
3322compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3323{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003324 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003326 case Index_kind:
3327 kindname = "index";
3328 if (ctx != AugStore) {
3329 VISIT(c, expr, s->v.Index.value);
3330 }
3331 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003333 kindname = "ellipsis";
3334 if (ctx != AugStore) {
3335 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337 break;
3338 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003339 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340 if (!s->v.Slice.step)
3341 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003342 if (ctx != AugStore) {
3343 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344 return 0;
3345 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003346 break;
3347 case ExtSlice_kind:
3348 kindname = "extended slice";
3349 if (ctx != AugStore) {
3350 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3351 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003352 slice_ty sub = (slice_ty)asdl_seq_GET(
3353 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003354 if (!compiler_visit_nested_slice(c, sub, ctx))
3355 return 0;
3356 }
3357 ADDOP_I(c, BUILD_TUPLE, n);
3358 }
3359 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003360 default:
3361 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003362 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003365 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366}
3367
3368/* do depth-first search of basic block graph, starting with block.
3369 post records the block indices in post-order.
3370
3371 XXX must handle implicit jumps from one block to next
3372*/
3373
3374static void
3375dfs(struct compiler *c, basicblock *b, struct assembler *a)
3376{
3377 int i;
3378 struct instr *instr = NULL;
3379
3380 if (b->b_seen)
3381 return;
3382 b->b_seen = 1;
3383 if (b->b_next != NULL)
3384 dfs(c, b->b_next, a);
3385 for (i = 0; i < b->b_iused; i++) {
3386 instr = &b->b_instr[i];
3387 if (instr->i_jrel || instr->i_jabs)
3388 dfs(c, instr->i_target, a);
3389 }
3390 a->a_postorder[a->a_nblocks++] = b;
3391}
3392
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003393static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3395{
3396 int i;
3397 struct instr *instr;
3398 if (b->b_seen || b->b_startdepth >= depth)
3399 return maxdepth;
3400 b->b_seen = 1;
3401 b->b_startdepth = depth;
3402 for (i = 0; i < b->b_iused; i++) {
3403 instr = &b->b_instr[i];
3404 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3405 if (depth > maxdepth)
3406 maxdepth = depth;
3407 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3408 if (instr->i_jrel || instr->i_jabs) {
3409 maxdepth = stackdepth_walk(c, instr->i_target,
3410 depth, maxdepth);
3411 if (instr->i_opcode == JUMP_ABSOLUTE ||
3412 instr->i_opcode == JUMP_FORWARD) {
3413 goto out; /* remaining code is dead */
3414 }
3415 }
3416 }
3417 if (b->b_next)
3418 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3419out:
3420 b->b_seen = 0;
3421 return maxdepth;
3422}
3423
3424/* Find the flow path that needs the largest stack. We assume that
3425 * cycles in the flow graph have no net effect on the stack depth.
3426 */
3427static int
3428stackdepth(struct compiler *c)
3429{
3430 basicblock *b, *entryblock;
3431 entryblock = NULL;
3432 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3433 b->b_seen = 0;
3434 b->b_startdepth = INT_MIN;
3435 entryblock = b;
3436 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003437 if (!entryblock)
3438 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439 return stackdepth_walk(c, entryblock, 0, 0);
3440}
3441
3442static int
3443assemble_init(struct assembler *a, int nblocks, int firstlineno)
3444{
3445 memset(a, 0, sizeof(struct assembler));
3446 a->a_lineno = firstlineno;
3447 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3448 if (!a->a_bytecode)
3449 return 0;
3450 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3451 if (!a->a_lnotab)
3452 return 0;
3453 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003454 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003455 if (!a->a_postorder) {
3456 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003458 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459 return 1;
3460}
3461
3462static void
3463assemble_free(struct assembler *a)
3464{
3465 Py_XDECREF(a->a_bytecode);
3466 Py_XDECREF(a->a_lnotab);
3467 if (a->a_postorder)
3468 PyObject_Free(a->a_postorder);
3469}
3470
3471/* Return the size of a basic block in bytes. */
3472
3473static int
3474instrsize(struct instr *instr)
3475{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003476 if (!instr->i_hasarg)
3477 return 1;
3478 if (instr->i_oparg > 0xffff)
3479 return 6;
3480 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481}
3482
3483static int
3484blocksize(basicblock *b)
3485{
3486 int i;
3487 int size = 0;
3488
3489 for (i = 0; i < b->b_iused; i++)
3490 size += instrsize(&b->b_instr[i]);
3491 return size;
3492}
3493
3494/* All about a_lnotab.
3495
3496c_lnotab is an array of unsigned bytes disguised as a Python string.
3497It is used to map bytecode offsets to source code line #s (when needed
3498for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003499
Tim Peters2a7f3842001-06-09 09:26:21 +00003500The array is conceptually a list of
3501 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003502pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003503
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003504 byte code offset source code line number
3505 0 1
3506 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003507 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003508 350 307
3509 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003510
3511The first trick is that these numbers aren't stored, only the increments
3512from one row to the next (this doesn't really work, but it's a start):
3513
3514 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3515
3516The second trick is that an unsigned byte can't hold negative values, or
3517values larger than 255, so (a) there's a deep assumption that byte code
3518offsets and their corresponding line #s both increase monotonically, and (b)
3519if at least one column jumps by more than 255 from one row to the next, more
3520than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003521from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003522part. A user of c_lnotab desiring to find the source line number
3523corresponding to a bytecode address A should do something like this
3524
3525 lineno = addr = 0
3526 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003527 addr += addr_incr
3528 if addr > A:
3529 return lineno
3530 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003531
3532In order for this to work, when the addr field increments by more than 255,
3533the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003534increment is < 256. So, in the example above, assemble_lnotab (it used
3535to be called com_set_lineno) should not (as was actually done until 2.2)
3536expand 300, 300 to 255, 255, 45, 45,
3537 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003538*/
3539
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003540static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003542{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 int d_bytecode, d_lineno;
3544 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003545 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546
3547 d_bytecode = a->a_offset - a->a_lineno_off;
3548 d_lineno = i->i_lineno - a->a_lineno;
3549
3550 assert(d_bytecode >= 0);
3551 assert(d_lineno >= 0);
3552
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003553 /* XXX(nnorwitz): is there a better way to handle this?
3554 for loops are special, we want to be able to trace them
3555 each time around, so we need to set an extra line number. */
3556 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003557 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003558
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003560 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 nbytes = a->a_lnotab_off + 2 * ncodes;
3562 len = PyString_GET_SIZE(a->a_lnotab);
3563 if (nbytes >= len) {
3564 if (len * 2 < nbytes)
3565 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003566 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567 len *= 2;
3568 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3569 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003570 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003571 lnotab = (unsigned char *)
3572 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003573 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 *lnotab++ = 255;
3575 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003576 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 d_bytecode -= ncodes * 255;
3578 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 assert(d_bytecode <= 255);
3581 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003582 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 nbytes = a->a_lnotab_off + 2 * ncodes;
3584 len = PyString_GET_SIZE(a->a_lnotab);
3585 if (nbytes >= len) {
3586 if (len * 2 < nbytes)
3587 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003588 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 len *= 2;
3590 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3591 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003592 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003593 lnotab = (unsigned char *)
3594 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003596 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003598 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003600 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 d_lineno -= ncodes * 255;
3603 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003604 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003605
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 len = PyString_GET_SIZE(a->a_lnotab);
3607 if (a->a_lnotab_off + 2 >= len) {
3608 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003609 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003610 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003611 lnotab = (unsigned char *)
3612 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003613
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 a->a_lnotab_off += 2;
3615 if (d_bytecode) {
3616 *lnotab++ = d_bytecode;
3617 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003618 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003619 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 *lnotab++ = 0;
3621 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 a->a_lineno = i->i_lineno;
3624 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003625 return 1;
3626}
3627
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628/* assemble_emit()
3629 Extend the bytecode with a new instruction.
3630 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003631*/
3632
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003633static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003635{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003636 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003637 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 char *code;
3639
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003640 size = instrsize(i);
3641 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003643 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003644 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003646 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647 if (a->a_offset + size >= len) {
3648 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003649 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003650 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3652 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003653 if (size == 6) {
3654 assert(i->i_hasarg);
3655 *code++ = (char)EXTENDED_ARG;
3656 *code++ = ext & 0xff;
3657 *code++ = ext >> 8;
3658 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003659 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003661 if (i->i_hasarg) {
3662 assert(size == 3 || size == 6);
3663 *code++ = arg & 0xff;
3664 *code++ = arg >> 8;
3665 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003667}
3668
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003669static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003671{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003673 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003674 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676 /* Compute the size of each block and fixup jump args.
3677 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003678start:
3679 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003681 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682 bsize = blocksize(b);
3683 b->b_offset = totsize;
3684 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003685 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003686 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3688 bsize = b->b_offset;
3689 for (i = 0; i < b->b_iused; i++) {
3690 struct instr *instr = &b->b_instr[i];
3691 /* Relative jumps are computed relative to
3692 the instruction pointer after fetching
3693 the jump instruction.
3694 */
3695 bsize += instrsize(instr);
3696 if (instr->i_jabs)
3697 instr->i_oparg = instr->i_target->b_offset;
3698 else if (instr->i_jrel) {
3699 int delta = instr->i_target->b_offset - bsize;
3700 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003701 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003702 else
3703 continue;
3704 if (instr->i_oparg > 0xffff)
3705 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003706 }
3707 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003708
3709 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003710 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003711 with a better solution.
3712
3713 In the meantime, should the goto be dropped in favor
3714 of a loop?
3715
3716 The issue is that in the first loop blocksize() is called
3717 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003718 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003719 i_oparg is calculated in the second loop above.
3720
3721 So we loop until we stop seeing new EXTENDED_ARGs.
3722 The only EXTENDED_ARGs that could be popping up are
3723 ones in jump instructions. So this should converge
3724 fairly quickly.
3725 */
3726 if (last_extended_arg_count != extended_arg_count) {
3727 last_extended_arg_count = extended_arg_count;
3728 goto start;
3729 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003730}
3731
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003732static PyObject *
3733dict_keys_inorder(PyObject *dict, int offset)
3734{
3735 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003736 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003737
3738 tuple = PyTuple_New(size);
3739 if (tuple == NULL)
3740 return NULL;
3741 while (PyDict_Next(dict, &pos, &k, &v)) {
3742 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003743 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003744 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003745 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003746 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003747 PyTuple_SET_ITEM(tuple, i - offset, k);
3748 }
3749 return tuple;
3750}
3751
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003752static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003754{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755 PySTEntryObject *ste = c->u->u_ste;
3756 int flags = 0, n;
3757 if (ste->ste_type != ModuleBlock)
3758 flags |= CO_NEWLOCALS;
3759 if (ste->ste_type == FunctionBlock) {
3760 if (!ste->ste_unoptimized)
3761 flags |= CO_OPTIMIZED;
3762 if (ste->ste_nested)
3763 flags |= CO_NESTED;
3764 if (ste->ste_generator)
3765 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003766 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767 if (ste->ste_varargs)
3768 flags |= CO_VARARGS;
3769 if (ste->ste_varkeywords)
3770 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003771 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003773
3774 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003775 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777 n = PyDict_Size(c->u->u_freevars);
3778 if (n < 0)
3779 return -1;
3780 if (n == 0) {
3781 n = PyDict_Size(c->u->u_cellvars);
3782 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003783 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784 if (n == 0) {
3785 flags |= CO_NOFREE;
3786 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003787 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003788
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003789 return flags;
3790}
3791
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792static PyCodeObject *
3793makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003794{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795 PyObject *tmp;
3796 PyCodeObject *co = NULL;
3797 PyObject *consts = NULL;
3798 PyObject *names = NULL;
3799 PyObject *varnames = NULL;
3800 PyObject *filename = NULL;
3801 PyObject *name = NULL;
3802 PyObject *freevars = NULL;
3803 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003804 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003806
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807 tmp = dict_keys_inorder(c->u->u_consts, 0);
3808 if (!tmp)
3809 goto error;
3810 consts = PySequence_List(tmp); /* optimize_code requires a list */
3811 Py_DECREF(tmp);
3812
3813 names = dict_keys_inorder(c->u->u_names, 0);
3814 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3815 if (!consts || !names || !varnames)
3816 goto error;
3817
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003818 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3819 if (!cellvars)
3820 goto error;
3821 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3822 if (!freevars)
3823 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824 filename = PyString_FromString(c->c_filename);
3825 if (!filename)
3826 goto error;
3827
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003828 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829 flags = compute_code_flags(c);
3830 if (flags < 0)
3831 goto error;
3832
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003833 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003834 if (!bytecode)
3835 goto error;
3836
3837 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3838 if (!tmp)
3839 goto error;
3840 Py_DECREF(consts);
3841 consts = tmp;
3842
3843 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3844 bytecode, consts, names, varnames,
3845 freevars, cellvars,
3846 filename, c->u->u_name,
3847 c->u->u_firstlineno,
3848 a->a_lnotab);
3849 error:
3850 Py_XDECREF(consts);
3851 Py_XDECREF(names);
3852 Py_XDECREF(varnames);
3853 Py_XDECREF(filename);
3854 Py_XDECREF(name);
3855 Py_XDECREF(freevars);
3856 Py_XDECREF(cellvars);
3857 Py_XDECREF(bytecode);
3858 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003859}
3860
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003861
3862/* For debugging purposes only */
3863#if 0
3864static void
3865dump_instr(const struct instr *i)
3866{
3867 const char *jrel = i->i_jrel ? "jrel " : "";
3868 const char *jabs = i->i_jabs ? "jabs " : "";
3869 char arg[128];
3870
3871 *arg = '\0';
3872 if (i->i_hasarg)
3873 sprintf(arg, "arg: %d ", i->i_oparg);
3874
3875 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3876 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3877}
3878
3879static void
3880dump_basicblock(const basicblock *b)
3881{
3882 const char *seen = b->b_seen ? "seen " : "";
3883 const char *b_return = b->b_return ? "return " : "";
3884 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3885 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3886 if (b->b_instr) {
3887 int i;
3888 for (i = 0; i < b->b_iused; i++) {
3889 fprintf(stderr, " [%02d] ", i);
3890 dump_instr(b->b_instr + i);
3891 }
3892 }
3893}
3894#endif
3895
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003896static PyCodeObject *
3897assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003898{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 basicblock *b, *entryblock;
3900 struct assembler a;
3901 int i, j, nblocks;
3902 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 /* Make sure every block that falls off the end returns None.
3905 XXX NEXT_BLOCK() isn't quite right, because if the last
3906 block ends with a jump or return b_next shouldn't set.
3907 */
3908 if (!c->u->u_curblock->b_return) {
3909 NEXT_BLOCK(c);
3910 if (addNone)
3911 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3912 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003913 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915 nblocks = 0;
3916 entryblock = NULL;
3917 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3918 nblocks++;
3919 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003920 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003921
Neal Norwitzed657552006-07-10 00:04:44 +00003922 /* Set firstlineno if it wasn't explicitly set. */
3923 if (!c->u->u_firstlineno) {
3924 if (entryblock && entryblock->b_instr)
3925 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3926 else
3927 c->u->u_firstlineno = 1;
3928 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003929 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3930 goto error;
3931 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003932
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003934 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003935
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936 /* Emit code in reverse postorder from dfs. */
3937 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003938 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003939 for (j = 0; j < b->b_iused; j++)
3940 if (!assemble_emit(&a, &b->b_instr[j]))
3941 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003942 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003944 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3945 goto error;
3946 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3947 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003948
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949 co = makecode(c, &a);
3950 error:
3951 assemble_free(&a);
3952 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003953}