blob: 8951331053ab81641670bdf5571672176f25a574 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Guido van Rossumd8faa362007-04-27 19:54:29 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Nick Coghlan650f0d02007-04-15 12:05:43 +000042#define COMP_GENEXP 0
43#define COMP_LISTCOMP 1
44#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000045#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
50 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000072 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000073 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
88enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
89
90struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000091 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092 basicblock *fb_block;
93};
94
95/* The following items change on entry and exit of code blocks.
96 They must be saved and restored when returning to a block.
97*/
98struct compiler_unit {
99 PySTEntryObject *u_ste;
100
101 PyObject *u_name;
102 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000103 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000104 the argument for opcodes that refer to those collections.
105 */
106 PyObject *u_consts; /* all constants */
107 PyObject *u_names; /* all names */
108 PyObject *u_varnames; /* local variables */
109 PyObject *u_cellvars; /* cell variables */
110 PyObject *u_freevars; /* free variables */
111
112 PyObject *u_private; /* for private name mangling */
113
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000114 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000115 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 /* Pointer to the most recently allocated block. By following b_list
117 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
122 int u_nfblocks;
123 struct fblockinfo u_fblock[CO_MAXBLOCKS];
124
125 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000126 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000127 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128 has been generated with current lineno */
129};
130
131/* This struct captures the global state of a compilation.
132
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133The u pointer points to the current compilation unit, while units
134for enclosing blocks are stored in c_stack. The u and c_stack are
135managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136*/
137
138struct compiler {
139 const char *c_filename;
140 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142 PyCompilerFlags *c_flags;
143
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 struct compiler_unit *u; /* compiler state for current block */
148 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151};
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153static int compiler_enter_scope(struct compiler *, identifier, void *, int);
154static void compiler_free(struct compiler *);
155static basicblock *compiler_new_block(struct compiler *);
156static int compiler_next_instr(struct compiler *, basicblock *);
157static int compiler_addop(struct compiler *, int);
158static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
159static int compiler_addop_i(struct compiler *, int, int);
160static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161static basicblock *compiler_use_new_block(struct compiler *);
162static int compiler_error(struct compiler *, const char *);
163static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
164
165static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
166static int compiler_visit_stmt(struct compiler *, stmt_ty);
167static int compiler_visit_keyword(struct compiler *, keyword_ty);
168static int compiler_visit_expr(struct compiler *, expr_ty);
169static int compiler_augassign(struct compiler *, stmt_ty);
170static int compiler_visit_slice(struct compiler *, slice_ty,
171 expr_context_ty);
172
173static int compiler_push_fblock(struct compiler *, enum fblocktype,
174 basicblock *);
175static void compiler_pop_fblock(struct compiler *, enum fblocktype,
176 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177/* Returns true if there is a loop on the fblock stack. */
178static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179
180static int inplace_binop(struct compiler *, operator_ty);
181static int expr_constant(expr_ty e);
182
Guido van Rossumc2e20742006-02-27 22:32:47 +0000183static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000184static int compiler_call_helper(struct compiler *c, int n,
185 asdl_seq *args,
186 asdl_seq *keywords,
187 expr_ty starargs,
188 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static PyCodeObject *assemble(struct compiler *, int addNone);
191static PyObject *__doc__;
192
193PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000195{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 /* Name mangling: __private becomes _classname__private.
197 This is independent from how the name is used. */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000198 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
199 Py_UNICODE *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200 size_t nlen, plen;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000201 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000202 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000203 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000206 p = PyUnicode_AS_UNICODE(privateobj);
207 nlen = Py_UNICODE_strlen(name);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 /* Don't mangle __id__ or names with dots.
209
210 The only time a name with a dot can occur is when
211 we are compiling an import statement that has a
212 package name.
213
214 TODO(jhylton): Decide whether we want to support
215 mangling of the module name, e.g. __M.X.
216 */
217 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Martin v. Löwis5b222132007-06-10 09:51:05 +0000218 || Py_UNICODE_strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 /* Strip leading underscores from class name */
223 while (*p == '_')
224 p++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000225 if (*p == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000229 plen = Py_UNICODE_strlen(p);
230 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000231 if (!ident)
232 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000234 buffer = PyUnicode_AS_UNICODE(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 buffer[0] = '_';
Martin v. Löwis5b222132007-06-10 09:51:05 +0000236 Py_UNICODE_strncpy(buffer+1, p, plen);
237 Py_UNICODE_strcpy(buffer+1+plen, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000238 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000239}
240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241static int
242compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000243{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000245
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000246 c->c_stack = PyList_New(0);
247 if (!c->c_stack)
248 return 0;
249
250 return 1;
251}
252
253PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000254PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256{
257 struct compiler c;
258 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000259 PyCompilerFlags local_flags;
260 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000262 if (!__doc__) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000263 __doc__ = PyUnicode_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 if (!__doc__)
265 return NULL;
266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267
268 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000269 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000271 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272 c.c_future = PyFuture_FromAST(mod, filename);
273 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000274 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000275 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000276 local_flags.cf_flags = 0;
277 flags = &local_flags;
278 }
279 merged = c.c_future->ff_features | flags->cf_flags;
280 c.c_future->ff_features = merged;
281 flags->cf_flags = merged;
282 c.c_flags = flags;
283 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284
285 c.c_st = PySymtable_Build(mod, filename, c.c_future);
286 if (c.c_st == NULL) {
287 if (!PyErr_Occurred())
288 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000289 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290 }
291
292 /* XXX initialize to NULL for now, need to handle */
293 c.c_encoding = NULL;
294
295 co = compiler_mod(&c, mod);
296
Thomas Wouters1175c432006-02-27 22:49:54 +0000297 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000299 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300 return co;
301}
302
303PyCodeObject *
304PyNode_Compile(struct _node *n, const char *filename)
305{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000306 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000307 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000308 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000309 if (!arena)
310 return NULL;
311 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000312 if (mod)
313 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000314 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000315 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000316}
317
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321 if (c->c_st)
322 PySymtable_Free(c->c_st);
323 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000326}
327
Guido van Rossum79f25d91997-04-29 20:08:16 +0000328static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000330{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000331 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000332 PyObject *v, *k;
333 PyObject *dict = PyDict_New();
334 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000335
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336 n = PyList_Size(list);
337 for (i = 0; i < n; i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000338 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339 if (!v) {
340 Py_DECREF(dict);
341 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000342 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000343 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000344 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
346 Py_XDECREF(k);
347 Py_DECREF(v);
348 Py_DECREF(dict);
349 return NULL;
350 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000351 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354 return dict;
355}
356
357/* Return new dict containing names from src that match scope(s).
358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359src is a symbol table dictionary. If the scope of a name matches
360either scope_type or flag is set, insert it into the new dict. The
361values are integers, starting at offset and increasing by one for
362each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363*/
364
365static PyObject *
366dictbytype(PyObject *src, int scope_type, int flag, int offset)
367{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000368 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369 PyObject *k, *v, *dest = PyDict_New();
370
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000371 assert(offset >= 0);
372 if (dest == NULL)
373 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374
375 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000377 long vi;
Christian Heimes217cfd12007-12-02 14:31:20 +0000378 assert(PyLong_Check(v));
379 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000380 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000382 if (scope == scope_type || vi & flag) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000383 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 if (item == NULL) {
385 Py_DECREF(dest);
386 return NULL;
387 }
388 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000389 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000390 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
391 Py_DECREF(item);
392 Py_DECREF(dest);
393 Py_XDECREF(tuple);
394 return NULL;
395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399 }
400 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000401}
402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403static void
404compiler_unit_check(struct compiler_unit *u)
405{
406 basicblock *block;
407 for (block = u->u_blocks; block != NULL; block = block->b_list) {
408 assert(block != (void *)0xcbcbcbcb);
409 assert(block != (void *)0xfbfbfbfb);
410 assert(block != (void *)0xdbdbdbdb);
411 if (block->b_instr != NULL) {
412 assert(block->b_ialloc > 0);
413 assert(block->b_iused > 0);
414 assert(block->b_ialloc >= block->b_iused);
415 }
416 else {
417 assert (block->b_iused == 0);
418 assert (block->b_ialloc == 0);
419 }
420 }
421}
422
423static void
424compiler_unit_free(struct compiler_unit *u)
425{
426 basicblock *b, *next;
427
428 compiler_unit_check(u);
429 b = u->u_blocks;
430 while (b != NULL) {
431 if (b->b_instr)
432 PyObject_Free((void *)b->b_instr);
433 next = b->b_list;
434 PyObject_Free((void *)b);
435 b = next;
436 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000437 Py_CLEAR(u->u_ste);
438 Py_CLEAR(u->u_name);
439 Py_CLEAR(u->u_consts);
440 Py_CLEAR(u->u_names);
441 Py_CLEAR(u->u_varnames);
442 Py_CLEAR(u->u_freevars);
443 Py_CLEAR(u->u_cellvars);
444 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445 PyObject_Free(u);
446}
447
448static int
449compiler_enter_scope(struct compiler *c, identifier name, void *key,
450 int lineno)
451{
452 struct compiler_unit *u;
453
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000454 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000455 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000456 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 PyErr_NoMemory();
458 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000459 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000460 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000462 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463 u->u_ste = PySymtable_Lookup(c->c_st, key);
464 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000465 compiler_unit_free(u);
466 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 }
468 Py_INCREF(name);
469 u->u_name = name;
470 u->u_varnames = list2dict(u->u_ste->ste_varnames);
471 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000472 if (!u->u_varnames || !u->u_cellvars) {
473 compiler_unit_free(u);
474 return 0;
475 }
476
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000477 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000478 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000479 if (!u->u_freevars) {
480 compiler_unit_free(u);
481 return 0;
482 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483
484 u->u_blocks = NULL;
485 u->u_tmpname = 0;
486 u->u_nfblocks = 0;
487 u->u_firstlineno = lineno;
488 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000489 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490 u->u_consts = PyDict_New();
491 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000492 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493 return 0;
494 }
495 u->u_names = PyDict_New();
496 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000497 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498 return 0;
499 }
500
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000501 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502
503 /* Push the old compiler_unit on the stack. */
504 if (c->u) {
505 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
507 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000508 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 return 0;
510 }
511 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 u->u_private = c->u->u_private;
513 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000514 }
515 c->u = u;
516
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000517 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000518 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519 return 0;
520
521 return 1;
522}
523
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525compiler_exit_scope(struct compiler *c)
526{
527 int n;
528 PyObject *wrapper;
529
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000530 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531 compiler_unit_free(c->u);
532 /* Restore c->u to the parent unit. */
533 n = PyList_GET_SIZE(c->c_stack) - 1;
534 if (n >= 0) {
535 wrapper = PyList_GET_ITEM(c->c_stack, n);
536 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000537 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000538 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000539 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000540 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541 compiler_unit_check(c->u);
542 }
543 else
544 c->u = NULL;
545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546}
547
Guido van Rossumc2e20742006-02-27 22:32:47 +0000548/* Allocate a new "anonymous" local variable.
549 Used by list comprehensions and with statements.
550*/
551
552static PyObject *
553compiler_new_tmpname(struct compiler *c)
554{
555 char tmpname[256];
556 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000557 return PyUnicode_FromString(tmpname);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000558}
559
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560/* Allocate a new block and return a pointer to it.
561 Returns NULL on error.
562*/
563
564static basicblock *
565compiler_new_block(struct compiler *c)
566{
567 basicblock *b;
568 struct compiler_unit *u;
569
570 u = c->u;
571 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000572 if (b == NULL) {
573 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000574 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000576 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000577 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578 b->b_list = u->u_blocks;
579 u->u_blocks = b;
580 return b;
581}
582
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000583static basicblock *
584compiler_use_new_block(struct compiler *c)
585{
586 basicblock *block = compiler_new_block(c);
587 if (block == NULL)
588 return NULL;
589 c->u->u_curblock = block;
590 return block;
591}
592
593static basicblock *
594compiler_next_block(struct compiler *c)
595{
596 basicblock *block = compiler_new_block(c);
597 if (block == NULL)
598 return NULL;
599 c->u->u_curblock->b_next = block;
600 c->u->u_curblock = block;
601 return block;
602}
603
604static basicblock *
605compiler_use_next_block(struct compiler *c, basicblock *block)
606{
607 assert(block != NULL);
608 c->u->u_curblock->b_next = block;
609 c->u->u_curblock = block;
610 return block;
611}
612
613/* Returns the offset of the next instruction in the current block's
614 b_instr array. Resizes the b_instr as necessary.
615 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000616*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617
618static int
619compiler_next_instr(struct compiler *c, basicblock *b)
620{
621 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000622 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000623 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000624 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 if (b->b_instr == NULL) {
626 PyErr_NoMemory();
627 return -1;
628 }
629 b->b_ialloc = DEFAULT_BLOCK_SIZE;
630 memset((char *)b->b_instr, 0,
631 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000632 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635 size_t oldsize, newsize;
636 oldsize = b->b_ialloc * sizeof(struct instr);
637 newsize = oldsize << 1;
638 if (newsize == 0) {
639 PyErr_NoMemory();
640 return -1;
641 }
642 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645 if (tmp == NULL) {
646 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648 }
649 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
651 }
652 return b->b_iused++;
653}
654
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000655/* Set the i_lineno member of the instruction at offse off if the
656 line number for the current expression/statement (?) has not
657 already been set. If it has been set, the call has no effect.
658
659 Every time a new node is b
Thomas Wouters89f507f2006-12-13 04:49:30 +0000660*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000661
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662static void
663compiler_set_lineno(struct compiler *c, int off)
664{
665 basicblock *b;
666 if (c->u->u_lineno_set)
667 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000668 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000670 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000671}
672
673static int
674opcode_stack_effect(int opcode, int oparg)
675{
676 switch (opcode) {
677 case POP_TOP:
678 return -1;
679 case ROT_TWO:
680 case ROT_THREE:
681 return 0;
682 case DUP_TOP:
683 return 1;
684 case ROT_FOUR:
685 return 0;
686
687 case UNARY_POSITIVE:
688 case UNARY_NEGATIVE:
689 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000690 case UNARY_INVERT:
691 return 0;
692
Nick Coghlan650f0d02007-04-15 12:05:43 +0000693 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000694 case LIST_APPEND:
695 return -2;
696
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000697 case BINARY_POWER:
698 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000699 case BINARY_MODULO:
700 case BINARY_ADD:
701 case BINARY_SUBTRACT:
702 case BINARY_SUBSCR:
703 case BINARY_FLOOR_DIVIDE:
704 case BINARY_TRUE_DIVIDE:
705 return -1;
706 case INPLACE_FLOOR_DIVIDE:
707 case INPLACE_TRUE_DIVIDE:
708 return -1;
709
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000710 case INPLACE_ADD:
711 case INPLACE_SUBTRACT:
712 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000713 case INPLACE_MODULO:
714 return -1;
715 case STORE_SUBSCR:
716 return -3;
717 case DELETE_SUBSCR:
718 return -2;
719
720 case BINARY_LSHIFT:
721 case BINARY_RSHIFT:
722 case BINARY_AND:
723 case BINARY_XOR:
724 case BINARY_OR:
725 return -1;
726 case INPLACE_POWER:
727 return -1;
728 case GET_ITER:
729 return 0;
730
731 case PRINT_EXPR:
732 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000733 case LOAD_BUILD_CLASS:
734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735 case INPLACE_LSHIFT:
736 case INPLACE_RSHIFT:
737 case INPLACE_AND:
738 case INPLACE_XOR:
739 case INPLACE_OR:
740 return -1;
741 case BREAK_LOOP:
742 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000743 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000744 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000745 case STORE_LOCALS:
746 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747 case RETURN_VALUE:
748 return -1;
749 case IMPORT_STAR:
750 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751 case YIELD_VALUE:
752 return 0;
753
754 case POP_BLOCK:
755 return 0;
756 case END_FINALLY:
757 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758
759 case STORE_NAME:
760 return -1;
761 case DELETE_NAME:
762 return 0;
763 case UNPACK_SEQUENCE:
764 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000765 case UNPACK_EX:
766 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767 case FOR_ITER:
768 return 1;
769
770 case STORE_ATTR:
771 return -2;
772 case DELETE_ATTR:
773 return -1;
774 case STORE_GLOBAL:
775 return -1;
776 case DELETE_GLOBAL:
777 return 0;
778 case DUP_TOPX:
779 return oparg;
780 case LOAD_CONST:
781 return 1;
782 case LOAD_NAME:
783 return 1;
784 case BUILD_TUPLE:
785 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000786 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787 return 1-oparg;
788 case BUILD_MAP:
789 return 1;
790 case LOAD_ATTR:
791 return 0;
792 case COMPARE_OP:
793 return -1;
794 case IMPORT_NAME:
795 return 0;
796 case IMPORT_FROM:
797 return 1;
798
799 case JUMP_FORWARD:
800 case JUMP_IF_FALSE:
801 case JUMP_IF_TRUE:
802 case JUMP_ABSOLUTE:
803 return 0;
804
805 case LOAD_GLOBAL:
806 return 1;
807
808 case CONTINUE_LOOP:
809 return 0;
810 case SETUP_LOOP:
811 return 0;
812 case SETUP_EXCEPT:
813 case SETUP_FINALLY:
814 return 3; /* actually pushed by an exception */
815
816 case LOAD_FAST:
817 return 1;
818 case STORE_FAST:
819 return -1;
820 case DELETE_FAST:
821 return 0;
822
823 case RAISE_VARARGS:
824 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000825#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000826 case CALL_FUNCTION:
827 return -NARGS(oparg);
828 case CALL_FUNCTION_VAR:
829 case CALL_FUNCTION_KW:
830 return -NARGS(oparg)-1;
831 case CALL_FUNCTION_VAR_KW:
832 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000834 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000835 case MAKE_CLOSURE:
836 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000837#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838 case BUILD_SLICE:
839 if (oparg == 3)
840 return -2;
841 else
842 return -1;
843
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844 case LOAD_CLOSURE:
845 return 1;
846 case LOAD_DEREF:
847 return 1;
848 case STORE_DEREF:
849 return -1;
850 default:
851 fprintf(stderr, "opcode = %d\n", opcode);
852 Py_FatalError("opcode_stack_effect()");
853
854 }
855 return 0; /* not reachable */
856}
857
858/* Add an opcode with no argument.
859 Returns 0 on failure, 1 on success.
860*/
861
862static int
863compiler_addop(struct compiler *c, int opcode)
864{
865 basicblock *b;
866 struct instr *i;
867 int off;
868 off = compiler_next_instr(c, c->u->u_curblock);
869 if (off < 0)
870 return 0;
871 b = c->u->u_curblock;
872 i = &b->b_instr[off];
873 i->i_opcode = opcode;
874 i->i_hasarg = 0;
875 if (opcode == RETURN_VALUE)
876 b->b_return = 1;
877 compiler_set_lineno(c, off);
878 return 1;
879}
880
881static int
882compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
883{
884 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000885 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000886
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000887 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000888 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
889 if (PyFloat_Check(o)) {
890 double d = PyFloat_AS_DOUBLE(o);
891 unsigned char* p = (unsigned char*) &d;
892 /* all we need is to make the tuple different in either the 0.0
893 * or -0.0 case from all others, just to avoid the "coercion".
894 */
895 if (*p==0 && p[sizeof(double)-1]==0)
896 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
897 else
898 t = PyTuple_Pack(2, o, o->ob_type);
899 } else {
900 t = PyTuple_Pack(2, o, o->ob_type);
901 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000902 if (t == NULL)
903 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000904
905 v = PyDict_GetItem(dict, t);
906 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000907 if (PyErr_Occurred())
908 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000909 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000910 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000911 if (!v) {
912 Py_DECREF(t);
913 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000914 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915 if (PyDict_SetItem(dict, t, v) < 0) {
916 Py_DECREF(t);
917 Py_DECREF(v);
918 return -1;
919 }
920 Py_DECREF(v);
921 }
922 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000923 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000925 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926}
927
928static int
929compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
930 PyObject *o)
931{
932 int arg = compiler_add_o(c, dict, o);
933 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000934 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935 return compiler_addop_i(c, opcode, arg);
936}
937
938static int
939compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000940 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941{
942 int arg;
943 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
944 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000945 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946 arg = compiler_add_o(c, dict, mangled);
947 Py_DECREF(mangled);
948 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000949 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000950 return compiler_addop_i(c, opcode, arg);
951}
952
953/* Add an opcode with an integer argument.
954 Returns 0 on failure, 1 on success.
955*/
956
957static int
958compiler_addop_i(struct compiler *c, int opcode, int oparg)
959{
960 struct instr *i;
961 int off;
962 off = compiler_next_instr(c, c->u->u_curblock);
963 if (off < 0)
964 return 0;
965 i = &c->u->u_curblock->b_instr[off];
966 i->i_opcode = opcode;
967 i->i_oparg = oparg;
968 i->i_hasarg = 1;
969 compiler_set_lineno(c, off);
970 return 1;
971}
972
973static int
974compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
975{
976 struct instr *i;
977 int off;
978
979 assert(b != NULL);
980 off = compiler_next_instr(c, c->u->u_curblock);
981 if (off < 0)
982 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983 i = &c->u->u_curblock->b_instr[off];
984 i->i_opcode = opcode;
985 i->i_target = b;
986 i->i_hasarg = 1;
987 if (absolute)
988 i->i_jabs = 1;
989 else
990 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000991 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992 return 1;
993}
994
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000995/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
996 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997 it as the current block. NEXT_BLOCK() also creates an implicit jump
998 from the current block to the new block.
999*/
1000
Thomas Wouters89f507f2006-12-13 04:49:30 +00001001/* The returns inside these macros make it impossible to decref objects
1002 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003*/
1004
1005
1006#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001007 if (compiler_use_new_block((C)) == NULL) \
1008 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009}
1010
1011#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001012 if (compiler_next_block((C)) == NULL) \
1013 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001014}
1015
1016#define ADDOP(C, OP) { \
1017 if (!compiler_addop((C), (OP))) \
1018 return 0; \
1019}
1020
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001021#define ADDOP_IN_SCOPE(C, OP) { \
1022 if (!compiler_addop((C), (OP))) { \
1023 compiler_exit_scope(c); \
1024 return 0; \
1025 } \
1026}
1027
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028#define ADDOP_O(C, OP, O, TYPE) { \
1029 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1030 return 0; \
1031}
1032
1033#define ADDOP_NAME(C, OP, O, TYPE) { \
1034 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1035 return 0; \
1036}
1037
1038#define ADDOP_I(C, OP, O) { \
1039 if (!compiler_addop_i((C), (OP), (O))) \
1040 return 0; \
1041}
1042
1043#define ADDOP_JABS(C, OP, O) { \
1044 if (!compiler_addop_j((C), (OP), (O), 1)) \
1045 return 0; \
1046}
1047
1048#define ADDOP_JREL(C, OP, O) { \
1049 if (!compiler_addop_j((C), (OP), (O), 0)) \
1050 return 0; \
1051}
1052
1053/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1054 the ASDL name to synthesize the name of the C type and the visit function.
1055*/
1056
1057#define VISIT(C, TYPE, V) {\
1058 if (!compiler_visit_ ## TYPE((C), (V))) \
1059 return 0; \
1060}
1061
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001062#define VISIT_IN_SCOPE(C, TYPE, V) {\
1063 if (!compiler_visit_ ## TYPE((C), (V))) { \
1064 compiler_exit_scope(c); \
1065 return 0; \
1066 } \
1067}
1068
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069#define VISIT_SLICE(C, V, CTX) {\
1070 if (!compiler_visit_slice((C), (V), (CTX))) \
1071 return 0; \
1072}
1073
1074#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001075 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001077 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001078 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079 if (!compiler_visit_ ## TYPE((C), elt)) \
1080 return 0; \
1081 } \
1082}
1083
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001084#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001085 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001086 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001087 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001088 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001089 if (!compiler_visit_ ## TYPE((C), elt)) { \
1090 compiler_exit_scope(c); \
1091 return 0; \
1092 } \
1093 } \
1094}
1095
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096static int
1097compiler_isdocstring(stmt_ty s)
1098{
1099 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001100 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001101 return s->v.Expr.value->kind == Str_kind;
1102}
1103
1104/* Compile a sequence of statements, checking for a docstring. */
1105
1106static int
1107compiler_body(struct compiler *c, asdl_seq *stmts)
1108{
1109 int i = 0;
1110 stmt_ty st;
1111
1112 if (!asdl_seq_LEN(stmts))
1113 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001114 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001115 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1116 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117 i = 1;
1118 VISIT(c, expr, st->v.Expr.value);
1119 if (!compiler_nameop(c, __doc__, Store))
1120 return 0;
1121 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001122 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001123 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124 return 1;
1125}
1126
1127static PyCodeObject *
1128compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001129{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001130 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001131 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132 static PyObject *module;
1133 if (!module) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001134 module = PyUnicode_FromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 if (!module)
1136 return NULL;
1137 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001138 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1139 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001140 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141 switch (mod->kind) {
1142 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001143 if (!compiler_body(c, mod->v.Module.body)) {
1144 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001146 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147 break;
1148 case Interactive_kind:
1149 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001150 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001151 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 break;
1153 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001154 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001155 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 break;
1157 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001158 PyErr_SetString(PyExc_SystemError,
1159 "suite should not be possible");
1160 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001161 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001162 PyErr_Format(PyExc_SystemError,
1163 "module kind %d should not be possible",
1164 mod->kind);
1165 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 co = assemble(c, addNone);
1168 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001169 return co;
1170}
1171
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172/* The test for LOCAL must come before the test for FREE in order to
1173 handle classes where name is both local and free. The local var is
1174 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001175*/
1176
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177static int
1178get_ref_type(struct compiler *c, PyObject *name)
1179{
1180 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001181 if (scope == 0) {
1182 char buf[350];
1183 PyOS_snprintf(buf, sizeof(buf),
1184 "unknown scope for %.100s in %.100s(%s) in %s\n"
1185 "symbols: %s\nlocals: %s\nglobals: %s\n",
1186 PyString_AS_STRING(name),
1187 PyString_AS_STRING(c->u->u_name),
1188 PyObject_REPR(c->u->u_ste->ste_id),
1189 c->c_filename,
1190 PyObject_REPR(c->u->u_ste->ste_symbols),
1191 PyObject_REPR(c->u->u_varnames),
1192 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001194 Py_FatalError(buf);
1195 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001196
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001197 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198}
1199
1200static int
1201compiler_lookup_arg(PyObject *dict, PyObject *name)
1202{
1203 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001204 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001206 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001208 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001210 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001211 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212}
1213
1214static int
1215compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1216{
1217 int i, free = PyCode_GetNumFree(co);
1218 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001219 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1220 ADDOP_I(c, MAKE_FUNCTION, args);
1221 return 1;
1222 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223 for (i = 0; i < free; ++i) {
1224 /* Bypass com_addop_varname because it will generate
1225 LOAD_DEREF but LOAD_CLOSURE is needed.
1226 */
1227 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1228 int arg, reftype;
1229
1230 /* Special case: If a class contains a method with a
1231 free variable that has the same name as a method,
1232 the name will be considered free *and* local in the
1233 class. It should be handled by the closure, as
1234 well as by the normal name loookup logic.
1235 */
1236 reftype = get_ref_type(c, name);
1237 if (reftype == CELL)
1238 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1239 else /* (reftype == FREE) */
1240 arg = compiler_lookup_arg(c->u->u_freevars, name);
1241 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001242 fprintf(stderr,
1243 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 "freevars of %s: %s\n",
1245 PyObject_REPR(name),
1246 PyString_AS_STRING(c->u->u_name),
1247 reftype, arg,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001248 PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249 PyObject_REPR(co->co_freevars));
1250 Py_FatalError("compiler_make_closure()");
1251 }
1252 ADDOP_I(c, LOAD_CLOSURE, arg);
1253 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001254 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001256 ADDOP_I(c, MAKE_CLOSURE, args);
1257 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258}
1259
1260static int
1261compiler_decorators(struct compiler *c, asdl_seq* decos)
1262{
1263 int i;
1264
1265 if (!decos)
1266 return 1;
1267
1268 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001269 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270 }
1271 return 1;
1272}
1273
1274static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001275compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1276 asdl_seq *kw_defaults)
1277{
1278 int i, default_count = 0;
1279 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001280 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001281 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1282 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001283 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001284 if (!compiler_visit_expr(c, default_)) {
1285 return -1;
1286 }
1287 default_count++;
1288 }
1289 }
1290 return default_count;
1291}
1292
1293static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001294compiler_visit_argannotation(struct compiler *c, identifier id,
1295 expr_ty annotation, PyObject *names)
1296{
1297 if (annotation) {
1298 VISIT(c, expr, annotation);
1299 if (PyList_Append(names, id))
1300 return -1;
1301 }
1302 return 0;
1303}
1304
1305static int
1306compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1307 PyObject *names)
1308{
1309 int i, error;
1310 for (i = 0; i < asdl_seq_LEN(args); i++) {
1311 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001312 error = compiler_visit_argannotation(
1313 c,
1314 arg->arg,
1315 arg->annotation,
1316 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001317 if (error)
1318 return error;
1319 }
1320 return 0;
1321}
1322
1323static int
1324compiler_visit_annotations(struct compiler *c, arguments_ty args,
1325 expr_ty returns)
1326{
Guido van Rossum0240b922007-02-26 21:23:50 +00001327 /* Push arg annotations and a list of the argument names. Return the #
1328 of items pushed. The expressions are evaluated out-of-order wrt the
1329 source code.
1330
1331 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1332 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001333 static identifier return_str;
1334 PyObject *names;
1335 int len;
1336 names = PyList_New(0);
1337 if (!names)
1338 return -1;
1339
1340 if (compiler_visit_argannotations(c, args->args, names))
1341 goto error;
1342 if (args->varargannotation &&
1343 compiler_visit_argannotation(c, args->vararg,
1344 args->varargannotation, names))
1345 goto error;
1346 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1347 goto error;
1348 if (args->kwargannotation &&
1349 compiler_visit_argannotation(c, args->kwarg,
1350 args->kwargannotation, names))
1351 goto error;
1352
1353 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001354 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001355 if (!return_str)
1356 goto error;
1357 }
1358 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1359 goto error;
1360 }
1361
1362 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001363 if (len > 65534) {
1364 /* len must fit in 16 bits, and len is incremented below */
1365 PyErr_SetString(PyExc_SyntaxError,
1366 "too many annotations");
1367 goto error;
1368 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001369 if (len) {
1370 /* convert names to a tuple and place on stack */
1371 PyObject *elt;
1372 int i;
1373 PyObject *s = PyTuple_New(len);
1374 if (!s)
1375 goto error;
1376 for (i = 0; i < len; i++) {
1377 elt = PyList_GET_ITEM(names, i);
1378 Py_INCREF(elt);
1379 PyTuple_SET_ITEM(s, i, elt);
1380 }
1381 ADDOP_O(c, LOAD_CONST, s, consts);
1382 Py_DECREF(s);
1383 len++; /* include the just-pushed tuple */
1384 }
1385 Py_DECREF(names);
1386 return len;
1387
1388error:
1389 Py_DECREF(names);
1390 return -1;
1391}
1392
1393static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394compiler_function(struct compiler *c, stmt_ty s)
1395{
1396 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001397 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001399 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001400 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001401 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001402 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001403 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404
1405 assert(s->kind == FunctionDef_kind);
1406
1407 if (!compiler_decorators(c, decos))
1408 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001409 if (args->kwonlyargs) {
1410 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1411 args->kw_defaults);
1412 if (res < 0)
1413 return 0;
1414 kw_default_count = res;
1415 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416 if (args->defaults)
1417 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001418 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001419 if (num_annotations < 0)
1420 return 0;
1421 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001422
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1424 s->lineno))
1425 return 0;
1426
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001427 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001428 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001429 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001430 first_const = st->v.Expr.value->v.Str.s;
1431 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001432 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001433 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001434 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001437 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001439 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001441 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1442 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 }
1444 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001445 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 if (co == NULL)
1447 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448
Guido van Rossum4f72a782006-10-27 23:31:49 +00001449 arglength = asdl_seq_LEN(args->defaults);
1450 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001451 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001452 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001453 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454
Neal Norwitzc1505362006-12-28 06:47:50 +00001455 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1457 ADDOP_I(c, CALL_FUNCTION, 1);
1458 }
1459
1460 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1461}
1462
1463static int
1464compiler_class(struct compiler *c, stmt_ty s)
1465{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001466 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001468 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001469 PySTEntryObject *ste;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001470 int err, i;
1471 asdl_seq* decos = s->v.ClassDef.decorator_list;
1472
1473 if (!compiler_decorators(c, decos))
1474 return 0;
1475
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001476 /* initialize statics */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001477 if (locals == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001478 locals = PyUnicode_FromString("__locals__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001479 if (locals == NULL)
1480 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001481 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001483 /* ultimately generate code for:
1484 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1485 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001486 <func> is a function/closure created from the class body;
1487 it has a single argument (__locals__) where the dict
1488 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001489 <name> is the class name
1490 <bases> is the positional arguments and *varargs argument
1491 <keywords> is the keyword arguments and **kwds argument
1492 This borrows from compiler_call.
1493 */
1494
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001495 /* 0. Create a fake argument named __locals__ */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001496 ste = PySymtable_Lookup(c->c_st, s);
1497 if (ste == NULL)
1498 return 0;
1499 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001500 err = PyList_Append(ste->ste_varnames, locals);
1501 Py_DECREF(ste);
1502 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001503 return 0;
1504
1505 /* 1. compile the class body into a code object */
1506 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1507 return 0;
1508 /* this block represents what we do in the new scope */
1509 {
1510 /* use the class name for name mangling */
1511 Py_INCREF(s->v.ClassDef.name);
1512 c->u->u_private = s->v.ClassDef.name;
1513 /* force it to have one mandatory argument */
1514 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001515 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001516 ADDOP_I(c, LOAD_FAST, 0);
1517 /* ... and store it into f_locals */
1518 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001519 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001520 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001521 if (!str || !compiler_nameop(c, str, Load)) {
1522 Py_XDECREF(str);
1523 compiler_exit_scope(c);
1524 return 0;
1525 }
1526 Py_DECREF(str);
1527 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001528 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001529 if (!str || !compiler_nameop(c, str, Store)) {
1530 Py_XDECREF(str);
1531 compiler_exit_scope(c);
1532 return 0;
1533 }
1534 Py_DECREF(str);
1535 /* compile the body proper */
1536 if (!compiler_body(c, s->v.ClassDef.body)) {
1537 compiler_exit_scope(c);
1538 return 0;
1539 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001540 /* return the (empty) __class__ cell */
1541 str = PyUnicode_InternFromString("__class__");
1542 if (str == NULL) {
1543 compiler_exit_scope(c);
1544 return 0;
1545 }
1546 i = compiler_lookup_arg(c->u->u_cellvars, str);
1547 Py_DECREF(str);
1548 if (i == -1) {
1549 /* This happens when nobody references the cell */
1550 PyErr_Clear();
1551 /* Return None */
1552 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1553 }
1554 else {
1555 /* Return the cell where to store __class__ */
1556 ADDOP_I(c, LOAD_CLOSURE, i);
1557 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001558 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1559 /* create the code object */
1560 co = assemble(c, 1);
1561 }
1562 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001563 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001564 if (co == NULL)
1565 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001567 /* 2. load the 'build_class' function */
1568 ADDOP(c, LOAD_BUILD_CLASS);
1569
1570 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001571 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001572 Py_DECREF(co);
1573
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001574 /* 4. load class name */
1575 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1576
1577 /* 5. generate the rest of the code for the call */
1578 if (!compiler_call_helper(c, 2,
1579 s->v.ClassDef.bases,
1580 s->v.ClassDef.keywords,
1581 s->v.ClassDef.starargs,
1582 s->v.ClassDef.kwargs))
1583 return 0;
1584
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001585 /* 6. apply decorators */
1586 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1587 ADDOP_I(c, CALL_FUNCTION, 1);
1588 }
1589
1590 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1592 return 0;
1593 return 1;
1594}
1595
1596static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001597compiler_ifexp(struct compiler *c, expr_ty e)
1598{
1599 basicblock *end, *next;
1600
1601 assert(e->kind == IfExp_kind);
1602 end = compiler_new_block(c);
1603 if (end == NULL)
1604 return 0;
1605 next = compiler_new_block(c);
1606 if (next == NULL)
1607 return 0;
1608 VISIT(c, expr, e->v.IfExp.test);
1609 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1610 ADDOP(c, POP_TOP);
1611 VISIT(c, expr, e->v.IfExp.body);
1612 ADDOP_JREL(c, JUMP_FORWARD, end);
1613 compiler_use_next_block(c, next);
1614 ADDOP(c, POP_TOP);
1615 VISIT(c, expr, e->v.IfExp.orelse);
1616 compiler_use_next_block(c, end);
1617 return 1;
1618}
1619
1620static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621compiler_lambda(struct compiler *c, expr_ty e)
1622{
1623 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001624 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001625 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626 arguments_ty args = e->v.Lambda.args;
1627 assert(e->kind == Lambda_kind);
1628
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001629 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001630 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001631 if (!name)
1632 return 0;
1633 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001634
Guido van Rossum4f72a782006-10-27 23:31:49 +00001635 if (args->kwonlyargs) {
1636 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1637 args->kw_defaults);
1638 if (res < 0) return 0;
1639 kw_default_count = res;
1640 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001641 if (args->defaults)
1642 VISIT_SEQ(c, expr, args->defaults);
1643 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1644 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001645
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001647 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001648 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1649 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001650 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001651 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652 if (co == NULL)
1653 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654
Guido van Rossum4f72a782006-10-27 23:31:49 +00001655 arglength = asdl_seq_LEN(args->defaults);
1656 arglength |= kw_default_count << 8;
1657 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001658 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001659
1660 return 1;
1661}
1662
1663static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001664compiler_if(struct compiler *c, stmt_ty s)
1665{
1666 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001667 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668 assert(s->kind == If_kind);
1669 end = compiler_new_block(c);
1670 if (end == NULL)
1671 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001672 next = compiler_new_block(c);
1673 if (next == NULL)
1674 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001675
1676 constant = expr_constant(s->v.If.test);
1677 /* constant = 0: "if 0"
1678 * constant = 1: "if 1", "if 2", ...
1679 * constant = -1: rest */
1680 if (constant == 0) {
1681 if (s->v.If.orelse)
1682 VISIT_SEQ(c, stmt, s->v.If.orelse);
1683 } else if (constant == 1) {
1684 VISIT_SEQ(c, stmt, s->v.If.body);
1685 } else {
1686 VISIT(c, expr, s->v.If.test);
1687 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1688 ADDOP(c, POP_TOP);
1689 VISIT_SEQ(c, stmt, s->v.If.body);
1690 ADDOP_JREL(c, JUMP_FORWARD, end);
1691 compiler_use_next_block(c, next);
1692 ADDOP(c, POP_TOP);
1693 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001694 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 compiler_use_next_block(c, end);
1697 return 1;
1698}
1699
1700static int
1701compiler_for(struct compiler *c, stmt_ty s)
1702{
1703 basicblock *start, *cleanup, *end;
1704
1705 start = compiler_new_block(c);
1706 cleanup = compiler_new_block(c);
1707 end = compiler_new_block(c);
1708 if (start == NULL || end == NULL || cleanup == NULL)
1709 return 0;
1710 ADDOP_JREL(c, SETUP_LOOP, end);
1711 if (!compiler_push_fblock(c, LOOP, start))
1712 return 0;
1713 VISIT(c, expr, s->v.For.iter);
1714 ADDOP(c, GET_ITER);
1715 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001716 /* XXX(nnorwitz): is there a better way to handle this?
1717 for loops are special, we want to be able to trace them
1718 each time around, so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001719 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001720 ADDOP_JREL(c, FOR_ITER, cleanup);
1721 VISIT(c, expr, s->v.For.target);
1722 VISIT_SEQ(c, stmt, s->v.For.body);
1723 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1724 compiler_use_next_block(c, cleanup);
1725 ADDOP(c, POP_BLOCK);
1726 compiler_pop_fblock(c, LOOP, start);
1727 VISIT_SEQ(c, stmt, s->v.For.orelse);
1728 compiler_use_next_block(c, end);
1729 return 1;
1730}
1731
1732static int
1733compiler_while(struct compiler *c, stmt_ty s)
1734{
1735 basicblock *loop, *orelse, *end, *anchor = NULL;
1736 int constant = expr_constant(s->v.While.test);
1737
1738 if (constant == 0)
1739 return 1;
1740 loop = compiler_new_block(c);
1741 end = compiler_new_block(c);
1742 if (constant == -1) {
1743 anchor = compiler_new_block(c);
1744 if (anchor == NULL)
1745 return 0;
1746 }
1747 if (loop == NULL || end == NULL)
1748 return 0;
1749 if (s->v.While.orelse) {
1750 orelse = compiler_new_block(c);
1751 if (orelse == NULL)
1752 return 0;
1753 }
1754 else
1755 orelse = NULL;
1756
1757 ADDOP_JREL(c, SETUP_LOOP, end);
1758 compiler_use_next_block(c, loop);
1759 if (!compiler_push_fblock(c, LOOP, loop))
1760 return 0;
1761 if (constant == -1) {
1762 VISIT(c, expr, s->v.While.test);
1763 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1764 ADDOP(c, POP_TOP);
1765 }
1766 VISIT_SEQ(c, stmt, s->v.While.body);
1767 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1768
1769 /* XXX should the two POP instructions be in a separate block
1770 if there is no else clause ?
1771 */
1772
1773 if (constant == -1) {
1774 compiler_use_next_block(c, anchor);
1775 ADDOP(c, POP_TOP);
1776 ADDOP(c, POP_BLOCK);
1777 }
1778 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001779 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 VISIT_SEQ(c, stmt, s->v.While.orelse);
1781 compiler_use_next_block(c, end);
1782
1783 return 1;
1784}
1785
1786static int
1787compiler_continue(struct compiler *c)
1788{
1789 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001790 static const char IN_FINALLY_ERROR_MSG[] =
1791 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 int i;
1793
1794 if (!c->u->u_nfblocks)
1795 return compiler_error(c, LOOP_ERROR_MSG);
1796 i = c->u->u_nfblocks - 1;
1797 switch (c->u->u_fblock[i].fb_type) {
1798 case LOOP:
1799 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1800 break;
1801 case EXCEPT:
1802 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001803 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1804 /* Prevent continue anywhere under a finally
1805 even if hidden in a sub-try or except. */
1806 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1807 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1808 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 if (i == -1)
1810 return compiler_error(c, LOOP_ERROR_MSG);
1811 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1812 break;
1813 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001814 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815 }
1816
1817 return 1;
1818}
1819
1820/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1821
1822 SETUP_FINALLY L
1823 <code for body>
1824 POP_BLOCK
1825 LOAD_CONST <None>
1826 L: <code for finalbody>
1827 END_FINALLY
1828
1829 The special instructions use the block stack. Each block
1830 stack entry contains the instruction that created it (here
1831 SETUP_FINALLY), the level of the value stack at the time the
1832 block stack entry was created, and a label (here L).
1833
1834 SETUP_FINALLY:
1835 Pushes the current value stack level and the label
1836 onto the block stack.
1837 POP_BLOCK:
1838 Pops en entry from the block stack, and pops the value
1839 stack until its level is the same as indicated on the
1840 block stack. (The label is ignored.)
1841 END_FINALLY:
1842 Pops a variable number of entries from the *value* stack
1843 and re-raises the exception they specify. The number of
1844 entries popped depends on the (pseudo) exception type.
1845
1846 The block stack is unwound when an exception is raised:
1847 when a SETUP_FINALLY entry is found, the exception is pushed
1848 onto the value stack (and the exception condition is cleared),
1849 and the interpreter jumps to the label gotten from the block
1850 stack.
1851*/
1852
1853static int
1854compiler_try_finally(struct compiler *c, stmt_ty s)
1855{
1856 basicblock *body, *end;
1857 body = compiler_new_block(c);
1858 end = compiler_new_block(c);
1859 if (body == NULL || end == NULL)
1860 return 0;
1861
1862 ADDOP_JREL(c, SETUP_FINALLY, end);
1863 compiler_use_next_block(c, body);
1864 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1865 return 0;
1866 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1867 ADDOP(c, POP_BLOCK);
1868 compiler_pop_fblock(c, FINALLY_TRY, body);
1869
1870 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1871 compiler_use_next_block(c, end);
1872 if (!compiler_push_fblock(c, FINALLY_END, end))
1873 return 0;
1874 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1875 ADDOP(c, END_FINALLY);
1876 compiler_pop_fblock(c, FINALLY_END, end);
1877
1878 return 1;
1879}
1880
1881/*
1882 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1883 (The contents of the value stack is shown in [], with the top
1884 at the right; 'tb' is trace-back info, 'val' the exception's
1885 associated value, and 'exc' the exception.)
1886
1887 Value stack Label Instruction Argument
1888 [] SETUP_EXCEPT L1
1889 [] <code for S>
1890 [] POP_BLOCK
1891 [] JUMP_FORWARD L0
1892
1893 [tb, val, exc] L1: DUP )
1894 [tb, val, exc, exc] <evaluate E1> )
1895 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1896 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1897 [tb, val, exc, 1] POP )
1898 [tb, val, exc] POP
1899 [tb, val] <assign to V1> (or POP if no V1)
1900 [tb] POP
1901 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001902 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903
1904 [tb, val, exc, 0] L2: POP
1905 [tb, val, exc] DUP
1906 .............................etc.......................
1907
1908 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001909 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910
1911 [] L0: <next statement>
1912
1913 Of course, parts are not generated if Vi or Ei is not present.
1914*/
1915static int
1916compiler_try_except(struct compiler *c, stmt_ty s)
1917{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001918 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919 int i, n;
1920
1921 body = compiler_new_block(c);
1922 except = compiler_new_block(c);
1923 orelse = compiler_new_block(c);
1924 end = compiler_new_block(c);
1925 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1926 return 0;
1927 ADDOP_JREL(c, SETUP_EXCEPT, except);
1928 compiler_use_next_block(c, body);
1929 if (!compiler_push_fblock(c, EXCEPT, body))
1930 return 0;
1931 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1932 ADDOP(c, POP_BLOCK);
1933 compiler_pop_fblock(c, EXCEPT, body);
1934 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1935 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1936 compiler_use_next_block(c, except);
1937 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001938 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939 s->v.TryExcept.handlers, i);
1940 if (!handler->type && i < n-1)
1941 return compiler_error(c, "default 'except:' must be last");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001942 c->u->u_lineno_set = 0;
1943 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944 except = compiler_new_block(c);
1945 if (except == NULL)
1946 return 0;
1947 if (handler->type) {
1948 ADDOP(c, DUP_TOP);
1949 VISIT(c, expr, handler->type);
1950 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1951 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1952 ADDOP(c, POP_TOP);
1953 }
1954 ADDOP(c, POP_TOP);
1955 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001956 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001957
1958 cleanup_end = compiler_new_block(c);
1959 cleanup_body = compiler_new_block(c);
1960 if(!(cleanup_end || cleanup_body))
1961 return 0;
1962
Guido van Rossum16be03e2007-01-10 18:51:35 +00001963 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001964 ADDOP(c, POP_TOP);
1965
1966 /*
1967 try:
1968 # body
1969 except type as name:
1970 try:
1971 # body
1972 finally:
1973 name = None
1974 del name
1975 */
1976
1977 /* second try: */
1978 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
1979 compiler_use_next_block(c, cleanup_body);
1980 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
1981 return 0;
1982
1983 /* second # body */
1984 VISIT_SEQ(c, stmt, handler->body);
1985 ADDOP(c, POP_BLOCK);
1986 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
1987
1988 /* finally: */
1989 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1990 compiler_use_next_block(c, cleanup_end);
1991 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
1992 return 0;
1993
1994 /* name = None */
1995 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00001996 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001997
Guido van Rossum16be03e2007-01-10 18:51:35 +00001998 /* del name */
1999 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002000
2001 ADDOP(c, END_FINALLY);
2002 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002003 }
2004 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00002005 ADDOP(c, POP_TOP);
2006 ADDOP(c, POP_TOP);
2007 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009 ADDOP_JREL(c, JUMP_FORWARD, end);
2010 compiler_use_next_block(c, except);
2011 if (handler->type)
2012 ADDOP(c, POP_TOP);
2013 }
2014 ADDOP(c, END_FINALLY);
2015 compiler_use_next_block(c, orelse);
2016 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2017 compiler_use_next_block(c, end);
2018 return 1;
2019}
2020
2021static int
2022compiler_import_as(struct compiler *c, identifier name, identifier asname)
2023{
2024 /* The IMPORT_NAME opcode was already generated. This function
2025 merely needs to bind the result to a name.
2026
2027 If there is a dot in name, we need to split it and emit a
2028 LOAD_ATTR for each name.
2029 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002030 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2031 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032 if (dot) {
2033 /* Consume the base module name to get the first attribute */
2034 src = dot + 1;
2035 while (dot) {
2036 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002037 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002038 dot = Py_UNICODE_strchr(src, '.');
2039 attr = PyUnicode_FromUnicode(src,
2040 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002041 if (!attr)
2042 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002043 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002044 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002045 src = dot + 1;
2046 }
2047 }
2048 return compiler_nameop(c, asname, Store);
2049}
2050
2051static int
2052compiler_import(struct compiler *c, stmt_ty s)
2053{
2054 /* The Import node stores a module name like a.b.c as a single
2055 string. This is convenient for all cases except
2056 import a.b.c as d
2057 where we need to parse that string to extract the individual
2058 module names.
2059 XXX Perhaps change the representation to make this case simpler?
2060 */
2061 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002062
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002064 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002066 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067
Christian Heimes217cfd12007-12-02 14:31:20 +00002068 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002069 if (level == NULL)
2070 return 0;
2071
2072 ADDOP_O(c, LOAD_CONST, level, consts);
2073 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2075 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2076
2077 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002078 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 if (!r)
2080 return r;
2081 }
2082 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002084 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2085 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002087 tmp = PyUnicode_FromUnicode(base,
2088 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 r = compiler_nameop(c, tmp, Store);
2090 if (dot) {
2091 Py_DECREF(tmp);
2092 }
2093 if (!r)
2094 return r;
2095 }
2096 }
2097 return 1;
2098}
2099
2100static int
2101compiler_from_import(struct compiler *c, stmt_ty s)
2102{
2103 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104
2105 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002106 PyObject *level;
2107
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 if (!names)
2109 return 0;
2110
Christian Heimes217cfd12007-12-02 14:31:20 +00002111 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002112 if (!level) {
2113 Py_DECREF(names);
2114 return 0;
2115 }
2116
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 /* build up the names */
2118 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002119 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120 Py_INCREF(alias->name);
2121 PyTuple_SET_ITEM(names, i, alias->name);
2122 }
2123
2124 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002125 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2126 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002127 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 Py_DECREF(names);
2129 return compiler_error(c,
2130 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002131 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132
2133 }
2134 }
2135
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002136 ADDOP_O(c, LOAD_CONST, level, consts);
2137 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002139 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2141 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002142 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143 identifier store_name;
2144
Martin v. Löwis5b222132007-06-10 09:51:05 +00002145 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 assert(n == 1);
2147 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002148 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 }
2150
2151 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2152 store_name = alias->name;
2153 if (alias->asname)
2154 store_name = alias->asname;
2155
2156 if (!compiler_nameop(c, store_name, Store)) {
2157 Py_DECREF(names);
2158 return 0;
2159 }
2160 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002161 /* remove imported module */
2162 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 return 1;
2164}
2165
2166static int
2167compiler_assert(struct compiler *c, stmt_ty s)
2168{
2169 static PyObject *assertion_error = NULL;
2170 basicblock *end;
2171
2172 if (Py_OptimizeFlag)
2173 return 1;
2174 if (assertion_error == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002175 assertion_error = PyUnicode_FromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 if (assertion_error == NULL)
2177 return 0;
2178 }
2179 VISIT(c, expr, s->v.Assert.test);
2180 end = compiler_new_block(c);
2181 if (end == NULL)
2182 return 0;
2183 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2184 ADDOP(c, POP_TOP);
2185 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2186 if (s->v.Assert.msg) {
2187 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002188 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189 }
Collin Winter828f04a2007-08-31 00:04:24 +00002190 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002191 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192 ADDOP(c, POP_TOP);
2193 return 1;
2194}
2195
2196static int
2197compiler_visit_stmt(struct compiler *c, stmt_ty s)
2198{
2199 int i, n;
2200
Thomas Wouters89f507f2006-12-13 04:49:30 +00002201 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002203 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002206 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002207 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002208 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002210 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211 if (c->u->u_ste->ste_type != FunctionBlock)
2212 return compiler_error(c, "'return' outside function");
2213 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002214 VISIT(c, expr, s->v.Return.value);
2215 }
2216 else
2217 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2218 ADDOP(c, RETURN_VALUE);
2219 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002220 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 VISIT_SEQ(c, expr, s->v.Delete.targets)
2222 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002223 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224 n = asdl_seq_LEN(s->v.Assign.targets);
2225 VISIT(c, expr, s->v.Assign.value);
2226 for (i = 0; i < n; i++) {
2227 if (i < n - 1)
2228 ADDOP(c, DUP_TOP);
2229 VISIT(c, expr,
2230 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2231 }
2232 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002233 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002235 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002237 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002239 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002241 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002243 if (s->v.Raise.exc) {
2244 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002246 if (s->v.Raise.cause) {
2247 VISIT(c, expr, s->v.Raise.cause);
2248 n++;
2249 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250 }
2251 ADDOP_I(c, RAISE_VARARGS, n);
2252 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002253 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002255 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002257 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002259 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002261 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002263 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002264 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002266 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002268 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269 ADDOP(c, PRINT_EXPR);
2270 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002271 else if (s->v.Expr.value->kind != Str_kind &&
2272 s->v.Expr.value->kind != Num_kind) {
2273 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 ADDOP(c, POP_TOP);
2275 }
2276 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002277 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002279 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002280 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281 return compiler_error(c, "'break' outside loop");
2282 ADDOP(c, BREAK_LOOP);
2283 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002284 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002286 case With_kind:
2287 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 }
2289 return 1;
2290}
2291
2292static int
2293unaryop(unaryop_ty op)
2294{
2295 switch (op) {
2296 case Invert:
2297 return UNARY_INVERT;
2298 case Not:
2299 return UNARY_NOT;
2300 case UAdd:
2301 return UNARY_POSITIVE;
2302 case USub:
2303 return UNARY_NEGATIVE;
2304 }
2305 return 0;
2306}
2307
2308static int
2309binop(struct compiler *c, operator_ty op)
2310{
2311 switch (op) {
2312 case Add:
2313 return BINARY_ADD;
2314 case Sub:
2315 return BINARY_SUBTRACT;
2316 case Mult:
2317 return BINARY_MULTIPLY;
2318 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002319 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 case Mod:
2321 return BINARY_MODULO;
2322 case Pow:
2323 return BINARY_POWER;
2324 case LShift:
2325 return BINARY_LSHIFT;
2326 case RShift:
2327 return BINARY_RSHIFT;
2328 case BitOr:
2329 return BINARY_OR;
2330 case BitXor:
2331 return BINARY_XOR;
2332 case BitAnd:
2333 return BINARY_AND;
2334 case FloorDiv:
2335 return BINARY_FLOOR_DIVIDE;
2336 }
2337 return 0;
2338}
2339
2340static int
2341cmpop(cmpop_ty op)
2342{
2343 switch (op) {
2344 case Eq:
2345 return PyCmp_EQ;
2346 case NotEq:
2347 return PyCmp_NE;
2348 case Lt:
2349 return PyCmp_LT;
2350 case LtE:
2351 return PyCmp_LE;
2352 case Gt:
2353 return PyCmp_GT;
2354 case GtE:
2355 return PyCmp_GE;
2356 case Is:
2357 return PyCmp_IS;
2358 case IsNot:
2359 return PyCmp_IS_NOT;
2360 case In:
2361 return PyCmp_IN;
2362 case NotIn:
2363 return PyCmp_NOT_IN;
2364 }
2365 return PyCmp_BAD;
2366}
2367
2368static int
2369inplace_binop(struct compiler *c, operator_ty op)
2370{
2371 switch (op) {
2372 case Add:
2373 return INPLACE_ADD;
2374 case Sub:
2375 return INPLACE_SUBTRACT;
2376 case Mult:
2377 return INPLACE_MULTIPLY;
2378 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002379 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380 case Mod:
2381 return INPLACE_MODULO;
2382 case Pow:
2383 return INPLACE_POWER;
2384 case LShift:
2385 return INPLACE_LSHIFT;
2386 case RShift:
2387 return INPLACE_RSHIFT;
2388 case BitOr:
2389 return INPLACE_OR;
2390 case BitXor:
2391 return INPLACE_XOR;
2392 case BitAnd:
2393 return INPLACE_AND;
2394 case FloorDiv:
2395 return INPLACE_FLOOR_DIVIDE;
2396 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002397 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002398 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399 return 0;
2400}
2401
2402static int
2403compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2404{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002405 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2407
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002408 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002409 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410 /* XXX AugStore isn't used anywhere! */
2411
2412 /* First check for assignment to __debug__. Param? */
2413 if ((ctx == Store || ctx == AugStore || ctx == Del)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002414 && !PyUnicode_CompareWithASCIIString(name, "__debug__")) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415 return compiler_error(c, "can not assign to __debug__");
2416 }
2417
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002418 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002419 if (!mangled)
2420 return 0;
2421
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422 op = 0;
2423 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002424 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425 switch (scope) {
2426 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002427 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 optype = OP_DEREF;
2429 break;
2430 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002431 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432 optype = OP_DEREF;
2433 break;
2434 case LOCAL:
2435 if (c->u->u_ste->ste_type == FunctionBlock)
2436 optype = OP_FAST;
2437 break;
2438 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002439 if (c->u->u_ste->ste_type == FunctionBlock &&
2440 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441 optype = OP_GLOBAL;
2442 break;
2443 case GLOBAL_EXPLICIT:
2444 optype = OP_GLOBAL;
2445 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002446 default:
2447 /* scope can be 0 */
2448 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002449 }
2450
2451 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002452 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453
2454 switch (optype) {
2455 case OP_DEREF:
2456 switch (ctx) {
2457 case Load: op = LOAD_DEREF; break;
2458 case Store: op = STORE_DEREF; break;
2459 case AugLoad:
2460 case AugStore:
2461 break;
2462 case Del:
2463 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002464 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002466 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002467 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002470 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002471 PyErr_SetString(PyExc_SystemError,
2472 "param invalid for deref variable");
2473 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 }
2475 break;
2476 case OP_FAST:
2477 switch (ctx) {
2478 case Load: op = LOAD_FAST; break;
2479 case Store: op = STORE_FAST; break;
2480 case Del: op = DELETE_FAST; break;
2481 case AugLoad:
2482 case AugStore:
2483 break;
2484 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002485 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002486 PyErr_SetString(PyExc_SystemError,
2487 "param invalid for local variable");
2488 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002490 ADDOP_O(c, op, mangled, varnames);
2491 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002492 return 1;
2493 case OP_GLOBAL:
2494 switch (ctx) {
2495 case Load: op = LOAD_GLOBAL; break;
2496 case Store: op = STORE_GLOBAL; break;
2497 case Del: op = DELETE_GLOBAL; break;
2498 case AugLoad:
2499 case AugStore:
2500 break;
2501 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002502 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002503 PyErr_SetString(PyExc_SystemError,
2504 "param invalid for global variable");
2505 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506 }
2507 break;
2508 case OP_NAME:
2509 switch (ctx) {
2510 case Load: op = LOAD_NAME; break;
2511 case Store: op = STORE_NAME; break;
2512 case Del: op = DELETE_NAME; break;
2513 case AugLoad:
2514 case AugStore:
2515 break;
2516 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002517 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002518 PyErr_SetString(PyExc_SystemError,
2519 "param invalid for name variable");
2520 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521 }
2522 break;
2523 }
2524
2525 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002526 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002527 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002528 if (arg < 0)
2529 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002530 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531}
2532
2533static int
2534compiler_boolop(struct compiler *c, expr_ty e)
2535{
2536 basicblock *end;
2537 int jumpi, i, n;
2538 asdl_seq *s;
2539
2540 assert(e->kind == BoolOp_kind);
2541 if (e->v.BoolOp.op == And)
2542 jumpi = JUMP_IF_FALSE;
2543 else
2544 jumpi = JUMP_IF_TRUE;
2545 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002546 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547 return 0;
2548 s = e->v.BoolOp.values;
2549 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002550 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002551 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002552 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553 ADDOP_JREL(c, jumpi, end);
2554 ADDOP(c, POP_TOP)
2555 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002556 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557 compiler_use_next_block(c, end);
2558 return 1;
2559}
2560
2561static int
2562compiler_list(struct compiler *c, expr_ty e)
2563{
2564 int n = asdl_seq_LEN(e->v.List.elts);
2565 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002566 int i, seen_star = 0;
2567 for (i = 0; i < n; i++) {
2568 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2569 if (elt->kind == Starred_kind && !seen_star) {
2570 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2571 seen_star = 1;
2572 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2573 } else if (elt->kind == Starred_kind) {
2574 return compiler_error(c,
2575 "two starred expressions in assignment");
2576 }
2577 }
2578 if (!seen_star) {
2579 ADDOP_I(c, UNPACK_SEQUENCE, n);
2580 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581 }
2582 VISIT_SEQ(c, expr, e->v.List.elts);
2583 if (e->v.List.ctx == Load) {
2584 ADDOP_I(c, BUILD_LIST, n);
2585 }
2586 return 1;
2587}
2588
2589static int
2590compiler_tuple(struct compiler *c, expr_ty e)
2591{
2592 int n = asdl_seq_LEN(e->v.Tuple.elts);
2593 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002594 int i, seen_star = 0;
2595 for (i = 0; i < n; i++) {
2596 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2597 if (elt->kind == Starred_kind && !seen_star) {
2598 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2599 seen_star = 1;
2600 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2601 } else if (elt->kind == Starred_kind) {
2602 return compiler_error(c,
2603 "two starred expressions in assignment");
2604 }
2605 }
2606 if (!seen_star) {
2607 ADDOP_I(c, UNPACK_SEQUENCE, n);
2608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 }
2610 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2611 if (e->v.Tuple.ctx == Load) {
2612 ADDOP_I(c, BUILD_TUPLE, n);
2613 }
2614 return 1;
2615}
2616
2617static int
2618compiler_compare(struct compiler *c, expr_ty e)
2619{
2620 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002621 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622
2623 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2624 VISIT(c, expr, e->v.Compare.left);
2625 n = asdl_seq_LEN(e->v.Compare.ops);
2626 assert(n > 0);
2627 if (n > 1) {
2628 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002629 if (cleanup == NULL)
2630 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002631 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002632 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 }
2634 for (i = 1; i < n; i++) {
2635 ADDOP(c, DUP_TOP);
2636 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002638 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002639 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2641 NEXT_BLOCK(c);
2642 ADDOP(c, POP_TOP);
2643 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002644 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002645 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002647 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002649 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 if (n > 1) {
2651 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 if (end == NULL)
2653 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 ADDOP_JREL(c, JUMP_FORWARD, end);
2655 compiler_use_next_block(c, cleanup);
2656 ADDOP(c, ROT_TWO);
2657 ADDOP(c, POP_TOP);
2658 compiler_use_next_block(c, end);
2659 }
2660 return 1;
2661}
2662
2663static int
2664compiler_call(struct compiler *c, expr_ty e)
2665{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002667 return compiler_call_helper(c, 0,
2668 e->v.Call.args,
2669 e->v.Call.keywords,
2670 e->v.Call.starargs,
2671 e->v.Call.kwargs);
2672}
2673
2674/* shared code between compiler_call and compiler_class */
2675static int
2676compiler_call_helper(struct compiler *c,
2677 int n, /* Args already pushed */
2678 asdl_seq *args,
2679 asdl_seq *keywords,
2680 expr_ty starargs,
2681 expr_ty kwargs)
2682{
2683 int code = 0;
2684
2685 n += asdl_seq_LEN(args);
2686 VISIT_SEQ(c, expr, args);
2687 if (keywords) {
2688 VISIT_SEQ(c, keyword, keywords);
2689 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002691 if (starargs) {
2692 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693 code |= 1;
2694 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002695 if (kwargs) {
2696 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 code |= 2;
2698 }
2699 switch (code) {
2700 case 0:
2701 ADDOP_I(c, CALL_FUNCTION, n);
2702 break;
2703 case 1:
2704 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2705 break;
2706 case 2:
2707 ADDOP_I(c, CALL_FUNCTION_KW, n);
2708 break;
2709 case 3:
2710 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2711 break;
2712 }
2713 return 1;
2714}
2715
Nick Coghlan650f0d02007-04-15 12:05:43 +00002716
2717/* List and set comprehensions and generator expressions work by creating a
2718 nested function to perform the actual iteration. This means that the
2719 iteration variables don't leak into the current scope.
2720 The defined function is called immediately following its definition, with the
2721 result of that call being the result of the expression.
2722 The LC/SC version returns the populated container, while the GE version is
2723 flagged in symtable.c as a generator, so it returns the generator object
2724 when the function is called.
2725 This code *knows* that the loop cannot contain break, continue, or return,
2726 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2727
2728 Possible cleanups:
2729 - iterate over the generator sequence instead of using recursion
2730*/
2731
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002733compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
2734 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002735 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736{
2737 /* generate code for the iterator, then each of the ifs,
2738 and then write to the element */
2739
Nick Coghlan650f0d02007-04-15 12:05:43 +00002740 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002742 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743
2744 start = compiler_new_block(c);
2745 skip = compiler_new_block(c);
2746 if_cleanup = compiler_new_block(c);
2747 anchor = compiler_new_block(c);
2748
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002749 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002750 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752
Nick Coghlan650f0d02007-04-15 12:05:43 +00002753 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755 if (gen_index == 0) {
2756 /* Receive outermost iter as an implicit argument */
2757 c->u->u_argcount = 1;
2758 ADDOP_I(c, LOAD_FAST, 0);
2759 }
2760 else {
2761 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002762 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763 ADDOP(c, GET_ITER);
2764 }
2765 compiler_use_next_block(c, start);
2766 ADDOP_JREL(c, FOR_ITER, anchor);
2767 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002768 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002770 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002771 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002773 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774 VISIT(c, expr, e);
2775 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2776 NEXT_BLOCK(c);
2777 ADDOP(c, POP_TOP);
2778 }
2779
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002780 if (++gen_index < asdl_seq_LEN(generators))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002781 if (!compiler_comprehension_generator(c, tmpname,
2782 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002783 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002784 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785
Nick Coghlan650f0d02007-04-15 12:05:43 +00002786 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002787 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002788 /* comprehension specific code */
2789 switch (type) {
2790 case COMP_GENEXP:
2791 VISIT(c, expr, elt);
2792 ADDOP(c, YIELD_VALUE);
2793 ADDOP(c, POP_TOP);
2794 break;
2795 case COMP_LISTCOMP:
2796 if (!compiler_nameop(c, tmpname, Load))
2797 return 0;
2798 VISIT(c, expr, elt);
2799 ADDOP(c, LIST_APPEND);
2800 break;
2801 case COMP_SETCOMP:
2802 if (!compiler_nameop(c, tmpname, Load))
2803 return 0;
2804 VISIT(c, expr, elt);
2805 ADDOP(c, SET_ADD);
2806 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002807 case COMP_DICTCOMP:
2808 if (!compiler_nameop(c, tmpname, Load))
2809 return 0;
2810 /* With 'd[k] = v', v is evaluated before k, so we do
2811 the same. STORE_SUBSCR requires (item, map, key),
2812 so we still end up ROTing once. */
2813 VISIT(c, expr, val);
2814 ADDOP(c, ROT_TWO);
2815 VISIT(c, expr, elt);
2816 ADDOP(c, STORE_SUBSCR);
2817 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002818 default:
2819 return 0;
2820 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821
2822 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002823 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824 for (i = 0; i < n; i++) {
2825 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002826 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002828
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829 ADDOP(c, POP_TOP);
2830 }
2831 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2832 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
2834 return 1;
2835}
2836
2837static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002838compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002839 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002840{
2841 PyCodeObject *co = NULL;
2842 identifier tmp = NULL;
2843 expr_ty outermost_iter;
2844
2845 outermost_iter = ((comprehension_ty)
2846 asdl_seq_GET(generators, 0))->iter;
2847
2848 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2849 goto error;
2850
2851 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002852 int op;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002853 tmp = compiler_new_tmpname(c);
2854 if (!tmp)
2855 goto error_in_scope;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002856 switch (type) {
2857 case COMP_LISTCOMP:
2858 op = BUILD_LIST;
2859 break;
2860 case COMP_SETCOMP:
2861 op = BUILD_SET;
2862 break;
2863 case COMP_DICTCOMP:
2864 op = BUILD_MAP;
2865 break;
2866 default:
2867 PyErr_Format(PyExc_SystemError,
2868 "unknown comprehension type %d", type);
2869 goto error_in_scope;
2870 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002871
Guido van Rossum992d4a32007-07-11 13:09:30 +00002872 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002873 ADDOP(c, DUP_TOP);
2874 if (!compiler_nameop(c, tmp, Store))
2875 goto error_in_scope;
2876 }
2877
Guido van Rossum992d4a32007-07-11 13:09:30 +00002878 if (!compiler_comprehension_generator(c, tmp, generators, 0, elt,
2879 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002880 goto error_in_scope;
2881
2882 if (type != COMP_GENEXP) {
2883 ADDOP(c, RETURN_VALUE);
2884 }
2885
2886 co = assemble(c, 1);
2887 compiler_exit_scope(c);
2888 if (co == NULL)
2889 goto error;
2890
2891 if (!compiler_make_closure(c, co, 0))
2892 goto error;
2893 Py_DECREF(co);
2894 Py_XDECREF(tmp);
2895
2896 VISIT(c, expr, outermost_iter);
2897 ADDOP(c, GET_ITER);
2898 ADDOP_I(c, CALL_FUNCTION, 1);
2899 return 1;
2900error_in_scope:
2901 compiler_exit_scope(c);
2902error:
2903 Py_XDECREF(co);
2904 Py_XDECREF(tmp);
2905 return 0;
2906}
2907
2908static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909compiler_genexp(struct compiler *c, expr_ty e)
2910{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002911 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002912 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002913 name = PyUnicode_FromString("<genexp>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002914 if (!name)
2915 return 0;
2916 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002917 assert(e->kind == GeneratorExp_kind);
2918 return compiler_comprehension(c, e, COMP_GENEXP, name,
2919 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002920 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921}
2922
2923static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002924compiler_listcomp(struct compiler *c, expr_ty e)
2925{
2926 static identifier name;
2927 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002928 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002929 if (!name)
2930 return 0;
2931 }
2932 assert(e->kind == ListComp_kind);
2933 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2934 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002935 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002936}
2937
2938static int
2939compiler_setcomp(struct compiler *c, expr_ty e)
2940{
2941 static identifier name;
2942 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002943 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002944 if (!name)
2945 return 0;
2946 }
2947 assert(e->kind == SetComp_kind);
2948 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2949 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002950 e->v.SetComp.elt, NULL);
2951}
2952
2953
2954static int
2955compiler_dictcomp(struct compiler *c, expr_ty e)
2956{
2957 static identifier name;
2958 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00002959 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00002960 if (!name)
2961 return 0;
2962 }
2963 assert(e->kind == DictComp_kind);
2964 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2965 e->v.DictComp.generators,
2966 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002967}
2968
2969
2970static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971compiler_visit_keyword(struct compiler *c, keyword_ty k)
2972{
2973 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2974 VISIT(c, expr, k->value);
2975 return 1;
2976}
2977
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002978/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979 whether they are true or false.
2980
2981 Return values: 1 for true, 0 for false, -1 for non-constant.
2982 */
2983
2984static int
2985expr_constant(expr_ty e)
2986{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002987 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002988 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00002989 case Ellipsis_kind:
2990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991 case Num_kind:
2992 return PyObject_IsTrue(e->v.Num.n);
2993 case Str_kind:
2994 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002995 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002996 /* optimize away names that can't be reassigned */
Guido van Rossumbdbb3952007-06-14 00:28:01 +00002997 id = PyString_AS_STRING(
2998 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002999 if (strcmp(id, "True") == 0) return 1;
3000 if (strcmp(id, "False") == 0) return 0;
3001 if (strcmp(id, "None") == 0) return 0;
3002 if (strcmp(id, "__debug__") == 0)
3003 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003004 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 default:
3006 return -1;
3007 }
3008}
3009
Guido van Rossumc2e20742006-02-27 22:32:47 +00003010/*
3011 Implements the with statement from PEP 343.
3012
3013 The semantics outlined in that PEP are as follows:
3014
3015 with EXPR as VAR:
3016 BLOCK
3017
3018 It is implemented roughly as:
3019
Thomas Wouters477c8d52006-05-27 19:21:47 +00003020 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003021 exit = context.__exit__ # not calling it
3022 value = context.__enter__()
3023 try:
3024 VAR = value # if VAR present in the syntax
3025 BLOCK
3026 finally:
3027 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003028 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003029 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003030 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003031 exit(*exc)
3032 */
3033static int
3034compiler_with(struct compiler *c, stmt_ty s)
3035{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003036 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003037 basicblock *block, *finally;
3038 identifier tmpexit, tmpvalue = NULL;
3039
3040 assert(s->kind == With_kind);
3041
Guido van Rossumc2e20742006-02-27 22:32:47 +00003042 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003043 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003044 if (!enter_attr)
3045 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003046 }
3047 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003048 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003049 if (!exit_attr)
3050 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003051 }
3052
3053 block = compiler_new_block(c);
3054 finally = compiler_new_block(c);
3055 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003056 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003057
3058 /* Create a temporary variable to hold context.__exit__ */
3059 tmpexit = compiler_new_tmpname(c);
3060 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003061 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003062 PyArena_AddPyObject(c->c_arena, tmpexit);
3063
3064 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003065 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003066 We need to do this rather than preserving it on the stack
3067 because SETUP_FINALLY remembers the stack level.
3068 We need to do the assignment *inside* the try/finally
3069 so that context.__exit__() is called when the assignment
3070 fails. But we need to call context.__enter__() *before*
3071 the try/finally so that if it fails we won't call
3072 context.__exit__().
3073 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075 if (tmpvalue == NULL)
3076 return 0;
3077 PyArena_AddPyObject(c->c_arena, tmpvalue);
3078 }
3079
Thomas Wouters477c8d52006-05-27 19:21:47 +00003080 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003082
3083 /* Squirrel away context.__exit__ */
3084 ADDOP(c, DUP_TOP);
3085 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3086 if (!compiler_nameop(c, tmpexit, Store))
3087 return 0;
3088
3089 /* Call context.__enter__() */
3090 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3091 ADDOP_I(c, CALL_FUNCTION, 0);
3092
3093 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003094 /* Store it in tmpvalue */
3095 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003096 return 0;
3097 }
3098 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003099 /* Discard result from context.__enter__() */
3100 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003101 }
3102
3103 /* Start the try block */
3104 ADDOP_JREL(c, SETUP_FINALLY, finally);
3105
3106 compiler_use_next_block(c, block);
3107 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003108 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003109 }
3110
3111 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003112 /* Bind saved result of context.__enter__() to VAR */
3113 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003114 !compiler_nameop(c, tmpvalue, Del))
3115 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003117 }
3118
3119 /* BLOCK code */
3120 VISIT_SEQ(c, stmt, s->v.With.body);
3121
3122 /* End of try block; start the finally block */
3123 ADDOP(c, POP_BLOCK);
3124 compiler_pop_fblock(c, FINALLY_TRY, block);
3125
3126 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3127 compiler_use_next_block(c, finally);
3128 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003129 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003130
3131 /* Finally block starts; push tmpexit and issue our magic opcode. */
3132 if (!compiler_nameop(c, tmpexit, Load) ||
3133 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003135 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003136
3137 /* Finally block ends. */
3138 ADDOP(c, END_FINALLY);
3139 compiler_pop_fblock(c, FINALLY_END, finally);
3140 return 1;
3141}
3142
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143static int
3144compiler_visit_expr(struct compiler *c, expr_ty e)
3145{
3146 int i, n;
3147
Thomas Wouters89f507f2006-12-13 04:49:30 +00003148 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003149 set a new line number for the next instruction.
3150 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151 if (e->lineno > c->u->u_lineno) {
3152 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003153 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154 }
3155 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 VISIT(c, expr, e->v.BinOp.left);
3160 VISIT(c, expr, e->v.BinOp.right);
3161 ADDOP(c, binop(c, e->v.BinOp.op));
3162 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003163 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164 VISIT(c, expr, e->v.UnaryOp.operand);
3165 ADDOP(c, unaryop(e->v.UnaryOp.op));
3166 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003169 case IfExp_kind:
3170 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003171 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003172 /* XXX get rid of arg? */
3173 ADDOP_I(c, BUILD_MAP, 0);
3174 n = asdl_seq_LEN(e->v.Dict.values);
3175 /* We must arrange things just right for STORE_SUBSCR.
3176 It wants the stack to look like (value) (dict) (key) */
3177 for (i = 0; i < n; i++) {
3178 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003179 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003180 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003182 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003183 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184 ADDOP(c, STORE_SUBSCR);
3185 }
3186 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003187 case Set_kind:
3188 n = asdl_seq_LEN(e->v.Set.elts);
3189 VISIT_SEQ(c, expr, e->v.Set.elts);
3190 ADDOP_I(c, BUILD_SET, n);
3191 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003194 case ListComp_kind:
3195 return compiler_listcomp(c, e);
3196 case SetComp_kind:
3197 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003198 case DictComp_kind:
3199 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200 case Yield_kind:
3201 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003202 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 if (e->v.Yield.value) {
3204 VISIT(c, expr, e->v.Yield.value);
3205 }
3206 else {
3207 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3208 }
3209 ADDOP(c, YIELD_VALUE);
3210 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003213 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003215 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3217 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003218 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3220 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003221 case Bytes_kind:
3222 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003223 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003224 case Ellipsis_kind:
3225 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3226 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003228 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229 if (e->v.Attribute.ctx != AugStore)
3230 VISIT(c, expr, e->v.Attribute.value);
3231 switch (e->v.Attribute.ctx) {
3232 case AugLoad:
3233 ADDOP(c, DUP_TOP);
3234 /* Fall through to load */
3235 case Load:
3236 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3237 break;
3238 case AugStore:
3239 ADDOP(c, ROT_TWO);
3240 /* Fall through to save */
3241 case Store:
3242 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3243 break;
3244 case Del:
3245 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3246 break;
3247 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003248 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003249 PyErr_SetString(PyExc_SystemError,
3250 "param invalid in attribute expression");
3251 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 }
3253 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003254 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255 switch (e->v.Subscript.ctx) {
3256 case AugLoad:
3257 VISIT(c, expr, e->v.Subscript.value);
3258 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3259 break;
3260 case Load:
3261 VISIT(c, expr, e->v.Subscript.value);
3262 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3263 break;
3264 case AugStore:
3265 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3266 break;
3267 case Store:
3268 VISIT(c, expr, e->v.Subscript.value);
3269 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3270 break;
3271 case Del:
3272 VISIT(c, expr, e->v.Subscript.value);
3273 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3274 break;
3275 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003276 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003277 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003278 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003279 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 }
3281 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003282 case Starred_kind:
3283 switch (e->v.Starred.ctx) {
3284 case Store:
3285 /* In all legitimate cases, the Starred node was already replaced
3286 * by compiler_list/compiler_tuple. XXX: is that okay? */
3287 return compiler_error(c,
3288 "starred assignment target must be in a list or tuple");
3289 default:
3290 return compiler_error(c,
3291 "can use starred expression only as assignment target");
3292 }
3293 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003294 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3296 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003297 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003299 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 return compiler_tuple(c, e);
3301 }
3302 return 1;
3303}
3304
3305static int
3306compiler_augassign(struct compiler *c, stmt_ty s)
3307{
3308 expr_ty e = s->v.AugAssign.target;
3309 expr_ty auge;
3310
3311 assert(s->kind == AugAssign_kind);
3312
3313 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003314 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003316 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003317 if (auge == NULL)
3318 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319 VISIT(c, expr, auge);
3320 VISIT(c, expr, s->v.AugAssign.value);
3321 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3322 auge->v.Attribute.ctx = AugStore;
3323 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 break;
3325 case Subscript_kind:
3326 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003327 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003328 if (auge == NULL)
3329 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330 VISIT(c, expr, auge);
3331 VISIT(c, expr, s->v.AugAssign.value);
3332 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003333 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003334 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003335 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003337 if (!compiler_nameop(c, e->v.Name.id, Load))
3338 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339 VISIT(c, expr, s->v.AugAssign.value);
3340 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3341 return compiler_nameop(c, e->v.Name.id, Store);
3342 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003343 PyErr_Format(PyExc_SystemError,
3344 "invalid node type (%d) for augmented assignment",
3345 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347 }
3348 return 1;
3349}
3350
3351static int
3352compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3353{
3354 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003355 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3356 PyErr_SetString(PyExc_SystemError,
3357 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003359 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360 f = &c->u->u_fblock[c->u->u_nfblocks++];
3361 f->fb_type = t;
3362 f->fb_block = b;
3363 return 1;
3364}
3365
3366static void
3367compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3368{
3369 struct compiler_unit *u = c->u;
3370 assert(u->u_nfblocks > 0);
3371 u->u_nfblocks--;
3372 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3373 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3374}
3375
Thomas Wouters89f507f2006-12-13 04:49:30 +00003376static int
3377compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003378 int i;
3379 struct compiler_unit *u = c->u;
3380 for (i = 0; i < u->u_nfblocks; ++i) {
3381 if (u->u_fblock[i].fb_type == LOOP)
3382 return 1;
3383 }
3384 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003385}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386/* Raises a SyntaxError and returns 0.
3387 If something goes wrong, a different exception may be raised.
3388*/
3389
3390static int
3391compiler_error(struct compiler *c, const char *errstr)
3392{
3393 PyObject *loc;
3394 PyObject *u = NULL, *v = NULL;
3395
3396 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3397 if (!loc) {
3398 Py_INCREF(Py_None);
3399 loc = Py_None;
3400 }
3401 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3402 Py_None, loc);
3403 if (!u)
3404 goto exit;
3405 v = Py_BuildValue("(zO)", errstr, u);
3406 if (!v)
3407 goto exit;
3408 PyErr_SetObject(PyExc_SyntaxError, v);
3409 exit:
3410 Py_DECREF(loc);
3411 Py_XDECREF(u);
3412 Py_XDECREF(v);
3413 return 0;
3414}
3415
3416static int
3417compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003418 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003419{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003420 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003422 /* XXX this code is duplicated */
3423 switch (ctx) {
3424 case AugLoad: /* fall through to Load */
3425 case Load: op = BINARY_SUBSCR; break;
3426 case AugStore:/* fall through to Store */
3427 case Store: op = STORE_SUBSCR; break;
3428 case Del: op = DELETE_SUBSCR; break;
3429 case Param:
3430 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003431 "invalid %s kind %d in subscript\n",
3432 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003433 return 0;
3434 }
3435 if (ctx == AugLoad) {
3436 ADDOP_I(c, DUP_TOPX, 2);
3437 }
3438 else if (ctx == AugStore) {
3439 ADDOP(c, ROT_THREE);
3440 }
3441 ADDOP(c, op);
3442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443}
3444
3445static int
3446compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3447{
3448 int n = 2;
3449 assert(s->kind == Slice_kind);
3450
3451 /* only handles the cases where BUILD_SLICE is emitted */
3452 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003453 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454 }
3455 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003456 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003458
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003460 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461 }
3462 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003463 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003464 }
3465
3466 if (s->v.Slice.step) {
3467 n++;
3468 VISIT(c, expr, s->v.Slice.step);
3469 }
3470 ADDOP_I(c, BUILD_SLICE, n);
3471 return 1;
3472}
3473
3474static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003475compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3476 expr_context_ty ctx)
3477{
3478 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479 case Slice_kind:
3480 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481 case Index_kind:
3482 VISIT(c, expr, s->v.Index.value);
3483 break;
3484 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003485 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003486 PyErr_SetString(PyExc_SystemError,
3487 "extended slice invalid in nested slice");
3488 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489 }
3490 return 1;
3491}
3492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493static int
3494compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3495{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003496 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003498 case Index_kind:
3499 kindname = "index";
3500 if (ctx != AugStore) {
3501 VISIT(c, expr, s->v.Index.value);
3502 }
3503 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003505 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003506 if (ctx != AugStore) {
3507 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003508 return 0;
3509 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003510 break;
3511 case ExtSlice_kind:
3512 kindname = "extended slice";
3513 if (ctx != AugStore) {
3514 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3515 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003516 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003517 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003518 if (!compiler_visit_nested_slice(c, sub, ctx))
3519 return 0;
3520 }
3521 ADDOP_I(c, BUILD_TUPLE, n);
3522 }
3523 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003524 default:
3525 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003526 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003527 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003529 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530}
3531
Thomas Wouters89f507f2006-12-13 04:49:30 +00003532/* End of the compiler section, beginning of the assembler section */
3533
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534/* do depth-first search of basic block graph, starting with block.
3535 post records the block indices in post-order.
3536
3537 XXX must handle implicit jumps from one block to next
3538*/
3539
Thomas Wouters89f507f2006-12-13 04:49:30 +00003540struct assembler {
3541 PyObject *a_bytecode; /* string containing bytecode */
3542 int a_offset; /* offset into bytecode */
3543 int a_nblocks; /* number of reachable blocks */
3544 basicblock **a_postorder; /* list of blocks in dfs postorder */
3545 PyObject *a_lnotab; /* string containing lnotab */
3546 int a_lnotab_off; /* offset into lnotab */
3547 int a_lineno; /* last lineno of emitted instruction */
3548 int a_lineno_off; /* bytecode offset of last lineno */
3549};
3550
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551static void
3552dfs(struct compiler *c, basicblock *b, struct assembler *a)
3553{
3554 int i;
3555 struct instr *instr = NULL;
3556
3557 if (b->b_seen)
3558 return;
3559 b->b_seen = 1;
3560 if (b->b_next != NULL)
3561 dfs(c, b->b_next, a);
3562 for (i = 0; i < b->b_iused; i++) {
3563 instr = &b->b_instr[i];
3564 if (instr->i_jrel || instr->i_jabs)
3565 dfs(c, instr->i_target, a);
3566 }
3567 a->a_postorder[a->a_nblocks++] = b;
3568}
3569
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003570static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3572{
3573 int i;
3574 struct instr *instr;
3575 if (b->b_seen || b->b_startdepth >= depth)
3576 return maxdepth;
3577 b->b_seen = 1;
3578 b->b_startdepth = depth;
3579 for (i = 0; i < b->b_iused; i++) {
3580 instr = &b->b_instr[i];
3581 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3582 if (depth > maxdepth)
3583 maxdepth = depth;
3584 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3585 if (instr->i_jrel || instr->i_jabs) {
3586 maxdepth = stackdepth_walk(c, instr->i_target,
3587 depth, maxdepth);
3588 if (instr->i_opcode == JUMP_ABSOLUTE ||
3589 instr->i_opcode == JUMP_FORWARD) {
3590 goto out; /* remaining code is dead */
3591 }
3592 }
3593 }
3594 if (b->b_next)
3595 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3596out:
3597 b->b_seen = 0;
3598 return maxdepth;
3599}
3600
3601/* Find the flow path that needs the largest stack. We assume that
3602 * cycles in the flow graph have no net effect on the stack depth.
3603 */
3604static int
3605stackdepth(struct compiler *c)
3606{
3607 basicblock *b, *entryblock;
3608 entryblock = NULL;
3609 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3610 b->b_seen = 0;
3611 b->b_startdepth = INT_MIN;
3612 entryblock = b;
3613 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003614 if (!entryblock)
3615 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 return stackdepth_walk(c, entryblock, 0, 0);
3617}
3618
3619static int
3620assemble_init(struct assembler *a, int nblocks, int firstlineno)
3621{
3622 memset(a, 0, sizeof(struct assembler));
3623 a->a_lineno = firstlineno;
3624 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3625 if (!a->a_bytecode)
3626 return 0;
3627 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3628 if (!a->a_lnotab)
3629 return 0;
3630 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003631 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003632 if (!a->a_postorder) {
3633 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 return 1;
3637}
3638
3639static void
3640assemble_free(struct assembler *a)
3641{
3642 Py_XDECREF(a->a_bytecode);
3643 Py_XDECREF(a->a_lnotab);
3644 if (a->a_postorder)
3645 PyObject_Free(a->a_postorder);
3646}
3647
3648/* Return the size of a basic block in bytes. */
3649
3650static int
3651instrsize(struct instr *instr)
3652{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003653 if (!instr->i_hasarg)
3654 return 1;
3655 if (instr->i_oparg > 0xffff)
3656 return 6;
3657 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658}
3659
3660static int
3661blocksize(basicblock *b)
3662{
3663 int i;
3664 int size = 0;
3665
3666 for (i = 0; i < b->b_iused; i++)
3667 size += instrsize(&b->b_instr[i]);
3668 return size;
3669}
3670
3671/* All about a_lnotab.
3672
3673c_lnotab is an array of unsigned bytes disguised as a Python string.
3674It is used to map bytecode offsets to source code line #s (when needed
3675for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003676
Tim Peters2a7f3842001-06-09 09:26:21 +00003677The array is conceptually a list of
3678 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003679pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003680
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003681 byte code offset source code line number
3682 0 1
3683 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003684 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003685 350 307
3686 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003687
3688The first trick is that these numbers aren't stored, only the increments
3689from one row to the next (this doesn't really work, but it's a start):
3690
3691 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3692
3693The second trick is that an unsigned byte can't hold negative values, or
3694values larger than 255, so (a) there's a deep assumption that byte code
3695offsets and their corresponding line #s both increase monotonically, and (b)
3696if at least one column jumps by more than 255 from one row to the next, more
3697than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003698from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003699part. A user of c_lnotab desiring to find the source line number
3700corresponding to a bytecode address A should do something like this
3701
3702 lineno = addr = 0
3703 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003704 addr += addr_incr
3705 if addr > A:
3706 return lineno
3707 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003708
3709In order for this to work, when the addr field increments by more than 255,
3710the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003711increment is < 256. So, in the example above, assemble_lnotab (it used
3712to be called com_set_lineno) should not (as was actually done until 2.2)
3713expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003714 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003715*/
3716
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003717static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003719{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720 int d_bytecode, d_lineno;
3721 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003722 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723
3724 d_bytecode = a->a_offset - a->a_lineno_off;
3725 d_lineno = i->i_lineno - a->a_lineno;
3726
3727 assert(d_bytecode >= 0);
3728 assert(d_lineno >= 0);
3729
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003730 /* XXX(nnorwitz): is there a better way to handle this?
3731 for loops are special, we want to be able to trace them
3732 each time around, so we need to set an extra line number. */
3733 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003734 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003735
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003737 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 nbytes = a->a_lnotab_off + 2 * ncodes;
3739 len = PyString_GET_SIZE(a->a_lnotab);
3740 if (nbytes >= len) {
3741 if (len * 2 < nbytes)
3742 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003743 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744 len *= 2;
3745 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3746 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003747 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003748 lnotab = (unsigned char *)
3749 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003750 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751 *lnotab++ = 255;
3752 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003753 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754 d_bytecode -= ncodes * 255;
3755 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003756 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 assert(d_bytecode <= 255);
3758 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003759 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 nbytes = a->a_lnotab_off + 2 * ncodes;
3761 len = PyString_GET_SIZE(a->a_lnotab);
3762 if (nbytes >= len) {
3763 if (len * 2 < nbytes)
3764 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003765 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 len *= 2;
3767 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3768 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003769 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003770 lnotab = (unsigned char *)
3771 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003773 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003775 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003777 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003778 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779 d_lineno -= ncodes * 255;
3780 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003781 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003782
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783 len = PyString_GET_SIZE(a->a_lnotab);
3784 if (a->a_lnotab_off + 2 >= len) {
3785 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003786 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003787 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003788 lnotab = (unsigned char *)
3789 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791 a->a_lnotab_off += 2;
3792 if (d_bytecode) {
3793 *lnotab++ = d_bytecode;
3794 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003795 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003796 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797 *lnotab++ = 0;
3798 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003799 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 a->a_lineno = i->i_lineno;
3801 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003802 return 1;
3803}
3804
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805/* assemble_emit()
3806 Extend the bytecode with a new instruction.
3807 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003808*/
3809
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003810static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003811assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003812{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003813 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003814 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 char *code;
3816
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003817 size = instrsize(i);
3818 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003820 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003821 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003823 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824 if (a->a_offset + size >= len) {
3825 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003826 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003827 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003828 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3829 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003830 if (size == 6) {
3831 assert(i->i_hasarg);
3832 *code++ = (char)EXTENDED_ARG;
3833 *code++ = ext & 0xff;
3834 *code++ = ext >> 8;
3835 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003837 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003838 if (i->i_hasarg) {
3839 assert(size == 3 || size == 6);
3840 *code++ = arg & 0xff;
3841 *code++ = arg >> 8;
3842 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003844}
3845
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003846static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003848{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003850 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003851 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 /* Compute the size of each block and fixup jump args.
3854 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003855start:
3856 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003858 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 bsize = blocksize(b);
3860 b->b_offset = totsize;
3861 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003862 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003863 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3865 bsize = b->b_offset;
3866 for (i = 0; i < b->b_iused; i++) {
3867 struct instr *instr = &b->b_instr[i];
3868 /* Relative jumps are computed relative to
3869 the instruction pointer after fetching
3870 the jump instruction.
3871 */
3872 bsize += instrsize(instr);
3873 if (instr->i_jabs)
3874 instr->i_oparg = instr->i_target->b_offset;
3875 else if (instr->i_jrel) {
3876 int delta = instr->i_target->b_offset - bsize;
3877 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003878 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003879 else
3880 continue;
3881 if (instr->i_oparg > 0xffff)
3882 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003883 }
3884 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003885
3886 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003887 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003888 with a better solution.
3889
3890 In the meantime, should the goto be dropped in favor
3891 of a loop?
3892
3893 The issue is that in the first loop blocksize() is called
3894 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003895 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003896 i_oparg is calculated in the second loop above.
3897
3898 So we loop until we stop seeing new EXTENDED_ARGs.
3899 The only EXTENDED_ARGs that could be popping up are
3900 ones in jump instructions. So this should converge
3901 fairly quickly.
3902 */
3903 if (last_extended_arg_count != extended_arg_count) {
3904 last_extended_arg_count = extended_arg_count;
3905 goto start;
3906 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003907}
3908
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003909static PyObject *
3910dict_keys_inorder(PyObject *dict, int offset)
3911{
3912 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003913 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003914
3915 tuple = PyTuple_New(size);
3916 if (tuple == NULL)
3917 return NULL;
3918 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003919 i = PyLong_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003920 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003921 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003922 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003923 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003924 PyTuple_SET_ITEM(tuple, i - offset, k);
3925 }
3926 return tuple;
3927}
3928
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003929static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003931{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932 PySTEntryObject *ste = c->u->u_ste;
3933 int flags = 0, n;
3934 if (ste->ste_type != ModuleBlock)
3935 flags |= CO_NEWLOCALS;
3936 if (ste->ste_type == FunctionBlock) {
3937 if (!ste->ste_unoptimized)
3938 flags |= CO_OPTIMIZED;
3939 if (ste->ste_nested)
3940 flags |= CO_NESTED;
3941 if (ste->ste_generator)
3942 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003943 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003944 if (ste->ste_varargs)
3945 flags |= CO_VARARGS;
3946 if (ste->ste_varkeywords)
3947 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003948 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003950
3951 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003952 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003953
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003954 n = PyDict_Size(c->u->u_freevars);
3955 if (n < 0)
3956 return -1;
3957 if (n == 0) {
3958 n = PyDict_Size(c->u->u_cellvars);
3959 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003960 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003961 if (n == 0) {
3962 flags |= CO_NOFREE;
3963 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003964 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003965
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003966 return flags;
3967}
3968
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003969static PyCodeObject *
3970makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003971{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972 PyObject *tmp;
3973 PyCodeObject *co = NULL;
3974 PyObject *consts = NULL;
3975 PyObject *names = NULL;
3976 PyObject *varnames = NULL;
3977 PyObject *filename = NULL;
3978 PyObject *name = NULL;
3979 PyObject *freevars = NULL;
3980 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003981 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003982 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003983
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003984 tmp = dict_keys_inorder(c->u->u_consts, 0);
3985 if (!tmp)
3986 goto error;
3987 consts = PySequence_List(tmp); /* optimize_code requires a list */
3988 Py_DECREF(tmp);
3989
3990 names = dict_keys_inorder(c->u->u_names, 0);
3991 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3992 if (!consts || !names || !varnames)
3993 goto error;
3994
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003995 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3996 if (!cellvars)
3997 goto error;
3998 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3999 if (!freevars)
4000 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004001 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004002 if (!filename)
4003 goto error;
4004
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004005 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004006 flags = compute_code_flags(c);
4007 if (flags < 0)
4008 goto error;
4009
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004010 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004011 if (!bytecode)
4012 goto error;
4013
4014 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4015 if (!tmp)
4016 goto error;
4017 Py_DECREF(consts);
4018 consts = tmp;
4019
Guido van Rossum4f72a782006-10-27 23:31:49 +00004020 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4021 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004022 bytecode, consts, names, varnames,
4023 freevars, cellvars,
4024 filename, c->u->u_name,
4025 c->u->u_firstlineno,
4026 a->a_lnotab);
4027 error:
4028 Py_XDECREF(consts);
4029 Py_XDECREF(names);
4030 Py_XDECREF(varnames);
4031 Py_XDECREF(filename);
4032 Py_XDECREF(name);
4033 Py_XDECREF(freevars);
4034 Py_XDECREF(cellvars);
4035 Py_XDECREF(bytecode);
4036 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004037}
4038
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004039
4040/* For debugging purposes only */
4041#if 0
4042static void
4043dump_instr(const struct instr *i)
4044{
4045 const char *jrel = i->i_jrel ? "jrel " : "";
4046 const char *jabs = i->i_jabs ? "jabs " : "";
4047 char arg[128];
4048
4049 *arg = '\0';
4050 if (i->i_hasarg)
4051 sprintf(arg, "arg: %d ", i->i_oparg);
4052
4053 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4054 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4055}
4056
4057static void
4058dump_basicblock(const basicblock *b)
4059{
4060 const char *seen = b->b_seen ? "seen " : "";
4061 const char *b_return = b->b_return ? "return " : "";
4062 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4063 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4064 if (b->b_instr) {
4065 int i;
4066 for (i = 0; i < b->b_iused; i++) {
4067 fprintf(stderr, " [%02d] ", i);
4068 dump_instr(b->b_instr + i);
4069 }
4070 }
4071}
4072#endif
4073
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004074static PyCodeObject *
4075assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004076{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077 basicblock *b, *entryblock;
4078 struct assembler a;
4079 int i, j, nblocks;
4080 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004081
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082 /* Make sure every block that falls off the end returns None.
4083 XXX NEXT_BLOCK() isn't quite right, because if the last
4084 block ends with a jump or return b_next shouldn't set.
4085 */
4086 if (!c->u->u_curblock->b_return) {
4087 NEXT_BLOCK(c);
4088 if (addNone)
4089 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4090 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004091 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004092
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093 nblocks = 0;
4094 entryblock = NULL;
4095 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4096 nblocks++;
4097 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004098 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004099
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004100 /* Set firstlineno if it wasn't explicitly set. */
4101 if (!c->u->u_firstlineno) {
4102 if (entryblock && entryblock->b_instr)
4103 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4104 else
4105 c->u->u_firstlineno = 1;
4106 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004107 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4108 goto error;
4109 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004110
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004112 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004113
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 /* Emit code in reverse postorder from dfs. */
4115 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004116 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117 for (j = 0; j < b->b_iused; j++)
4118 if (!assemble_emit(&a, &b->b_instr[j]))
4119 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004120 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4123 goto error;
4124 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4125 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004126
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004127 co = makecode(c, &a);
4128 error:
4129 assemble_free(&a);
4130 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004131}