blob: 1ab315b7e27196ba69814934501132445bec2a2a [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_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000118 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000119 /* Pointer to the most recently allocated block. By following b_list
120 members, you can reach all early allocated blocks. */
121 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000123 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
125 int u_nfblocks;
126 struct fblockinfo u_fblock[CO_MAXBLOCKS];
127
128 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000129 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130 bool u_lineno_set; /* boolean to indicate whether instr
131 has been generated with current lineno */
132};
133
134/* This struct captures the global state of a compilation.
135
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000136The u pointer points to the current compilation unit, while units
137for enclosing blocks are stored in c_stack. The u and c_stack are
138managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139*/
140
141struct compiler {
142 const char *c_filename;
143 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145 PyCompilerFlags *c_flags;
146
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000147 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000148 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150 struct compiler_unit *u; /* compiler state for current block */
151 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000153 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000154};
155
156struct assembler {
157 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000158 int a_offset; /* offset into bytecode */
159 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160 basicblock **a_postorder; /* list of blocks in dfs postorder */
161 PyObject *a_lnotab; /* string containing lnotab */
162 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000163 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164 int a_lineno_off; /* bytecode offset of last lineno */
165};
166
167static int compiler_enter_scope(struct compiler *, identifier, void *, int);
168static void compiler_free(struct compiler *);
169static basicblock *compiler_new_block(struct compiler *);
170static int compiler_next_instr(struct compiler *, basicblock *);
171static int compiler_addop(struct compiler *, int);
172static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
173static int compiler_addop_i(struct compiler *, int, int);
174static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175static basicblock *compiler_use_new_block(struct compiler *);
176static int compiler_error(struct compiler *, const char *);
177static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
178
179static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
180static int compiler_visit_stmt(struct compiler *, stmt_ty);
181static int compiler_visit_keyword(struct compiler *, keyword_ty);
182static int compiler_visit_expr(struct compiler *, expr_ty);
183static int compiler_augassign(struct compiler *, stmt_ty);
184static int compiler_visit_slice(struct compiler *, slice_ty,
185 expr_context_ty);
186
187static int compiler_push_fblock(struct compiler *, enum fblocktype,
188 basicblock *);
189static void compiler_pop_fblock(struct compiler *, enum fblocktype,
190 basicblock *);
191
192static int inplace_binop(struct compiler *, operator_ty);
193static int expr_constant(expr_ty e);
194
Guido van Rossumc2e20742006-02-27 22:32:47 +0000195static int compiler_with(struct compiler *, stmt_ty);
196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197static PyCodeObject *assemble(struct compiler *, int addNone);
198static PyObject *__doc__;
199
200PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000201_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000202{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203 /* Name mangling: __private becomes _classname__private.
204 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 const char *p, *name = PyString_AsString(ident);
206 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000208 if (privateobj == NULL || !PyString_Check(privateobj) ||
209 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000212 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000213 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214 nlen = strlen(name);
215 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000216 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000217 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000219 /* Strip leading underscores from class name */
220 while (*p == '_')
221 p++;
222 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000225 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000227 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
228 if (!ident)
229 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000231 buffer = PyString_AS_STRING(ident);
232 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233 strncpy(buffer+1, p, plen);
234 strcpy(buffer+1+plen, name);
235 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000236}
237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000238static int
239compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000240{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000243 c->c_stack = PyList_New(0);
244 if (!c->c_stack)
245 return 0;
246
247 return 1;
248}
249
250PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000251PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000252 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253{
254 struct compiler c;
255 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000256 PyCompilerFlags local_flags;
257 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000258
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000259 if (!__doc__) {
260 __doc__ = PyString_InternFromString("__doc__");
261 if (!__doc__)
262 return NULL;
263 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264
265 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000266 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000268 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000269 c.c_future = PyFuture_FromAST(mod, filename);
270 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000271 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000273 local_flags.cf_flags = 0;
274 flags = &local_flags;
275 }
276 merged = c.c_future->ff_features | flags->cf_flags;
277 c.c_future->ff_features = merged;
278 flags->cf_flags = merged;
279 c.c_flags = flags;
280 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000281
282 c.c_st = PySymtable_Build(mod, filename, c.c_future);
283 if (c.c_st == NULL) {
284 if (!PyErr_Occurred())
285 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000286 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287 }
288
289 /* XXX initialize to NULL for now, need to handle */
290 c.c_encoding = NULL;
291
292 co = compiler_mod(&c, mod);
293
Thomas Wouters1175c432006-02-27 22:49:54 +0000294 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000296 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297 return co;
298}
299
300PyCodeObject *
301PyNode_Compile(struct _node *n, const char *filename)
302{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000303 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000304 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000305 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000306 if (!arena)
307 return NULL;
308 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000309 if (mod)
310 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000311 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000312 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000313}
314
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000315static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000317{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318 if (c->c_st)
319 PySymtable_Free(c->c_st);
320 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000321 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000323}
324
Guido van Rossum79f25d91997-04-29 20:08:16 +0000325static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000327{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000328 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000329 PyObject *v, *k;
330 PyObject *dict = PyDict_New();
331 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000332
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333 n = PyList_Size(list);
334 for (i = 0; i < n; i++) {
335 v = PyInt_FromLong(i);
336 if (!v) {
337 Py_DECREF(dict);
338 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000339 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000340 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000341 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
343 Py_XDECREF(k);
344 Py_DECREF(v);
345 Py_DECREF(dict);
346 return NULL;
347 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000348 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000350 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351 return dict;
352}
353
354/* Return new dict containing names from src that match scope(s).
355
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000356src is a symbol table dictionary. If the scope of a name matches
357either scope_type or flag is set, insert it into the new dict. The
358values are integers, starting at offset and increasing by one for
359each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360*/
361
362static PyObject *
363dictbytype(PyObject *src, int scope_type, int flag, int offset)
364{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000365 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000366 PyObject *k, *v, *dest = PyDict_New();
367
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 assert(offset >= 0);
369 if (dest == NULL)
370 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371
372 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 /* XXX this should probably be a macro in symtable.h */
374 assert(PyInt_Check(v));
375 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
378 PyObject *tuple, *item = PyInt_FromLong(i);
379 if (item == NULL) {
380 Py_DECREF(dest);
381 return NULL;
382 }
383 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000384 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000385 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
386 Py_DECREF(item);
387 Py_DECREF(dest);
388 Py_XDECREF(tuple);
389 return NULL;
390 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000391 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000392 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394 }
395 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000396}
397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398/*
399
400Leave this debugging code for just a little longer.
401
402static void
403compiler_display_symbols(PyObject *name, PyObject *symbols)
404{
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000405PyObject *key, *value;
406int flags;
407Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000408
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000409fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
410while (PyDict_Next(symbols, &pos, &key, &value)) {
411flags = PyInt_AsLong(value);
412fprintf(stderr, "var %s:", PyString_AS_STRING(key));
413if (flags & DEF_GLOBAL)
414fprintf(stderr, " declared_global");
415if (flags & DEF_LOCAL)
416fprintf(stderr, " local");
417if (flags & DEF_PARAM)
418fprintf(stderr, " param");
419if (flags & DEF_STAR)
420fprintf(stderr, " stararg");
421if (flags & DEF_DOUBLESTAR)
422fprintf(stderr, " starstar");
423if (flags & DEF_INTUPLE)
424fprintf(stderr, " tuple");
425if (flags & DEF_FREE)
426fprintf(stderr, " free");
427if (flags & DEF_FREE_GLOBAL)
428fprintf(stderr, " global");
429if (flags & DEF_FREE_CLASS)
430fprintf(stderr, " free/class");
431if (flags & DEF_IMPORT)
432fprintf(stderr, " import");
433fprintf(stderr, "\n");
434}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435 fprintf(stderr, "\n");
436}
437*/
438
439static void
440compiler_unit_check(struct compiler_unit *u)
441{
442 basicblock *block;
443 for (block = u->u_blocks; block != NULL; block = block->b_list) {
444 assert(block != (void *)0xcbcbcbcb);
445 assert(block != (void *)0xfbfbfbfb);
446 assert(block != (void *)0xdbdbdbdb);
447 if (block->b_instr != NULL) {
448 assert(block->b_ialloc > 0);
449 assert(block->b_iused > 0);
450 assert(block->b_ialloc >= block->b_iused);
451 }
452 else {
453 assert (block->b_iused == 0);
454 assert (block->b_ialloc == 0);
455 }
456 }
457}
458
459static void
460compiler_unit_free(struct compiler_unit *u)
461{
462 basicblock *b, *next;
463
464 compiler_unit_check(u);
465 b = u->u_blocks;
466 while (b != NULL) {
467 if (b->b_instr)
468 PyObject_Free((void *)b->b_instr);
469 next = b->b_list;
470 PyObject_Free((void *)b);
471 b = next;
472 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000473 Py_CLEAR(u->u_ste);
474 Py_CLEAR(u->u_name);
475 Py_CLEAR(u->u_consts);
476 Py_CLEAR(u->u_names);
477 Py_CLEAR(u->u_varnames);
478 Py_CLEAR(u->u_freevars);
479 Py_CLEAR(u->u_cellvars);
480 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481 PyObject_Free(u);
482}
483
484static int
485compiler_enter_scope(struct compiler *c, identifier name, void *key,
486 int lineno)
487{
488 struct compiler_unit *u;
489
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000490 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
491 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000492 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000493 PyErr_NoMemory();
494 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000495 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000496 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000498 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499 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);
Thomas Wouters0e3f5912006-08-11 14:57:12 +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));
Thomas Wouters0e3f5912006-08-11 14:57:12 +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);
Thomas Wouters0e3f5912006-08-11 14:57:12 +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);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +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));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +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;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000680 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000681 if (tmp == NULL) {
682 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000726 case UNARY_INVERT:
727 return 0;
728
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000729 case LIST_APPEND:
730 return -2;
731
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732 case BINARY_POWER:
733 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734 case BINARY_MODULO:
735 case BINARY_ADD:
736 case BINARY_SUBTRACT:
737 case BINARY_SUBSCR:
738 case BINARY_FLOOR_DIVIDE:
739 case BINARY_TRUE_DIVIDE:
740 return -1;
741 case INPLACE_FLOOR_DIVIDE:
742 case INPLACE_TRUE_DIVIDE:
743 return -1;
744
745 case SLICE+0:
746 return 1;
747 case SLICE+1:
748 return 0;
749 case SLICE+2:
750 return 0;
751 case SLICE+3:
752 return -1;
753
754 case STORE_SLICE+0:
755 return -2;
756 case STORE_SLICE+1:
757 return -3;
758 case STORE_SLICE+2:
759 return -3;
760 case STORE_SLICE+3:
761 return -4;
762
763 case DELETE_SLICE+0:
764 return -1;
765 case DELETE_SLICE+1:
766 return -2;
767 case DELETE_SLICE+2:
768 return -2;
769 case DELETE_SLICE+3:
770 return -3;
771
772 case INPLACE_ADD:
773 case INPLACE_SUBTRACT:
774 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775 case INPLACE_MODULO:
776 return -1;
777 case STORE_SUBSCR:
778 return -3;
779 case DELETE_SUBSCR:
780 return -2;
781
782 case BINARY_LSHIFT:
783 case BINARY_RSHIFT:
784 case BINARY_AND:
785 case BINARY_XOR:
786 case BINARY_OR:
787 return -1;
788 case INPLACE_POWER:
789 return -1;
790 case GET_ITER:
791 return 0;
792
793 case PRINT_EXPR:
794 return -1;
795 case PRINT_ITEM:
796 return -1;
797 case PRINT_NEWLINE:
798 return 0;
799 case PRINT_ITEM_TO:
800 return -2;
801 case PRINT_NEWLINE_TO:
802 return -1;
803 case INPLACE_LSHIFT:
804 case INPLACE_RSHIFT:
805 case INPLACE_AND:
806 case INPLACE_XOR:
807 case INPLACE_OR:
808 return -1;
809 case BREAK_LOOP:
810 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000811 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000812 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813 case LOAD_LOCALS:
814 return 1;
815 case RETURN_VALUE:
816 return -1;
817 case IMPORT_STAR:
818 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819 case YIELD_VALUE:
820 return 0;
821
822 case POP_BLOCK:
823 return 0;
824 case END_FINALLY:
825 return -1; /* or -2 or -3 if exception occurred */
826 case BUILD_CLASS:
827 return -2;
828
829 case STORE_NAME:
830 return -1;
831 case DELETE_NAME:
832 return 0;
833 case UNPACK_SEQUENCE:
834 return oparg-1;
835 case FOR_ITER:
836 return 1;
837
838 case STORE_ATTR:
839 return -2;
840 case DELETE_ATTR:
841 return -1;
842 case STORE_GLOBAL:
843 return -1;
844 case DELETE_GLOBAL:
845 return 0;
846 case DUP_TOPX:
847 return oparg;
848 case LOAD_CONST:
849 return 1;
850 case LOAD_NAME:
851 return 1;
852 case BUILD_TUPLE:
853 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000854 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855 return 1-oparg;
856 case BUILD_MAP:
857 return 1;
858 case LOAD_ATTR:
859 return 0;
860 case COMPARE_OP:
861 return -1;
862 case IMPORT_NAME:
863 return 0;
864 case IMPORT_FROM:
865 return 1;
866
867 case JUMP_FORWARD:
868 case JUMP_IF_FALSE:
869 case JUMP_IF_TRUE:
870 case JUMP_ABSOLUTE:
871 return 0;
872
873 case LOAD_GLOBAL:
874 return 1;
875
876 case CONTINUE_LOOP:
877 return 0;
878 case SETUP_LOOP:
879 return 0;
880 case SETUP_EXCEPT:
881 case SETUP_FINALLY:
882 return 3; /* actually pushed by an exception */
883
884 case LOAD_FAST:
885 return 1;
886 case STORE_FAST:
887 return -1;
888 case DELETE_FAST:
889 return 0;
890
891 case RAISE_VARARGS:
892 return -oparg;
893#define NARGS(o) (((o) % 256) + 2*((o) / 256))
894 case CALL_FUNCTION:
895 return -NARGS(oparg);
896 case CALL_FUNCTION_VAR:
897 case CALL_FUNCTION_KW:
898 return -NARGS(oparg)-1;
899 case CALL_FUNCTION_VAR_KW:
900 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000901 case MAKE_FUNCTION:
Guido van Rossum4f72a782006-10-27 23:31:49 +0000902 return -NARGS(oparg);
903#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000904 case BUILD_SLICE:
905 if (oparg == 3)
906 return -2;
907 else
908 return -1;
909
910 case MAKE_CLOSURE:
911 return -oparg;
912 case LOAD_CLOSURE:
913 return 1;
914 case LOAD_DEREF:
915 return 1;
916 case STORE_DEREF:
917 return -1;
918 default:
919 fprintf(stderr, "opcode = %d\n", opcode);
920 Py_FatalError("opcode_stack_effect()");
921
922 }
923 return 0; /* not reachable */
924}
925
926/* Add an opcode with no argument.
927 Returns 0 on failure, 1 on success.
928*/
929
930static int
931compiler_addop(struct compiler *c, int opcode)
932{
933 basicblock *b;
934 struct instr *i;
935 int off;
936 off = compiler_next_instr(c, c->u->u_curblock);
937 if (off < 0)
938 return 0;
939 b = c->u->u_curblock;
940 i = &b->b_instr[off];
941 i->i_opcode = opcode;
942 i->i_hasarg = 0;
943 if (opcode == RETURN_VALUE)
944 b->b_return = 1;
945 compiler_set_lineno(c, off);
946 return 1;
947}
948
949static int
950compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
951{
952 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000953 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000955 /* necessary to make sure types aren't coerced (e.g., int and long) */
956 t = PyTuple_Pack(2, o, o->ob_type);
957 if (t == NULL)
958 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
960 v = PyDict_GetItem(dict, t);
961 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000962 if (PyErr_Occurred())
963 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964 arg = PyDict_Size(dict);
965 v = PyInt_FromLong(arg);
966 if (!v) {
967 Py_DECREF(t);
968 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000969 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970 if (PyDict_SetItem(dict, t, v) < 0) {
971 Py_DECREF(t);
972 Py_DECREF(v);
973 return -1;
974 }
975 Py_DECREF(v);
976 }
977 else
978 arg = PyInt_AsLong(v);
979 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981}
982
983static int
984compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
985 PyObject *o)
986{
987 int arg = compiler_add_o(c, dict, o);
988 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000989 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990 return compiler_addop_i(c, opcode, arg);
991}
992
993static int
994compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000995 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000996{
997 int arg;
998 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
999 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001 arg = compiler_add_o(c, dict, mangled);
1002 Py_DECREF(mangled);
1003 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005 return compiler_addop_i(c, opcode, arg);
1006}
1007
1008/* Add an opcode with an integer argument.
1009 Returns 0 on failure, 1 on success.
1010*/
1011
1012static int
1013compiler_addop_i(struct compiler *c, int opcode, int oparg)
1014{
1015 struct instr *i;
1016 int off;
1017 off = compiler_next_instr(c, c->u->u_curblock);
1018 if (off < 0)
1019 return 0;
1020 i = &c->u->u_curblock->b_instr[off];
1021 i->i_opcode = opcode;
1022 i->i_oparg = oparg;
1023 i->i_hasarg = 1;
1024 compiler_set_lineno(c, off);
1025 return 1;
1026}
1027
1028static int
1029compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1030{
1031 struct instr *i;
1032 int off;
1033
1034 assert(b != NULL);
1035 off = compiler_next_instr(c, c->u->u_curblock);
1036 if (off < 0)
1037 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038 i = &c->u->u_curblock->b_instr[off];
1039 i->i_opcode = opcode;
1040 i->i_target = b;
1041 i->i_hasarg = 1;
1042 if (absolute)
1043 i->i_jabs = 1;
1044 else
1045 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001046 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047 return 1;
1048}
1049
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001050/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1051 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052 it as the current block. NEXT_BLOCK() also creates an implicit jump
1053 from the current block to the new block.
1054*/
1055
1056/* XXX The returns inside these macros make it impossible to decref
1057 objects created in the local function.
1058*/
1059
1060
1061#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001062 if (compiler_use_new_block((C)) == NULL) \
1063 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064}
1065
1066#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001067 if (compiler_next_block((C)) == NULL) \
1068 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069}
1070
1071#define ADDOP(C, OP) { \
1072 if (!compiler_addop((C), (OP))) \
1073 return 0; \
1074}
1075
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001076#define ADDOP_IN_SCOPE(C, OP) { \
1077 if (!compiler_addop((C), (OP))) { \
1078 compiler_exit_scope(c); \
1079 return 0; \
1080 } \
1081}
1082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083#define ADDOP_O(C, OP, O, TYPE) { \
1084 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1085 return 0; \
1086}
1087
1088#define ADDOP_NAME(C, OP, O, TYPE) { \
1089 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1090 return 0; \
1091}
1092
1093#define ADDOP_I(C, OP, O) { \
1094 if (!compiler_addop_i((C), (OP), (O))) \
1095 return 0; \
1096}
1097
1098#define ADDOP_JABS(C, OP, O) { \
1099 if (!compiler_addop_j((C), (OP), (O), 1)) \
1100 return 0; \
1101}
1102
1103#define ADDOP_JREL(C, OP, O) { \
1104 if (!compiler_addop_j((C), (OP), (O), 0)) \
1105 return 0; \
1106}
1107
1108/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1109 the ASDL name to synthesize the name of the C type and the visit function.
1110*/
1111
1112#define VISIT(C, TYPE, V) {\
1113 if (!compiler_visit_ ## TYPE((C), (V))) \
1114 return 0; \
1115}
1116
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001117#define VISIT_IN_SCOPE(C, TYPE, V) {\
1118 if (!compiler_visit_ ## TYPE((C), (V))) { \
1119 compiler_exit_scope(c); \
1120 return 0; \
1121 } \
1122}
1123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124#define VISIT_SLICE(C, V, CTX) {\
1125 if (!compiler_visit_slice((C), (V), (CTX))) \
1126 return 0; \
1127}
1128
1129#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001133 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134 if (!compiler_visit_ ## TYPE((C), elt)) \
1135 return 0; \
1136 } \
1137}
1138
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001141 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001144 if (!compiler_visit_ ## TYPE((C), elt)) { \
1145 compiler_exit_scope(c); \
1146 return 0; \
1147 } \
1148 } \
1149}
1150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151static int
1152compiler_isdocstring(stmt_ty s)
1153{
1154 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return s->v.Expr.value->kind == Str_kind;
1157}
1158
1159/* Compile a sequence of statements, checking for a docstring. */
1160
1161static int
1162compiler_body(struct compiler *c, asdl_seq *stmts)
1163{
1164 int i = 0;
1165 stmt_ty st;
1166
1167 if (!asdl_seq_LEN(stmts))
1168 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001169 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 if (compiler_isdocstring(st)) {
1171 i = 1;
1172 VISIT(c, expr, st->v.Expr.value);
1173 if (!compiler_nameop(c, __doc__, Store))
1174 return 0;
1175 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001176 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001177 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 return 1;
1179}
1180
1181static PyCodeObject *
1182compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001183{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001184 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001185 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 static PyObject *module;
1187 if (!module) {
1188 module = PyString_FromString("<module>");
1189 if (!module)
1190 return NULL;
1191 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001192 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1193 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001194 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 switch (mod->kind) {
1196 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001197 if (!compiler_body(c, mod->v.Module.body)) {
1198 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 break;
1202 case Interactive_kind:
1203 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001204 VISIT_SEQ_IN_SCOPE(c, stmt,
1205 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 break;
1207 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001208 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 break;
1211 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001212 PyErr_SetString(PyExc_SystemError,
1213 "suite should not be possible");
1214 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001215 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001216 PyErr_Format(PyExc_SystemError,
1217 "module kind %d should not be possible",
1218 mod->kind);
1219 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 co = assemble(c, addNone);
1222 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001223 return co;
1224}
1225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226/* The test for LOCAL must come before the test for FREE in order to
1227 handle classes where name is both local and free. The local var is
1228 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001229*/
1230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231static int
1232get_ref_type(struct compiler *c, PyObject *name)
1233{
1234 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001235 if (scope == 0) {
1236 char buf[350];
1237 PyOS_snprintf(buf, sizeof(buf),
1238 "unknown scope for %.100s in %.100s(%s) in %s\n"
1239 "symbols: %s\nlocals: %s\nglobals: %s\n",
1240 PyString_AS_STRING(name),
1241 PyString_AS_STRING(c->u->u_name),
1242 PyObject_REPR(c->u->u_ste->ste_id),
1243 c->c_filename,
1244 PyObject_REPR(c->u->u_ste->ste_symbols),
1245 PyObject_REPR(c->u->u_varnames),
1246 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001248 Py_FatalError(buf);
1249 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254static int
1255compiler_lookup_arg(PyObject *dict, PyObject *name)
1256{
1257 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001260 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001262 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001264 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 return PyInt_AS_LONG(v);
1266}
1267
1268static int
1269compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1270{
1271 int i, free = PyCode_GetNumFree(co);
1272 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001273 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1274 ADDOP_I(c, MAKE_FUNCTION, args);
1275 return 1;
1276 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 for (i = 0; i < free; ++i) {
1278 /* Bypass com_addop_varname because it will generate
1279 LOAD_DEREF but LOAD_CLOSURE is needed.
1280 */
1281 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1282 int arg, reftype;
1283
1284 /* Special case: If a class contains a method with a
1285 free variable that has the same name as a method,
1286 the name will be considered free *and* local in the
1287 class. It should be handled by the closure, as
1288 well as by the normal name loookup logic.
1289 */
1290 reftype = get_ref_type(c, name);
1291 if (reftype == CELL)
1292 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1293 else /* (reftype == FREE) */
1294 arg = compiler_lookup_arg(c->u->u_freevars, name);
1295 if (arg == -1) {
1296 printf("lookup %s in %s %d %d\n"
1297 "freevars of %s: %s\n",
1298 PyObject_REPR(name),
1299 PyString_AS_STRING(c->u->u_name),
1300 reftype, arg,
1301 PyString_AS_STRING(co->co_name),
1302 PyObject_REPR(co->co_freevars));
1303 Py_FatalError("compiler_make_closure()");
1304 }
1305 ADDOP_I(c, LOAD_CLOSURE, arg);
1306 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001309 ADDOP_I(c, MAKE_CLOSURE, args);
1310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
1314compiler_decorators(struct compiler *c, asdl_seq* decos)
1315{
1316 int i;
1317
1318 if (!decos)
1319 return 1;
1320
1321 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 }
1324 return 1;
1325}
1326
1327static int
1328compiler_arguments(struct compiler *c, arguments_ty args)
1329{
1330 int i;
1331 int n = asdl_seq_LEN(args->args);
1332 /* Correctly handle nested argument lists */
1333 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001334 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 if (arg->kind == Tuple_kind) {
1336 PyObject *id = PyString_FromFormat(".%d", i);
1337 if (id == NULL) {
1338 return 0;
1339 }
1340 if (!compiler_nameop(c, id, Load)) {
1341 Py_DECREF(id);
1342 return 0;
1343 }
1344 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001345 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 }
1347 }
1348 return 1;
1349}
1350
1351static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001352compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1353 asdl_seq *kw_defaults)
1354{
1355 int i, default_count = 0;
1356 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1357 expr_ty arg = asdl_seq_GET(kwonlyargs, i);
1358 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1359 if (default_) {
1360 ADDOP_O(c, LOAD_CONST, arg->v.Name.id, consts);
1361 if (!compiler_visit_expr(c, default_)) {
1362 return -1;
1363 }
1364 default_count++;
1365 }
1366 }
1367 return default_count;
1368}
1369
1370static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371compiler_function(struct compiler *c, stmt_ty s)
1372{
1373 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001374 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375 arguments_ty args = s->v.FunctionDef.args;
1376 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001377 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001378 int i, n, docstring, kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379
1380 assert(s->kind == FunctionDef_kind);
1381
1382 if (!compiler_decorators(c, decos))
1383 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001384 if (args->kwonlyargs) {
1385 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1386 args->kw_defaults);
1387 if (res < 0)
1388 return 0;
1389 kw_default_count = res;
1390 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 if (args->defaults)
1392 VISIT_SEQ(c, expr, args->defaults);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1395 s->lineno))
1396 return 0;
1397
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001398 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001399 docstring = compiler_isdocstring(st);
1400 if (docstring)
1401 first_const = st->v.Expr.value->v.Str.s;
1402 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001403 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001404 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001405 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001407 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408 compiler_arguments(c, args);
1409
1410 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001411 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001412 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001413 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001415 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1416 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417 }
1418 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001419 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420 if (co == NULL)
1421 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422
Guido van Rossum4f72a782006-10-27 23:31:49 +00001423 arglength = asdl_seq_LEN(args->defaults);
1424 arglength |= kw_default_count << 8;
1425 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001426 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427
1428 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1429 ADDOP_I(c, CALL_FUNCTION, 1);
1430 }
1431
1432 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1433}
1434
1435static int
1436compiler_class(struct compiler *c, stmt_ty s)
1437{
1438 int n;
1439 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001440 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441 /* push class name on stack, needed by BUILD_CLASS */
1442 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1443 /* push the tuple of base classes on the stack */
1444 n = asdl_seq_LEN(s->v.ClassDef.bases);
1445 if (n > 0)
1446 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1447 ADDOP_I(c, BUILD_TUPLE, n);
1448 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1449 s->lineno))
1450 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001451 c->u->u_private = s->v.ClassDef.name;
1452 Py_INCREF(c->u->u_private);
1453 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 if (!str || !compiler_nameop(c, str, Load)) {
1455 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001456 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001458 }
1459
1460 Py_DECREF(str);
1461 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462 if (!str || !compiler_nameop(c, str, Store)) {
1463 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001464 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001466 }
1467 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001469 if (!compiler_body(c, s->v.ClassDef.body)) {
1470 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001474 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1475 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001477 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478 if (co == NULL)
1479 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001482 Py_DECREF(co);
1483
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484 ADDOP_I(c, CALL_FUNCTION, 0);
1485 ADDOP(c, BUILD_CLASS);
1486 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1487 return 0;
1488 return 1;
1489}
1490
1491static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001492compiler_ifexp(struct compiler *c, expr_ty e)
1493{
1494 basicblock *end, *next;
1495
1496 assert(e->kind == IfExp_kind);
1497 end = compiler_new_block(c);
1498 if (end == NULL)
1499 return 0;
1500 next = compiler_new_block(c);
1501 if (next == NULL)
1502 return 0;
1503 VISIT(c, expr, e->v.IfExp.test);
1504 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1505 ADDOP(c, POP_TOP);
1506 VISIT(c, expr, e->v.IfExp.body);
1507 ADDOP_JREL(c, JUMP_FORWARD, end);
1508 compiler_use_next_block(c, next);
1509 ADDOP(c, POP_TOP);
1510 VISIT(c, expr, e->v.IfExp.orelse);
1511 compiler_use_next_block(c, end);
1512 return 1;
1513}
1514
1515static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516compiler_lambda(struct compiler *c, expr_ty e)
1517{
1518 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001519 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001520 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521 arguments_ty args = e->v.Lambda.args;
1522 assert(e->kind == Lambda_kind);
1523
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001524 if (!name) {
1525 name = PyString_InternFromString("<lambda>");
1526 if (!name)
1527 return 0;
1528 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529
Guido van Rossum4f72a782006-10-27 23:31:49 +00001530 if (args->kwonlyargs) {
1531 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1532 args->kw_defaults);
1533 if (res < 0) return 0;
1534 kw_default_count = res;
1535 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536 if (args->defaults)
1537 VISIT_SEQ(c, expr, args->defaults);
1538 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1539 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001540
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001541 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542 compiler_arguments(c, args);
1543
1544 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001545 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1547 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001549 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550 if (co == NULL)
1551 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552
Guido van Rossum4f72a782006-10-27 23:31:49 +00001553 arglength = asdl_seq_LEN(args->defaults);
1554 arglength |= kw_default_count << 8;
1555 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001556 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557
1558 return 1;
1559}
1560
1561static int
1562compiler_print(struct compiler *c, stmt_ty s)
1563{
1564 int i, n;
1565 bool dest;
1566
1567 assert(s->kind == Print_kind);
1568 n = asdl_seq_LEN(s->v.Print.values);
1569 dest = false;
1570 if (s->v.Print.dest) {
1571 VISIT(c, expr, s->v.Print.dest);
1572 dest = true;
1573 }
1574 for (i = 0; i < n; i++) {
1575 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1576 if (dest) {
1577 ADDOP(c, DUP_TOP);
1578 VISIT(c, expr, e);
1579 ADDOP(c, ROT_TWO);
1580 ADDOP(c, PRINT_ITEM_TO);
1581 }
1582 else {
1583 VISIT(c, expr, e);
1584 ADDOP(c, PRINT_ITEM);
1585 }
1586 }
1587 if (s->v.Print.nl) {
1588 if (dest)
1589 ADDOP(c, PRINT_NEWLINE_TO)
1590 else
1591 ADDOP(c, PRINT_NEWLINE)
1592 }
1593 else if (dest)
1594 ADDOP(c, POP_TOP);
1595 return 1;
1596}
1597
1598static int
1599compiler_if(struct compiler *c, stmt_ty s)
1600{
1601 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001602 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603 assert(s->kind == If_kind);
1604 end = compiler_new_block(c);
1605 if (end == NULL)
1606 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001607 next = compiler_new_block(c);
1608 if (next == NULL)
1609 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001610
1611 constant = expr_constant(s->v.If.test);
1612 /* constant = 0: "if 0"
1613 * constant = 1: "if 1", "if 2", ...
1614 * constant = -1: rest */
1615 if (constant == 0) {
1616 if (s->v.If.orelse)
1617 VISIT_SEQ(c, stmt, s->v.If.orelse);
1618 } else if (constant == 1) {
1619 VISIT_SEQ(c, stmt, s->v.If.body);
1620 } else {
1621 VISIT(c, expr, s->v.If.test);
1622 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1623 ADDOP(c, POP_TOP);
1624 VISIT_SEQ(c, stmt, s->v.If.body);
1625 ADDOP_JREL(c, JUMP_FORWARD, end);
1626 compiler_use_next_block(c, next);
1627 ADDOP(c, POP_TOP);
1628 if (s->v.If.orelse)
1629 VISIT_SEQ(c, stmt, s->v.If.orelse);
1630 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631 compiler_use_next_block(c, end);
1632 return 1;
1633}
1634
1635static int
1636compiler_for(struct compiler *c, stmt_ty s)
1637{
1638 basicblock *start, *cleanup, *end;
1639
1640 start = compiler_new_block(c);
1641 cleanup = compiler_new_block(c);
1642 end = compiler_new_block(c);
1643 if (start == NULL || end == NULL || cleanup == NULL)
1644 return 0;
1645 ADDOP_JREL(c, SETUP_LOOP, end);
1646 if (!compiler_push_fblock(c, LOOP, start))
1647 return 0;
1648 VISIT(c, expr, s->v.For.iter);
1649 ADDOP(c, GET_ITER);
1650 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001651 /* XXX(nnorwitz): is there a better way to handle this?
1652 for loops are special, we want to be able to trace them
1653 each time around, so we need to set an extra line number. */
1654 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655 ADDOP_JREL(c, FOR_ITER, cleanup);
1656 VISIT(c, expr, s->v.For.target);
1657 VISIT_SEQ(c, stmt, s->v.For.body);
1658 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1659 compiler_use_next_block(c, cleanup);
1660 ADDOP(c, POP_BLOCK);
1661 compiler_pop_fblock(c, LOOP, start);
1662 VISIT_SEQ(c, stmt, s->v.For.orelse);
1663 compiler_use_next_block(c, end);
1664 return 1;
1665}
1666
1667static int
1668compiler_while(struct compiler *c, stmt_ty s)
1669{
1670 basicblock *loop, *orelse, *end, *anchor = NULL;
1671 int constant = expr_constant(s->v.While.test);
1672
1673 if (constant == 0)
1674 return 1;
1675 loop = compiler_new_block(c);
1676 end = compiler_new_block(c);
1677 if (constant == -1) {
1678 anchor = compiler_new_block(c);
1679 if (anchor == NULL)
1680 return 0;
1681 }
1682 if (loop == NULL || end == NULL)
1683 return 0;
1684 if (s->v.While.orelse) {
1685 orelse = compiler_new_block(c);
1686 if (orelse == NULL)
1687 return 0;
1688 }
1689 else
1690 orelse = NULL;
1691
1692 ADDOP_JREL(c, SETUP_LOOP, end);
1693 compiler_use_next_block(c, loop);
1694 if (!compiler_push_fblock(c, LOOP, loop))
1695 return 0;
1696 if (constant == -1) {
1697 VISIT(c, expr, s->v.While.test);
1698 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1699 ADDOP(c, POP_TOP);
1700 }
1701 VISIT_SEQ(c, stmt, s->v.While.body);
1702 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1703
1704 /* XXX should the two POP instructions be in a separate block
1705 if there is no else clause ?
1706 */
1707
1708 if (constant == -1) {
1709 compiler_use_next_block(c, anchor);
1710 ADDOP(c, POP_TOP);
1711 ADDOP(c, POP_BLOCK);
1712 }
1713 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001714 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715 VISIT_SEQ(c, stmt, s->v.While.orelse);
1716 compiler_use_next_block(c, end);
1717
1718 return 1;
1719}
1720
1721static int
1722compiler_continue(struct compiler *c)
1723{
1724 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1725 int i;
1726
1727 if (!c->u->u_nfblocks)
1728 return compiler_error(c, LOOP_ERROR_MSG);
1729 i = c->u->u_nfblocks - 1;
1730 switch (c->u->u_fblock[i].fb_type) {
1731 case LOOP:
1732 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1733 break;
1734 case EXCEPT:
1735 case FINALLY_TRY:
1736 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1737 ;
1738 if (i == -1)
1739 return compiler_error(c, LOOP_ERROR_MSG);
1740 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1741 break;
1742 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001743 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001744 "'continue' not supported inside 'finally' clause");
1745 }
1746
1747 return 1;
1748}
1749
1750/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1751
1752 SETUP_FINALLY L
1753 <code for body>
1754 POP_BLOCK
1755 LOAD_CONST <None>
1756 L: <code for finalbody>
1757 END_FINALLY
1758
1759 The special instructions use the block stack. Each block
1760 stack entry contains the instruction that created it (here
1761 SETUP_FINALLY), the level of the value stack at the time the
1762 block stack entry was created, and a label (here L).
1763
1764 SETUP_FINALLY:
1765 Pushes the current value stack level and the label
1766 onto the block stack.
1767 POP_BLOCK:
1768 Pops en entry from the block stack, and pops the value
1769 stack until its level is the same as indicated on the
1770 block stack. (The label is ignored.)
1771 END_FINALLY:
1772 Pops a variable number of entries from the *value* stack
1773 and re-raises the exception they specify. The number of
1774 entries popped depends on the (pseudo) exception type.
1775
1776 The block stack is unwound when an exception is raised:
1777 when a SETUP_FINALLY entry is found, the exception is pushed
1778 onto the value stack (and the exception condition is cleared),
1779 and the interpreter jumps to the label gotten from the block
1780 stack.
1781*/
1782
1783static int
1784compiler_try_finally(struct compiler *c, stmt_ty s)
1785{
1786 basicblock *body, *end;
1787 body = compiler_new_block(c);
1788 end = compiler_new_block(c);
1789 if (body == NULL || end == NULL)
1790 return 0;
1791
1792 ADDOP_JREL(c, SETUP_FINALLY, end);
1793 compiler_use_next_block(c, body);
1794 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1795 return 0;
1796 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1797 ADDOP(c, POP_BLOCK);
1798 compiler_pop_fblock(c, FINALLY_TRY, body);
1799
1800 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1801 compiler_use_next_block(c, end);
1802 if (!compiler_push_fblock(c, FINALLY_END, end))
1803 return 0;
1804 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1805 ADDOP(c, END_FINALLY);
1806 compiler_pop_fblock(c, FINALLY_END, end);
1807
1808 return 1;
1809}
1810
1811/*
1812 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1813 (The contents of the value stack is shown in [], with the top
1814 at the right; 'tb' is trace-back info, 'val' the exception's
1815 associated value, and 'exc' the exception.)
1816
1817 Value stack Label Instruction Argument
1818 [] SETUP_EXCEPT L1
1819 [] <code for S>
1820 [] POP_BLOCK
1821 [] JUMP_FORWARD L0
1822
1823 [tb, val, exc] L1: DUP )
1824 [tb, val, exc, exc] <evaluate E1> )
1825 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1826 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1827 [tb, val, exc, 1] POP )
1828 [tb, val, exc] POP
1829 [tb, val] <assign to V1> (or POP if no V1)
1830 [tb] POP
1831 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001832 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833
1834 [tb, val, exc, 0] L2: POP
1835 [tb, val, exc] DUP
1836 .............................etc.......................
1837
1838 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001839 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840
1841 [] L0: <next statement>
1842
1843 Of course, parts are not generated if Vi or Ei is not present.
1844*/
1845static int
1846compiler_try_except(struct compiler *c, stmt_ty s)
1847{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001848 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849 int i, n;
1850
1851 body = compiler_new_block(c);
1852 except = compiler_new_block(c);
1853 orelse = compiler_new_block(c);
1854 end = compiler_new_block(c);
1855 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1856 return 0;
1857 ADDOP_JREL(c, SETUP_EXCEPT, except);
1858 compiler_use_next_block(c, body);
1859 if (!compiler_push_fblock(c, EXCEPT, body))
1860 return 0;
1861 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1862 ADDOP(c, POP_BLOCK);
1863 compiler_pop_fblock(c, EXCEPT, body);
1864 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1865 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1866 compiler_use_next_block(c, except);
1867 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001868 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 s->v.TryExcept.handlers, i);
1870 if (!handler->type && i < n-1)
1871 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001872 c->u->u_lineno_set = false;
1873 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874 except = compiler_new_block(c);
1875 if (except == NULL)
1876 return 0;
1877 if (handler->type) {
1878 ADDOP(c, DUP_TOP);
1879 VISIT(c, expr, handler->type);
1880 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1881 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1882 ADDOP(c, POP_TOP);
1883 }
1884 ADDOP(c, POP_TOP);
1885 if (handler->name) {
1886 VISIT(c, expr, handler->name);
1887 }
1888 else {
1889 ADDOP(c, POP_TOP);
1890 }
1891 ADDOP(c, POP_TOP);
1892 VISIT_SEQ(c, stmt, handler->body);
1893 ADDOP_JREL(c, JUMP_FORWARD, end);
1894 compiler_use_next_block(c, except);
1895 if (handler->type)
1896 ADDOP(c, POP_TOP);
1897 }
1898 ADDOP(c, END_FINALLY);
1899 compiler_use_next_block(c, orelse);
1900 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1901 compiler_use_next_block(c, end);
1902 return 1;
1903}
1904
1905static int
1906compiler_import_as(struct compiler *c, identifier name, identifier asname)
1907{
1908 /* The IMPORT_NAME opcode was already generated. This function
1909 merely needs to bind the result to a name.
1910
1911 If there is a dot in name, we need to split it and emit a
1912 LOAD_ATTR for each name.
1913 */
1914 const char *src = PyString_AS_STRING(name);
1915 const char *dot = strchr(src, '.');
1916 if (dot) {
1917 /* Consume the base module name to get the first attribute */
1918 src = dot + 1;
1919 while (dot) {
1920 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001921 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001923 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001925 if (!attr)
1926 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001928 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929 src = dot + 1;
1930 }
1931 }
1932 return compiler_nameop(c, asname, Store);
1933}
1934
1935static int
1936compiler_import(struct compiler *c, stmt_ty s)
1937{
1938 /* The Import node stores a module name like a.b.c as a single
1939 string. This is convenient for all cases except
1940 import a.b.c as d
1941 where we need to parse that string to extract the individual
1942 module names.
1943 XXX Perhaps change the representation to make this case simpler?
1944 */
1945 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001946
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001947 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001948 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001950 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951
Guido van Rossum45aecf42006-03-15 04:58:47 +00001952 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001953 if (level == NULL)
1954 return 0;
1955
1956 ADDOP_O(c, LOAD_CONST, level, consts);
1957 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1959 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1960
1961 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001962 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001963 if (!r)
1964 return r;
1965 }
1966 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 identifier tmp = alias->name;
1968 const char *base = PyString_AS_STRING(alias->name);
1969 char *dot = strchr(base, '.');
1970 if (dot)
1971 tmp = PyString_FromStringAndSize(base,
1972 dot - base);
1973 r = compiler_nameop(c, tmp, Store);
1974 if (dot) {
1975 Py_DECREF(tmp);
1976 }
1977 if (!r)
1978 return r;
1979 }
1980 }
1981 return 1;
1982}
1983
1984static int
1985compiler_from_import(struct compiler *c, stmt_ty s)
1986{
1987 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988
1989 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001990 PyObject *level;
1991
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 if (!names)
1993 return 0;
1994
Guido van Rossum45aecf42006-03-15 04:58:47 +00001995 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001996 if (!level) {
1997 Py_DECREF(names);
1998 return 0;
1999 }
2000
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 /* build up the names */
2002 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002003 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 Py_INCREF(alias->name);
2005 PyTuple_SET_ITEM(names, i, alias->name);
2006 }
2007
2008 if (s->lineno > c->c_future->ff_lineno) {
2009 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2010 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002011 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012 Py_DECREF(names);
2013 return compiler_error(c,
2014 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002015 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
2017 }
2018 }
2019
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002020 ADDOP_O(c, LOAD_CONST, level, consts);
2021 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002023 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2025 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002026 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 identifier store_name;
2028
2029 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2030 assert(n == 1);
2031 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 }
2034
2035 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2036 store_name = alias->name;
2037 if (alias->asname)
2038 store_name = alias->asname;
2039
2040 if (!compiler_nameop(c, store_name, Store)) {
2041 Py_DECREF(names);
2042 return 0;
2043 }
2044 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002045 /* remove imported module */
2046 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 return 1;
2048}
2049
2050static int
2051compiler_assert(struct compiler *c, stmt_ty s)
2052{
2053 static PyObject *assertion_error = NULL;
2054 basicblock *end;
2055
2056 if (Py_OptimizeFlag)
2057 return 1;
2058 if (assertion_error == NULL) {
2059 assertion_error = PyString_FromString("AssertionError");
2060 if (assertion_error == NULL)
2061 return 0;
2062 }
2063 VISIT(c, expr, s->v.Assert.test);
2064 end = compiler_new_block(c);
2065 if (end == NULL)
2066 return 0;
2067 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2068 ADDOP(c, POP_TOP);
2069 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2070 if (s->v.Assert.msg) {
2071 VISIT(c, expr, s->v.Assert.msg);
2072 ADDOP_I(c, RAISE_VARARGS, 2);
2073 }
2074 else {
2075 ADDOP_I(c, RAISE_VARARGS, 1);
2076 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002077 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 ADDOP(c, POP_TOP);
2079 return 1;
2080}
2081
2082static int
2083compiler_visit_stmt(struct compiler *c, stmt_ty s)
2084{
2085 int i, n;
2086
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002087 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 c->u->u_lineno = s->lineno;
2089 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002090
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002092 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002094 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002096 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 if (c->u->u_ste->ste_type != FunctionBlock)
2098 return compiler_error(c, "'return' outside function");
2099 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 VISIT(c, expr, s->v.Return.value);
2101 }
2102 else
2103 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2104 ADDOP(c, RETURN_VALUE);
2105 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002106 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 VISIT_SEQ(c, expr, s->v.Delete.targets)
2108 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 n = asdl_seq_LEN(s->v.Assign.targets);
2111 VISIT(c, expr, s->v.Assign.value);
2112 for (i = 0; i < n; i++) {
2113 if (i < n - 1)
2114 ADDOP(c, DUP_TOP);
2115 VISIT(c, expr,
2116 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2117 }
2118 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002119 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002121 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002123 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002125 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130 n = 0;
2131 if (s->v.Raise.type) {
2132 VISIT(c, expr, s->v.Raise.type);
2133 n++;
2134 if (s->v.Raise.inst) {
2135 VISIT(c, expr, s->v.Raise.inst);
2136 n++;
2137 if (s->v.Raise.tback) {
2138 VISIT(c, expr, s->v.Raise.tback);
2139 n++;
2140 }
2141 }
2142 }
2143 ADDOP_I(c, RAISE_VARARGS, n);
2144 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002145 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002147 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002149 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002151 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002153 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002155 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002156 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002157 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002159 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160 ADDOP(c, PRINT_EXPR);
2161 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002162 else if (s->v.Expr.value->kind != Str_kind &&
2163 s->v.Expr.value->kind != Num_kind) {
2164 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165 ADDOP(c, POP_TOP);
2166 }
2167 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002168 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002170 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002171 if (!c->u->u_nfblocks)
2172 return compiler_error(c, "'break' outside loop");
2173 ADDOP(c, BREAK_LOOP);
2174 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002175 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002177 case With_kind:
2178 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179 }
2180 return 1;
2181}
2182
2183static int
2184unaryop(unaryop_ty op)
2185{
2186 switch (op) {
2187 case Invert:
2188 return UNARY_INVERT;
2189 case Not:
2190 return UNARY_NOT;
2191 case UAdd:
2192 return UNARY_POSITIVE;
2193 case USub:
2194 return UNARY_NEGATIVE;
2195 }
2196 return 0;
2197}
2198
2199static int
2200binop(struct compiler *c, operator_ty op)
2201{
2202 switch (op) {
2203 case Add:
2204 return BINARY_ADD;
2205 case Sub:
2206 return BINARY_SUBTRACT;
2207 case Mult:
2208 return BINARY_MULTIPLY;
2209 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002210 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211 case Mod:
2212 return BINARY_MODULO;
2213 case Pow:
2214 return BINARY_POWER;
2215 case LShift:
2216 return BINARY_LSHIFT;
2217 case RShift:
2218 return BINARY_RSHIFT;
2219 case BitOr:
2220 return BINARY_OR;
2221 case BitXor:
2222 return BINARY_XOR;
2223 case BitAnd:
2224 return BINARY_AND;
2225 case FloorDiv:
2226 return BINARY_FLOOR_DIVIDE;
2227 }
2228 return 0;
2229}
2230
2231static int
2232cmpop(cmpop_ty op)
2233{
2234 switch (op) {
2235 case Eq:
2236 return PyCmp_EQ;
2237 case NotEq:
2238 return PyCmp_NE;
2239 case Lt:
2240 return PyCmp_LT;
2241 case LtE:
2242 return PyCmp_LE;
2243 case Gt:
2244 return PyCmp_GT;
2245 case GtE:
2246 return PyCmp_GE;
2247 case Is:
2248 return PyCmp_IS;
2249 case IsNot:
2250 return PyCmp_IS_NOT;
2251 case In:
2252 return PyCmp_IN;
2253 case NotIn:
2254 return PyCmp_NOT_IN;
2255 }
2256 return PyCmp_BAD;
2257}
2258
2259static int
2260inplace_binop(struct compiler *c, operator_ty op)
2261{
2262 switch (op) {
2263 case Add:
2264 return INPLACE_ADD;
2265 case Sub:
2266 return INPLACE_SUBTRACT;
2267 case Mult:
2268 return INPLACE_MULTIPLY;
2269 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002270 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271 case Mod:
2272 return INPLACE_MODULO;
2273 case Pow:
2274 return INPLACE_POWER;
2275 case LShift:
2276 return INPLACE_LSHIFT;
2277 case RShift:
2278 return INPLACE_RSHIFT;
2279 case BitOr:
2280 return INPLACE_OR;
2281 case BitXor:
2282 return INPLACE_XOR;
2283 case BitAnd:
2284 return INPLACE_AND;
2285 case FloorDiv:
2286 return INPLACE_FLOOR_DIVIDE;
2287 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002288 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002289 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 return 0;
2291}
2292
2293static int
2294compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2295{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002296 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2298
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002299 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002300 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301 /* XXX AugStore isn't used anywhere! */
2302
2303 /* First check for assignment to __debug__. Param? */
2304 if ((ctx == Store || ctx == AugStore || ctx == Del)
2305 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2306 return compiler_error(c, "can not assign to __debug__");
2307 }
2308
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002309 mangled = _Py_Mangle(c->u->u_private, name);
2310 if (!mangled)
2311 return 0;
2312
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 op = 0;
2314 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002315 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 switch (scope) {
2317 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002318 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319 optype = OP_DEREF;
2320 break;
2321 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002322 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 optype = OP_DEREF;
2324 break;
2325 case LOCAL:
2326 if (c->u->u_ste->ste_type == FunctionBlock)
2327 optype = OP_FAST;
2328 break;
2329 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002330 if (c->u->u_ste->ste_type == FunctionBlock &&
2331 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332 optype = OP_GLOBAL;
2333 break;
2334 case GLOBAL_EXPLICIT:
2335 optype = OP_GLOBAL;
2336 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002337 default:
2338 /* scope can be 0 */
2339 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340 }
2341
2342 /* XXX Leave assert here, but handle __doc__ and the like better */
2343 assert(scope || PyString_AS_STRING(name)[0] == '_');
2344
2345 switch (optype) {
2346 case OP_DEREF:
2347 switch (ctx) {
2348 case Load: op = LOAD_DEREF; break;
2349 case Store: op = STORE_DEREF; break;
2350 case AugLoad:
2351 case AugStore:
2352 break;
2353 case Del:
2354 PyErr_Format(PyExc_SyntaxError,
2355 "can not delete variable '%s' referenced "
2356 "in nested scope",
2357 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002358 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002361 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002362 PyErr_SetString(PyExc_SystemError,
2363 "param invalid for deref variable");
2364 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365 }
2366 break;
2367 case OP_FAST:
2368 switch (ctx) {
2369 case Load: op = LOAD_FAST; break;
2370 case Store: op = STORE_FAST; break;
2371 case Del: op = DELETE_FAST; break;
2372 case AugLoad:
2373 case AugStore:
2374 break;
2375 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002376 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002377 PyErr_SetString(PyExc_SystemError,
2378 "param invalid for local variable");
2379 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002381 ADDOP_O(c, op, mangled, varnames);
2382 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383 return 1;
2384 case OP_GLOBAL:
2385 switch (ctx) {
2386 case Load: op = LOAD_GLOBAL; break;
2387 case Store: op = STORE_GLOBAL; break;
2388 case Del: op = DELETE_GLOBAL; break;
2389 case AugLoad:
2390 case AugStore:
2391 break;
2392 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002393 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002394 PyErr_SetString(PyExc_SystemError,
2395 "param invalid for global variable");
2396 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397 }
2398 break;
2399 case OP_NAME:
2400 switch (ctx) {
2401 case Load: op = LOAD_NAME; break;
2402 case Store: op = STORE_NAME; break;
2403 case Del: op = DELETE_NAME; break;
2404 case AugLoad:
2405 case AugStore:
2406 break;
2407 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002408 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002409 PyErr_SetString(PyExc_SystemError,
2410 "param invalid for name variable");
2411 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412 }
2413 break;
2414 }
2415
2416 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002417 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002418 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002419 if (arg < 0)
2420 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002421 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422}
2423
2424static int
2425compiler_boolop(struct compiler *c, expr_ty e)
2426{
2427 basicblock *end;
2428 int jumpi, i, n;
2429 asdl_seq *s;
2430
2431 assert(e->kind == BoolOp_kind);
2432 if (e->v.BoolOp.op == And)
2433 jumpi = JUMP_IF_FALSE;
2434 else
2435 jumpi = JUMP_IF_TRUE;
2436 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002437 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438 return 0;
2439 s = e->v.BoolOp.values;
2440 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002441 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002443 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 ADDOP_JREL(c, jumpi, end);
2445 ADDOP(c, POP_TOP)
2446 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002447 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448 compiler_use_next_block(c, end);
2449 return 1;
2450}
2451
2452static int
2453compiler_list(struct compiler *c, expr_ty e)
2454{
2455 int n = asdl_seq_LEN(e->v.List.elts);
2456 if (e->v.List.ctx == Store) {
2457 ADDOP_I(c, UNPACK_SEQUENCE, n);
2458 }
2459 VISIT_SEQ(c, expr, e->v.List.elts);
2460 if (e->v.List.ctx == Load) {
2461 ADDOP_I(c, BUILD_LIST, n);
2462 }
2463 return 1;
2464}
2465
2466static int
2467compiler_tuple(struct compiler *c, expr_ty e)
2468{
2469 int n = asdl_seq_LEN(e->v.Tuple.elts);
2470 if (e->v.Tuple.ctx == Store) {
2471 ADDOP_I(c, UNPACK_SEQUENCE, n);
2472 }
2473 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2474 if (e->v.Tuple.ctx == Load) {
2475 ADDOP_I(c, BUILD_TUPLE, n);
2476 }
2477 return 1;
2478}
2479
2480static int
2481compiler_compare(struct compiler *c, expr_ty e)
2482{
2483 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002484 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485
2486 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2487 VISIT(c, expr, e->v.Compare.left);
2488 n = asdl_seq_LEN(e->v.Compare.ops);
2489 assert(n > 0);
2490 if (n > 1) {
2491 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002492 if (cleanup == NULL)
2493 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002494 VISIT(c, expr,
2495 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496 }
2497 for (i = 1; i < n; i++) {
2498 ADDOP(c, DUP_TOP);
2499 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002501 cmpop((cmpop_ty)(asdl_seq_GET(
2502 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2504 NEXT_BLOCK(c);
2505 ADDOP(c, POP_TOP);
2506 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002507 VISIT(c, expr,
2508 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002510 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002512 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 if (n > 1) {
2514 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002515 if (end == NULL)
2516 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517 ADDOP_JREL(c, JUMP_FORWARD, end);
2518 compiler_use_next_block(c, cleanup);
2519 ADDOP(c, ROT_TWO);
2520 ADDOP(c, POP_TOP);
2521 compiler_use_next_block(c, end);
2522 }
2523 return 1;
2524}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002525#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526
2527static int
2528compiler_call(struct compiler *c, expr_ty e)
2529{
2530 int n, code = 0;
2531
2532 VISIT(c, expr, e->v.Call.func);
2533 n = asdl_seq_LEN(e->v.Call.args);
2534 VISIT_SEQ(c, expr, e->v.Call.args);
2535 if (e->v.Call.keywords) {
2536 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2537 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2538 }
2539 if (e->v.Call.starargs) {
2540 VISIT(c, expr, e->v.Call.starargs);
2541 code |= 1;
2542 }
2543 if (e->v.Call.kwargs) {
2544 VISIT(c, expr, e->v.Call.kwargs);
2545 code |= 2;
2546 }
2547 switch (code) {
2548 case 0:
2549 ADDOP_I(c, CALL_FUNCTION, n);
2550 break;
2551 case 1:
2552 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2553 break;
2554 case 2:
2555 ADDOP_I(c, CALL_FUNCTION_KW, n);
2556 break;
2557 case 3:
2558 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2559 break;
2560 }
2561 return 1;
2562}
2563
2564static int
2565compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002566 asdl_seq *generators, int gen_index,
2567 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568{
2569 /* generate code for the iterator, then each of the ifs,
2570 and then write to the element */
2571
2572 comprehension_ty l;
2573 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002574 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
2576 start = compiler_new_block(c);
2577 skip = compiler_new_block(c);
2578 if_cleanup = compiler_new_block(c);
2579 anchor = compiler_new_block(c);
2580
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002581 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2582 anchor == NULL)
2583 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002585 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 VISIT(c, expr, l->iter);
2587 ADDOP(c, GET_ITER);
2588 compiler_use_next_block(c, start);
2589 ADDOP_JREL(c, FOR_ITER, anchor);
2590 NEXT_BLOCK(c);
2591 VISIT(c, expr, l->target);
2592
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002593 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594 n = asdl_seq_LEN(l->ifs);
2595 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002596 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597 VISIT(c, expr, e);
2598 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2599 NEXT_BLOCK(c);
2600 ADDOP(c, POP_TOP);
2601 }
2602
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002603 if (++gen_index < asdl_seq_LEN(generators))
2604 if (!compiler_listcomp_generator(c, tmpname,
2605 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002608 /* only append after the last for generator */
2609 if (gen_index >= asdl_seq_LEN(generators)) {
2610 if (!compiler_nameop(c, tmpname, Load))
2611 return 0;
2612 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002613 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614
2615 compiler_use_next_block(c, skip);
2616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 for (i = 0; i < n; i++) {
2618 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002619 if (i == 0)
2620 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 ADDOP(c, POP_TOP);
2622 }
2623 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2624 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002625 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002627 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628 return 0;
2629
2630 return 1;
2631}
2632
2633static int
2634compiler_listcomp(struct compiler *c, expr_ty e)
2635{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002637 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 static identifier append;
2639 asdl_seq *generators = e->v.ListComp.generators;
2640
2641 assert(e->kind == ListComp_kind);
2642 if (!append) {
2643 append = PyString_InternFromString("append");
2644 if (!append)
2645 return 0;
2646 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002647 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 if (!tmp)
2649 return 0;
2650 ADDOP_I(c, BUILD_LIST, 0);
2651 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002653 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2654 e->v.ListComp.elt);
2655 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 return rc;
2657}
2658
2659static int
2660compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 asdl_seq *generators, int gen_index,
2662 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663{
2664 /* generate code for the iterator, then each of the ifs,
2665 and then write to the element */
2666
2667 comprehension_ty ge;
2668 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670
2671 start = compiler_new_block(c);
2672 skip = compiler_new_block(c);
2673 if_cleanup = compiler_new_block(c);
2674 anchor = compiler_new_block(c);
2675 end = compiler_new_block(c);
2676
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 anchor == NULL || end == NULL)
2679 return 0;
2680
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002681 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 ADDOP_JREL(c, SETUP_LOOP, end);
2683 if (!compiler_push_fblock(c, LOOP, start))
2684 return 0;
2685
2686 if (gen_index == 0) {
2687 /* Receive outermost iter as an implicit argument */
2688 c->u->u_argcount = 1;
2689 ADDOP_I(c, LOAD_FAST, 0);
2690 }
2691 else {
2692 /* Sub-iter - calculate on the fly */
2693 VISIT(c, expr, ge->iter);
2694 ADDOP(c, GET_ITER);
2695 }
2696 compiler_use_next_block(c, start);
2697 ADDOP_JREL(c, FOR_ITER, anchor);
2698 NEXT_BLOCK(c);
2699 VISIT(c, expr, ge->target);
2700
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002701 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 n = asdl_seq_LEN(ge->ifs);
2703 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002704 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 VISIT(c, expr, e);
2706 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2707 NEXT_BLOCK(c);
2708 ADDOP(c, POP_TOP);
2709 }
2710
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002711 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2713 return 0;
2714
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002715 /* only append after the last 'for' generator */
2716 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 VISIT(c, expr, elt);
2718 ADDOP(c, YIELD_VALUE);
2719 ADDOP(c, POP_TOP);
2720
2721 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002722 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 for (i = 0; i < n; i++) {
2724 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002725 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726 compiler_use_next_block(c, if_cleanup);
2727
2728 ADDOP(c, POP_TOP);
2729 }
2730 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2731 compiler_use_next_block(c, anchor);
2732 ADDOP(c, POP_BLOCK);
2733 compiler_pop_fblock(c, LOOP, start);
2734 compiler_use_next_block(c, end);
2735
2736 return 1;
2737}
2738
2739static int
2740compiler_genexp(struct compiler *c, expr_ty e)
2741{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002742 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 PyCodeObject *co;
2744 expr_ty outermost_iter = ((comprehension_ty)
2745 (asdl_seq_GET(e->v.GeneratorExp.generators,
2746 0)))->iter;
2747
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002748 if (!name) {
2749 name = PyString_FromString("<genexpr>");
2750 if (!name)
2751 return 0;
2752 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753
2754 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2755 return 0;
2756 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2757 e->v.GeneratorExp.elt);
2758 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002759 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760 if (co == NULL)
2761 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002763 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002764 Py_DECREF(co);
2765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766 VISIT(c, expr, outermost_iter);
2767 ADDOP(c, GET_ITER);
2768 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769
2770 return 1;
2771}
2772
2773static int
2774compiler_visit_keyword(struct compiler *c, keyword_ty k)
2775{
2776 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2777 VISIT(c, expr, k->value);
2778 return 1;
2779}
2780
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002781/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782 whether they are true or false.
2783
2784 Return values: 1 for true, 0 for false, -1 for non-constant.
2785 */
2786
2787static int
2788expr_constant(expr_ty e)
2789{
2790 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00002791 case Ellipsis_kind:
2792 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002793 case Num_kind:
2794 return PyObject_IsTrue(e->v.Num.n);
2795 case Str_kind:
2796 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002797 case Name_kind:
2798 /* __debug__ is not assignable, so we can optimize
2799 * it away in if and while statements */
2800 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2801 "__debug__") == 0)
2802 return ! Py_OptimizeFlag;
2803 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804 default:
2805 return -1;
2806 }
2807}
2808
Guido van Rossumc2e20742006-02-27 22:32:47 +00002809/*
2810 Implements the with statement from PEP 343.
2811
2812 The semantics outlined in that PEP are as follows:
2813
2814 with EXPR as VAR:
2815 BLOCK
2816
2817 It is implemented roughly as:
2818
Thomas Wouters477c8d52006-05-27 19:21:47 +00002819 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002820 exit = context.__exit__ # not calling it
2821 value = context.__enter__()
2822 try:
2823 VAR = value # if VAR present in the syntax
2824 BLOCK
2825 finally:
2826 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002827 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002828 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002829 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830 exit(*exc)
2831 */
2832static int
2833compiler_with(struct compiler *c, stmt_ty s)
2834{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002835 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 basicblock *block, *finally;
2837 identifier tmpexit, tmpvalue = NULL;
2838
2839 assert(s->kind == With_kind);
2840
Guido van Rossumc2e20742006-02-27 22:32:47 +00002841 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 enter_attr = PyString_InternFromString("__enter__");
2843 if (!enter_attr)
2844 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002845 }
2846 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847 exit_attr = PyString_InternFromString("__exit__");
2848 if (!exit_attr)
2849 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002850 }
2851
2852 block = compiler_new_block(c);
2853 finally = compiler_new_block(c);
2854 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002855 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002856
2857 /* Create a temporary variable to hold context.__exit__ */
2858 tmpexit = compiler_new_tmpname(c);
2859 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002860 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002861 PyArena_AddPyObject(c->c_arena, tmpexit);
2862
2863 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002864 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002865 We need to do this rather than preserving it on the stack
2866 because SETUP_FINALLY remembers the stack level.
2867 We need to do the assignment *inside* the try/finally
2868 so that context.__exit__() is called when the assignment
2869 fails. But we need to call context.__enter__() *before*
2870 the try/finally so that if it fails we won't call
2871 context.__exit__().
2872 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002873 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002874 if (tmpvalue == NULL)
2875 return 0;
2876 PyArena_AddPyObject(c->c_arena, tmpvalue);
2877 }
2878
Thomas Wouters477c8d52006-05-27 19:21:47 +00002879 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002880 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002881
2882 /* Squirrel away context.__exit__ */
2883 ADDOP(c, DUP_TOP);
2884 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2885 if (!compiler_nameop(c, tmpexit, Store))
2886 return 0;
2887
2888 /* Call context.__enter__() */
2889 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2890 ADDOP_I(c, CALL_FUNCTION, 0);
2891
2892 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002893 /* Store it in tmpvalue */
2894 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002895 return 0;
2896 }
2897 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002898 /* Discard result from context.__enter__() */
2899 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002900 }
2901
2902 /* Start the try block */
2903 ADDOP_JREL(c, SETUP_FINALLY, finally);
2904
2905 compiler_use_next_block(c, block);
2906 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002907 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908 }
2909
2910 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002911 /* Bind saved result of context.__enter__() to VAR */
2912 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002913 !compiler_nameop(c, tmpvalue, Del))
2914 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002915 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002916 }
2917
2918 /* BLOCK code */
2919 VISIT_SEQ(c, stmt, s->v.With.body);
2920
2921 /* End of try block; start the finally block */
2922 ADDOP(c, POP_BLOCK);
2923 compiler_pop_fblock(c, FINALLY_TRY, block);
2924
2925 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2926 compiler_use_next_block(c, finally);
2927 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002928 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002929
2930 /* Finally block starts; push tmpexit and issue our magic opcode. */
2931 if (!compiler_nameop(c, tmpexit, Load) ||
2932 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002933 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002934 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002935
2936 /* Finally block ends. */
2937 ADDOP(c, END_FINALLY);
2938 compiler_pop_fblock(c, FINALLY_END, finally);
2939 return 1;
2940}
2941
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942static int
2943compiler_visit_expr(struct compiler *c, expr_ty e)
2944{
2945 int i, n;
2946
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002947 /* If expr e has a different line number than the last expr/stmt,
2948 set a new line number for the next instruction.
2949 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950 if (e->lineno > c->u->u_lineno) {
2951 c->u->u_lineno = e->lineno;
2952 c->u->u_lineno_set = false;
2953 }
2954 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002955 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002957 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 VISIT(c, expr, e->v.BinOp.left);
2959 VISIT(c, expr, e->v.BinOp.right);
2960 ADDOP(c, binop(c, e->v.BinOp.op));
2961 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002962 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 VISIT(c, expr, e->v.UnaryOp.operand);
2964 ADDOP(c, unaryop(e->v.UnaryOp.op));
2965 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002966 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002968 case IfExp_kind:
2969 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002970 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 /* XXX get rid of arg? */
2972 ADDOP_I(c, BUILD_MAP, 0);
2973 n = asdl_seq_LEN(e->v.Dict.values);
2974 /* We must arrange things just right for STORE_SUBSCR.
2975 It wants the stack to look like (value) (dict) (key) */
2976 for (i = 0; i < n; i++) {
2977 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002978 VISIT(c, expr,
2979 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002981 VISIT(c, expr,
2982 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983 ADDOP(c, STORE_SUBSCR);
2984 }
2985 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002986 case Set_kind:
2987 n = asdl_seq_LEN(e->v.Set.elts);
2988 VISIT_SEQ(c, expr, e->v.Set.elts);
2989 ADDOP_I(c, BUILD_SET, n);
2990 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002991 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002993 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994 return compiler_genexp(c, e);
2995 case Yield_kind:
2996 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002997 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998 /*
2999 for (i = 0; i < c->u->u_nfblocks; i++) {
3000 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3001 return compiler_error(
3002 c, "'yield' not allowed in a 'try' "
3003 "block with a 'finally' clause");
3004 }
3005 */
3006 if (e->v.Yield.value) {
3007 VISIT(c, expr, e->v.Yield.value);
3008 }
3009 else {
3010 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3011 }
3012 ADDOP(c, YIELD_VALUE);
3013 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003014 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003016 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003018 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3020 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003021 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3023 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003024 case Ellipsis_kind:
3025 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3026 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003028 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 if (e->v.Attribute.ctx != AugStore)
3030 VISIT(c, expr, e->v.Attribute.value);
3031 switch (e->v.Attribute.ctx) {
3032 case AugLoad:
3033 ADDOP(c, DUP_TOP);
3034 /* Fall through to load */
3035 case Load:
3036 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3037 break;
3038 case AugStore:
3039 ADDOP(c, ROT_TWO);
3040 /* Fall through to save */
3041 case Store:
3042 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3043 break;
3044 case Del:
3045 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3046 break;
3047 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003048 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003049 PyErr_SetString(PyExc_SystemError,
3050 "param invalid in attribute expression");
3051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052 }
3053 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003054 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 switch (e->v.Subscript.ctx) {
3056 case AugLoad:
3057 VISIT(c, expr, e->v.Subscript.value);
3058 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3059 break;
3060 case Load:
3061 VISIT(c, expr, e->v.Subscript.value);
3062 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3063 break;
3064 case AugStore:
3065 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3066 break;
3067 case Store:
3068 VISIT(c, expr, e->v.Subscript.value);
3069 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3070 break;
3071 case Del:
3072 VISIT(c, expr, e->v.Subscript.value);
3073 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3074 break;
3075 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003076 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003077 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003078 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003079 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080 }
3081 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003082 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3084 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003085 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003087 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 return compiler_tuple(c, e);
3089 }
3090 return 1;
3091}
3092
3093static int
3094compiler_augassign(struct compiler *c, stmt_ty s)
3095{
3096 expr_ty e = s->v.AugAssign.target;
3097 expr_ty auge;
3098
3099 assert(s->kind == AugAssign_kind);
3100
3101 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003102 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003104 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003105 if (auge == NULL)
3106 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107 VISIT(c, expr, auge);
3108 VISIT(c, expr, s->v.AugAssign.value);
3109 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3110 auge->v.Attribute.ctx = AugStore;
3111 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112 break;
3113 case Subscript_kind:
3114 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003115 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 if (auge == NULL)
3117 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118 VISIT(c, expr, auge);
3119 VISIT(c, expr, s->v.AugAssign.value);
3120 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003121 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003124 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003125 if (!compiler_nameop(c, e->v.Name.id, Load))
3126 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127 VISIT(c, expr, s->v.AugAssign.value);
3128 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3129 return compiler_nameop(c, e->v.Name.id, Store);
3130 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003131 PyErr_Format(PyExc_SystemError,
3132 "invalid node type (%d) for augmented assignment",
3133 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135 }
3136 return 1;
3137}
3138
3139static int
3140compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3141{
3142 struct fblockinfo *f;
3143 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3144 return 0;
3145 f = &c->u->u_fblock[c->u->u_nfblocks++];
3146 f->fb_type = t;
3147 f->fb_block = b;
3148 return 1;
3149}
3150
3151static void
3152compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3153{
3154 struct compiler_unit *u = c->u;
3155 assert(u->u_nfblocks > 0);
3156 u->u_nfblocks--;
3157 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3158 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3159}
3160
3161/* Raises a SyntaxError and returns 0.
3162 If something goes wrong, a different exception may be raised.
3163*/
3164
3165static int
3166compiler_error(struct compiler *c, const char *errstr)
3167{
3168 PyObject *loc;
3169 PyObject *u = NULL, *v = NULL;
3170
3171 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3172 if (!loc) {
3173 Py_INCREF(Py_None);
3174 loc = Py_None;
3175 }
3176 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3177 Py_None, loc);
3178 if (!u)
3179 goto exit;
3180 v = Py_BuildValue("(zO)", errstr, u);
3181 if (!v)
3182 goto exit;
3183 PyErr_SetObject(PyExc_SyntaxError, v);
3184 exit:
3185 Py_DECREF(loc);
3186 Py_XDECREF(u);
3187 Py_XDECREF(v);
3188 return 0;
3189}
3190
3191static int
3192compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197 /* XXX this code is duplicated */
3198 switch (ctx) {
3199 case AugLoad: /* fall through to Load */
3200 case Load: op = BINARY_SUBSCR; break;
3201 case AugStore:/* fall through to Store */
3202 case Store: op = STORE_SUBSCR; break;
3203 case Del: op = DELETE_SUBSCR; break;
3204 case Param:
3205 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003206 "invalid %s kind %d in subscript\n",
3207 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003208 return 0;
3209 }
3210 if (ctx == AugLoad) {
3211 ADDOP_I(c, DUP_TOPX, 2);
3212 }
3213 else if (ctx == AugStore) {
3214 ADDOP(c, ROT_THREE);
3215 }
3216 ADDOP(c, op);
3217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218}
3219
3220static int
3221compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3222{
3223 int n = 2;
3224 assert(s->kind == Slice_kind);
3225
3226 /* only handles the cases where BUILD_SLICE is emitted */
3227 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003228 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229 }
3230 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003231 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236 }
3237 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003238 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239 }
3240
3241 if (s->v.Slice.step) {
3242 n++;
3243 VISIT(c, expr, s->v.Slice.step);
3244 }
3245 ADDOP_I(c, BUILD_SLICE, n);
3246 return 1;
3247}
3248
3249static int
3250compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3251{
3252 int op = 0, slice_offset = 0, stack_count = 0;
3253
3254 assert(s->v.Slice.step == NULL);
3255 if (s->v.Slice.lower) {
3256 slice_offset++;
3257 stack_count++;
3258 if (ctx != AugStore)
3259 VISIT(c, expr, s->v.Slice.lower);
3260 }
3261 if (s->v.Slice.upper) {
3262 slice_offset += 2;
3263 stack_count++;
3264 if (ctx != AugStore)
3265 VISIT(c, expr, s->v.Slice.upper);
3266 }
3267
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003268 if (ctx == AugLoad) {
3269 switch (stack_count) {
3270 case 0: ADDOP(c, DUP_TOP); break;
3271 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3272 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3273 }
3274 }
3275 else if (ctx == AugStore) {
3276 switch (stack_count) {
3277 case 0: ADDOP(c, ROT_TWO); break;
3278 case 1: ADDOP(c, ROT_THREE); break;
3279 case 2: ADDOP(c, ROT_FOUR); break;
3280 }
3281 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282
3283 switch (ctx) {
3284 case AugLoad: /* fall through to Load */
3285 case Load: op = SLICE; break;
3286 case AugStore:/* fall through to Store */
3287 case Store: op = STORE_SLICE; break;
3288 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003289 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003290 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003291 PyErr_SetString(PyExc_SystemError,
3292 "param invalid in simple slice");
3293 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294 }
3295
3296 ADDOP(c, op + slice_offset);
3297 return 1;
3298}
3299
3300static int
3301compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3302 expr_context_ty ctx)
3303{
3304 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305 case Slice_kind:
3306 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307 case Index_kind:
3308 VISIT(c, expr, s->v.Index.value);
3309 break;
3310 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003311 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003312 PyErr_SetString(PyExc_SystemError,
3313 "extended slice invalid in nested slice");
3314 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315 }
3316 return 1;
3317}
3318
3319
3320static int
3321compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3322{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003323 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003325 case Index_kind:
3326 kindname = "index";
3327 if (ctx != AugStore) {
3328 VISIT(c, expr, s->v.Index.value);
3329 }
3330 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003331 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003332 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333 if (!s->v.Slice.step)
3334 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003335 if (ctx != AugStore) {
3336 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337 return 0;
3338 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003339 break;
3340 case ExtSlice_kind:
3341 kindname = "extended slice";
3342 if (ctx != AugStore) {
3343 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3344 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003345 slice_ty sub = (slice_ty)asdl_seq_GET(
3346 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003347 if (!compiler_visit_nested_slice(c, sub, ctx))
3348 return 0;
3349 }
3350 ADDOP_I(c, BUILD_TUPLE, n);
3351 }
3352 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003353 default:
3354 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003355 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003358 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359}
3360
3361/* do depth-first search of basic block graph, starting with block.
3362 post records the block indices in post-order.
3363
3364 XXX must handle implicit jumps from one block to next
3365*/
3366
3367static void
3368dfs(struct compiler *c, basicblock *b, struct assembler *a)
3369{
3370 int i;
3371 struct instr *instr = NULL;
3372
3373 if (b->b_seen)
3374 return;
3375 b->b_seen = 1;
3376 if (b->b_next != NULL)
3377 dfs(c, b->b_next, a);
3378 for (i = 0; i < b->b_iused; i++) {
3379 instr = &b->b_instr[i];
3380 if (instr->i_jrel || instr->i_jabs)
3381 dfs(c, instr->i_target, a);
3382 }
3383 a->a_postorder[a->a_nblocks++] = b;
3384}
3385
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003386static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3388{
3389 int i;
3390 struct instr *instr;
3391 if (b->b_seen || b->b_startdepth >= depth)
3392 return maxdepth;
3393 b->b_seen = 1;
3394 b->b_startdepth = depth;
3395 for (i = 0; i < b->b_iused; i++) {
3396 instr = &b->b_instr[i];
3397 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3398 if (depth > maxdepth)
3399 maxdepth = depth;
3400 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3401 if (instr->i_jrel || instr->i_jabs) {
3402 maxdepth = stackdepth_walk(c, instr->i_target,
3403 depth, maxdepth);
3404 if (instr->i_opcode == JUMP_ABSOLUTE ||
3405 instr->i_opcode == JUMP_FORWARD) {
3406 goto out; /* remaining code is dead */
3407 }
3408 }
3409 }
3410 if (b->b_next)
3411 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3412out:
3413 b->b_seen = 0;
3414 return maxdepth;
3415}
3416
3417/* Find the flow path that needs the largest stack. We assume that
3418 * cycles in the flow graph have no net effect on the stack depth.
3419 */
3420static int
3421stackdepth(struct compiler *c)
3422{
3423 basicblock *b, *entryblock;
3424 entryblock = NULL;
3425 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3426 b->b_seen = 0;
3427 b->b_startdepth = INT_MIN;
3428 entryblock = b;
3429 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003430 if (!entryblock)
3431 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432 return stackdepth_walk(c, entryblock, 0, 0);
3433}
3434
3435static int
3436assemble_init(struct assembler *a, int nblocks, int firstlineno)
3437{
3438 memset(a, 0, sizeof(struct assembler));
3439 a->a_lineno = firstlineno;
3440 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3441 if (!a->a_bytecode)
3442 return 0;
3443 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3444 if (!a->a_lnotab)
3445 return 0;
3446 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003447 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003448 if (!a->a_postorder) {
3449 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003451 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452 return 1;
3453}
3454
3455static void
3456assemble_free(struct assembler *a)
3457{
3458 Py_XDECREF(a->a_bytecode);
3459 Py_XDECREF(a->a_lnotab);
3460 if (a->a_postorder)
3461 PyObject_Free(a->a_postorder);
3462}
3463
3464/* Return the size of a basic block in bytes. */
3465
3466static int
3467instrsize(struct instr *instr)
3468{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003469 if (!instr->i_hasarg)
3470 return 1;
3471 if (instr->i_oparg > 0xffff)
3472 return 6;
3473 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474}
3475
3476static int
3477blocksize(basicblock *b)
3478{
3479 int i;
3480 int size = 0;
3481
3482 for (i = 0; i < b->b_iused; i++)
3483 size += instrsize(&b->b_instr[i]);
3484 return size;
3485}
3486
3487/* All about a_lnotab.
3488
3489c_lnotab is an array of unsigned bytes disguised as a Python string.
3490It is used to map bytecode offsets to source code line #s (when needed
3491for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003492
Tim Peters2a7f3842001-06-09 09:26:21 +00003493The array is conceptually a list of
3494 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003496
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003497 byte code offset source code line number
3498 0 1
3499 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003500 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003501 350 307
3502 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003503
3504The first trick is that these numbers aren't stored, only the increments
3505from one row to the next (this doesn't really work, but it's a start):
3506
3507 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3508
3509The second trick is that an unsigned byte can't hold negative values, or
3510values larger than 255, so (a) there's a deep assumption that byte code
3511offsets and their corresponding line #s both increase monotonically, and (b)
3512if at least one column jumps by more than 255 from one row to the next, more
3513than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003514from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003515part. A user of c_lnotab desiring to find the source line number
3516corresponding to a bytecode address A should do something like this
3517
3518 lineno = addr = 0
3519 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003520 addr += addr_incr
3521 if addr > A:
3522 return lineno
3523 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003524
3525In order for this to work, when the addr field increments by more than 255,
3526the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003527increment is < 256. So, in the example above, assemble_lnotab (it used
3528to be called com_set_lineno) should not (as was actually done until 2.2)
3529expand 300, 300 to 255, 255, 45, 45,
3530 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003531*/
3532
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003533static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003535{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536 int d_bytecode, d_lineno;
3537 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003538 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539
3540 d_bytecode = a->a_offset - a->a_lineno_off;
3541 d_lineno = i->i_lineno - a->a_lineno;
3542
3543 assert(d_bytecode >= 0);
3544 assert(d_lineno >= 0);
3545
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003546 /* XXX(nnorwitz): is there a better way to handle this?
3547 for loops are special, we want to be able to trace them
3548 each time around, so we need to set an extra line number. */
3549 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003550 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003551
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003553 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 nbytes = a->a_lnotab_off + 2 * ncodes;
3555 len = PyString_GET_SIZE(a->a_lnotab);
3556 if (nbytes >= len) {
3557 if (len * 2 < nbytes)
3558 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003559 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 len *= 2;
3561 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3562 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003563 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003564 lnotab = (unsigned char *)
3565 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003566 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567 *lnotab++ = 255;
3568 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003569 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 d_bytecode -= ncodes * 255;
3571 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003572 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 assert(d_bytecode <= 255);
3574 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003575 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576 nbytes = a->a_lnotab_off + 2 * ncodes;
3577 len = PyString_GET_SIZE(a->a_lnotab);
3578 if (nbytes >= len) {
3579 if (len * 2 < nbytes)
3580 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003581 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582 len *= 2;
3583 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3584 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003585 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003586 lnotab = (unsigned char *)
3587 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003589 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003591 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003593 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595 d_lineno -= ncodes * 255;
3596 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003597 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003598
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599 len = PyString_GET_SIZE(a->a_lnotab);
3600 if (a->a_lnotab_off + 2 >= len) {
3601 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003602 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003603 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003604 lnotab = (unsigned char *)
3605 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003606
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607 a->a_lnotab_off += 2;
3608 if (d_bytecode) {
3609 *lnotab++ = d_bytecode;
3610 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003611 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003612 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 *lnotab++ = 0;
3614 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 a->a_lineno = i->i_lineno;
3617 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003618 return 1;
3619}
3620
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621/* assemble_emit()
3622 Extend the bytecode with a new instruction.
3623 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003624*/
3625
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003626static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003628{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003629 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003630 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 char *code;
3632
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003633 size = instrsize(i);
3634 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003636 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003637 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003639 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640 if (a->a_offset + size >= len) {
3641 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003642 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003643 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3645 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003646 if (size == 6) {
3647 assert(i->i_hasarg);
3648 *code++ = (char)EXTENDED_ARG;
3649 *code++ = ext & 0xff;
3650 *code++ = ext >> 8;
3651 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003652 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003654 if (i->i_hasarg) {
3655 assert(size == 3 || size == 6);
3656 *code++ = arg & 0xff;
3657 *code++ = arg >> 8;
3658 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003660}
3661
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003662static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003664{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003665 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003666 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003667 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003668
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669 /* Compute the size of each block and fixup jump args.
3670 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003671start:
3672 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003674 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675 bsize = blocksize(b);
3676 b->b_offset = totsize;
3677 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003678 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003679 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3681 bsize = b->b_offset;
3682 for (i = 0; i < b->b_iused; i++) {
3683 struct instr *instr = &b->b_instr[i];
3684 /* Relative jumps are computed relative to
3685 the instruction pointer after fetching
3686 the jump instruction.
3687 */
3688 bsize += instrsize(instr);
3689 if (instr->i_jabs)
3690 instr->i_oparg = instr->i_target->b_offset;
3691 else if (instr->i_jrel) {
3692 int delta = instr->i_target->b_offset - bsize;
3693 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003694 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003695 else
3696 continue;
3697 if (instr->i_oparg > 0xffff)
3698 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003699 }
3700 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003701
3702 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003703 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003704 with a better solution.
3705
3706 In the meantime, should the goto be dropped in favor
3707 of a loop?
3708
3709 The issue is that in the first loop blocksize() is called
3710 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003711 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003712 i_oparg is calculated in the second loop above.
3713
3714 So we loop until we stop seeing new EXTENDED_ARGs.
3715 The only EXTENDED_ARGs that could be popping up are
3716 ones in jump instructions. So this should converge
3717 fairly quickly.
3718 */
3719 if (last_extended_arg_count != extended_arg_count) {
3720 last_extended_arg_count = extended_arg_count;
3721 goto start;
3722 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003723}
3724
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003725static PyObject *
3726dict_keys_inorder(PyObject *dict, int offset)
3727{
3728 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003729 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003730
3731 tuple = PyTuple_New(size);
3732 if (tuple == NULL)
3733 return NULL;
3734 while (PyDict_Next(dict, &pos, &k, &v)) {
3735 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003736 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003737 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003738 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003739 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003740 PyTuple_SET_ITEM(tuple, i - offset, k);
3741 }
3742 return tuple;
3743}
3744
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003745static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003747{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748 PySTEntryObject *ste = c->u->u_ste;
3749 int flags = 0, n;
3750 if (ste->ste_type != ModuleBlock)
3751 flags |= CO_NEWLOCALS;
3752 if (ste->ste_type == FunctionBlock) {
3753 if (!ste->ste_unoptimized)
3754 flags |= CO_OPTIMIZED;
3755 if (ste->ste_nested)
3756 flags |= CO_NESTED;
3757 if (ste->ste_generator)
3758 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003759 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 if (ste->ste_varargs)
3761 flags |= CO_VARARGS;
3762 if (ste->ste_varkeywords)
3763 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003764 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003766
3767 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003768 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003769
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770 n = PyDict_Size(c->u->u_freevars);
3771 if (n < 0)
3772 return -1;
3773 if (n == 0) {
3774 n = PyDict_Size(c->u->u_cellvars);
3775 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003776 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777 if (n == 0) {
3778 flags |= CO_NOFREE;
3779 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003780 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003781
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003782 return flags;
3783}
3784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785static PyCodeObject *
3786makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003787{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788 PyObject *tmp;
3789 PyCodeObject *co = NULL;
3790 PyObject *consts = NULL;
3791 PyObject *names = NULL;
3792 PyObject *varnames = NULL;
3793 PyObject *filename = NULL;
3794 PyObject *name = NULL;
3795 PyObject *freevars = NULL;
3796 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003797 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003799
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 tmp = dict_keys_inorder(c->u->u_consts, 0);
3801 if (!tmp)
3802 goto error;
3803 consts = PySequence_List(tmp); /* optimize_code requires a list */
3804 Py_DECREF(tmp);
3805
3806 names = dict_keys_inorder(c->u->u_names, 0);
3807 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3808 if (!consts || !names || !varnames)
3809 goto error;
3810
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003811 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3812 if (!cellvars)
3813 goto error;
3814 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3815 if (!freevars)
3816 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817 filename = PyString_FromString(c->c_filename);
3818 if (!filename)
3819 goto error;
3820
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003821 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822 flags = compute_code_flags(c);
3823 if (flags < 0)
3824 goto error;
3825
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003826 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 if (!bytecode)
3828 goto error;
3829
3830 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3831 if (!tmp)
3832 goto error;
3833 Py_DECREF(consts);
3834 consts = tmp;
3835
Guido van Rossum4f72a782006-10-27 23:31:49 +00003836 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3837 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838 bytecode, consts, names, varnames,
3839 freevars, cellvars,
3840 filename, c->u->u_name,
3841 c->u->u_firstlineno,
3842 a->a_lnotab);
3843 error:
3844 Py_XDECREF(consts);
3845 Py_XDECREF(names);
3846 Py_XDECREF(varnames);
3847 Py_XDECREF(filename);
3848 Py_XDECREF(name);
3849 Py_XDECREF(freevars);
3850 Py_XDECREF(cellvars);
3851 Py_XDECREF(bytecode);
3852 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003853}
3854
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003855
3856/* For debugging purposes only */
3857#if 0
3858static void
3859dump_instr(const struct instr *i)
3860{
3861 const char *jrel = i->i_jrel ? "jrel " : "";
3862 const char *jabs = i->i_jabs ? "jabs " : "";
3863 char arg[128];
3864
3865 *arg = '\0';
3866 if (i->i_hasarg)
3867 sprintf(arg, "arg: %d ", i->i_oparg);
3868
3869 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3870 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3871}
3872
3873static void
3874dump_basicblock(const basicblock *b)
3875{
3876 const char *seen = b->b_seen ? "seen " : "";
3877 const char *b_return = b->b_return ? "return " : "";
3878 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3879 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3880 if (b->b_instr) {
3881 int i;
3882 for (i = 0; i < b->b_iused; i++) {
3883 fprintf(stderr, " [%02d] ", i);
3884 dump_instr(b->b_instr + i);
3885 }
3886 }
3887}
3888#endif
3889
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890static PyCodeObject *
3891assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003892{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 basicblock *b, *entryblock;
3894 struct assembler a;
3895 int i, j, nblocks;
3896 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003897
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898 /* Make sure every block that falls off the end returns None.
3899 XXX NEXT_BLOCK() isn't quite right, because if the last
3900 block ends with a jump or return b_next shouldn't set.
3901 */
3902 if (!c->u->u_curblock->b_return) {
3903 NEXT_BLOCK(c);
3904 if (addNone)
3905 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3906 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003907 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003908
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 nblocks = 0;
3910 entryblock = NULL;
3911 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3912 nblocks++;
3913 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003914 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003915
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003916 /* Set firstlineno if it wasn't explicitly set. */
3917 if (!c->u->u_firstlineno) {
3918 if (entryblock && entryblock->b_instr)
3919 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3920 else
3921 c->u->u_firstlineno = 1;
3922 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3924 goto error;
3925 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003928 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003929
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930 /* Emit code in reverse postorder from dfs. */
3931 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003932 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933 for (j = 0; j < b->b_iused; j++)
3934 if (!assemble_emit(&a, &b->b_instr[j]))
3935 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003936 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003937
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3939 goto error;
3940 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3941 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003942
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003943 co = makecode(c, &a);
3944 error:
3945 assemble_free(&a);
3946 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003947}