blob: 77c6a775b7eb36ca6807717c00d49933ce313f99 [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++) {
338 v = PyInt_FromLong(i);
339 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;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000378 assert(PyInt_Check(v));
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000379 vi = PyInt_AS_LONG(v);
380 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) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000383 PyObject *tuple, *item = PyInt_FromLong(i);
384 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
710 case SLICE+0:
711 return 1;
712 case SLICE+1:
713 return 0;
714 case SLICE+2:
715 return 0;
716 case SLICE+3:
717 return -1;
718
719 case STORE_SLICE+0:
720 return -2;
721 case STORE_SLICE+1:
722 return -3;
723 case STORE_SLICE+2:
724 return -3;
725 case STORE_SLICE+3:
726 return -4;
727
728 case DELETE_SLICE+0:
729 return -1;
730 case DELETE_SLICE+1:
731 return -2;
732 case DELETE_SLICE+2:
733 return -2;
734 case DELETE_SLICE+3:
735 return -3;
736
737 case INPLACE_ADD:
738 case INPLACE_SUBTRACT:
739 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000740 case INPLACE_MODULO:
741 return -1;
742 case STORE_SUBSCR:
743 return -3;
744 case DELETE_SUBSCR:
745 return -2;
746
747 case BINARY_LSHIFT:
748 case BINARY_RSHIFT:
749 case BINARY_AND:
750 case BINARY_XOR:
751 case BINARY_OR:
752 return -1;
753 case INPLACE_POWER:
754 return -1;
755 case GET_ITER:
756 return 0;
757
758 case PRINT_EXPR:
759 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000760 case LOAD_BUILD_CLASS:
761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762 case INPLACE_LSHIFT:
763 case INPLACE_RSHIFT:
764 case INPLACE_AND:
765 case INPLACE_XOR:
766 case INPLACE_OR:
767 return -1;
768 case BREAK_LOOP:
769 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000770 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000771 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000772 case STORE_LOCALS:
773 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774 case RETURN_VALUE:
775 return -1;
776 case IMPORT_STAR:
777 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778 case YIELD_VALUE:
779 return 0;
780
781 case POP_BLOCK:
782 return 0;
783 case END_FINALLY:
784 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785
786 case STORE_NAME:
787 return -1;
788 case DELETE_NAME:
789 return 0;
790 case UNPACK_SEQUENCE:
791 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000792 case UNPACK_EX:
793 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794 case FOR_ITER:
795 return 1;
796
797 case STORE_ATTR:
798 return -2;
799 case DELETE_ATTR:
800 return -1;
801 case STORE_GLOBAL:
802 return -1;
803 case DELETE_GLOBAL:
804 return 0;
805 case DUP_TOPX:
806 return oparg;
807 case LOAD_CONST:
808 return 1;
809 case LOAD_NAME:
810 return 1;
811 case BUILD_TUPLE:
812 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000813 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000814 return 1-oparg;
815 case BUILD_MAP:
816 return 1;
Thomas Wouters00e41de2007-02-23 19:56:57 +0000817 case MAKE_BYTES:
818 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819 case LOAD_ATTR:
820 return 0;
821 case COMPARE_OP:
822 return -1;
823 case IMPORT_NAME:
824 return 0;
825 case IMPORT_FROM:
826 return 1;
827
828 case JUMP_FORWARD:
829 case JUMP_IF_FALSE:
830 case JUMP_IF_TRUE:
831 case JUMP_ABSOLUTE:
832 return 0;
833
834 case LOAD_GLOBAL:
835 return 1;
836
837 case CONTINUE_LOOP:
838 return 0;
839 case SETUP_LOOP:
840 return 0;
841 case SETUP_EXCEPT:
842 case SETUP_FINALLY:
843 return 3; /* actually pushed by an exception */
844
845 case LOAD_FAST:
846 return 1;
847 case STORE_FAST:
848 return -1;
849 case DELETE_FAST:
850 return 0;
851
852 case RAISE_VARARGS:
853 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000854#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855 case CALL_FUNCTION:
856 return -NARGS(oparg);
857 case CALL_FUNCTION_VAR:
858 case CALL_FUNCTION_KW:
859 return -NARGS(oparg)-1;
860 case CALL_FUNCTION_VAR_KW:
861 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000863 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000864 case MAKE_CLOSURE:
865 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000866#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867 case BUILD_SLICE:
868 if (oparg == 3)
869 return -2;
870 else
871 return -1;
872
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873 case LOAD_CLOSURE:
874 return 1;
875 case LOAD_DEREF:
876 return 1;
877 case STORE_DEREF:
878 return -1;
879 default:
880 fprintf(stderr, "opcode = %d\n", opcode);
881 Py_FatalError("opcode_stack_effect()");
882
883 }
884 return 0; /* not reachable */
885}
886
887/* Add an opcode with no argument.
888 Returns 0 on failure, 1 on success.
889*/
890
891static int
892compiler_addop(struct compiler *c, int opcode)
893{
894 basicblock *b;
895 struct instr *i;
896 int off;
897 off = compiler_next_instr(c, c->u->u_curblock);
898 if (off < 0)
899 return 0;
900 b = c->u->u_curblock;
901 i = &b->b_instr[off];
902 i->i_opcode = opcode;
903 i->i_hasarg = 0;
904 if (opcode == RETURN_VALUE)
905 b->b_return = 1;
906 compiler_set_lineno(c, off);
907 return 1;
908}
909
910static int
911compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
912{
913 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000914 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000916 /* necessary to make sure types aren't coerced (e.g., int and long) */
917 t = PyTuple_Pack(2, o, o->ob_type);
918 if (t == NULL)
919 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
921 v = PyDict_GetItem(dict, t);
922 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000923 if (PyErr_Occurred())
924 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000925 arg = PyDict_Size(dict);
926 v = PyInt_FromLong(arg);
927 if (!v) {
928 Py_DECREF(t);
929 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000930 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000931 if (PyDict_SetItem(dict, t, v) < 0) {
932 Py_DECREF(t);
933 Py_DECREF(v);
934 return -1;
935 }
936 Py_DECREF(v);
937 }
938 else
939 arg = PyInt_AsLong(v);
940 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000941 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000942}
943
944static int
945compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
946 PyObject *o)
947{
948 int arg = compiler_add_o(c, dict, o);
949 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000950 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000951 return compiler_addop_i(c, opcode, arg);
952}
953
954static int
955compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000956 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957{
958 int arg;
959 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
960 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000961 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000962 arg = compiler_add_o(c, dict, mangled);
963 Py_DECREF(mangled);
964 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000965 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000966 return compiler_addop_i(c, opcode, arg);
967}
968
969/* Add an opcode with an integer argument.
970 Returns 0 on failure, 1 on success.
971*/
972
973static int
974compiler_addop_i(struct compiler *c, int opcode, int oparg)
975{
976 struct instr *i;
977 int off;
978 off = compiler_next_instr(c, c->u->u_curblock);
979 if (off < 0)
980 return 0;
981 i = &c->u->u_curblock->b_instr[off];
982 i->i_opcode = opcode;
983 i->i_oparg = oparg;
984 i->i_hasarg = 1;
985 compiler_set_lineno(c, off);
986 return 1;
987}
988
989static int
990compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
991{
992 struct instr *i;
993 int off;
994
995 assert(b != NULL);
996 off = compiler_next_instr(c, c->u->u_curblock);
997 if (off < 0)
998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999 i = &c->u->u_curblock->b_instr[off];
1000 i->i_opcode = opcode;
1001 i->i_target = b;
1002 i->i_hasarg = 1;
1003 if (absolute)
1004 i->i_jabs = 1;
1005 else
1006 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001007 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008 return 1;
1009}
1010
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001011/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1012 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013 it as the current block. NEXT_BLOCK() also creates an implicit jump
1014 from the current block to the new block.
1015*/
1016
Thomas Wouters89f507f2006-12-13 04:49:30 +00001017/* The returns inside these macros make it impossible to decref objects
1018 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019*/
1020
1021
1022#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001023 if (compiler_use_new_block((C)) == NULL) \
1024 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025}
1026
1027#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001028 if (compiler_next_block((C)) == NULL) \
1029 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030}
1031
1032#define ADDOP(C, OP) { \
1033 if (!compiler_addop((C), (OP))) \
1034 return 0; \
1035}
1036
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001037#define ADDOP_IN_SCOPE(C, OP) { \
1038 if (!compiler_addop((C), (OP))) { \
1039 compiler_exit_scope(c); \
1040 return 0; \
1041 } \
1042}
1043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044#define ADDOP_O(C, OP, O, TYPE) { \
1045 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1046 return 0; \
1047}
1048
1049#define ADDOP_NAME(C, OP, O, TYPE) { \
1050 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1051 return 0; \
1052}
1053
1054#define ADDOP_I(C, OP, O) { \
1055 if (!compiler_addop_i((C), (OP), (O))) \
1056 return 0; \
1057}
1058
1059#define ADDOP_JABS(C, OP, O) { \
1060 if (!compiler_addop_j((C), (OP), (O), 1)) \
1061 return 0; \
1062}
1063
1064#define ADDOP_JREL(C, OP, O) { \
1065 if (!compiler_addop_j((C), (OP), (O), 0)) \
1066 return 0; \
1067}
1068
1069/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1070 the ASDL name to synthesize the name of the C type and the visit function.
1071*/
1072
1073#define VISIT(C, TYPE, V) {\
1074 if (!compiler_visit_ ## TYPE((C), (V))) \
1075 return 0; \
1076}
1077
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001078#define VISIT_IN_SCOPE(C, TYPE, V) {\
1079 if (!compiler_visit_ ## TYPE((C), (V))) { \
1080 compiler_exit_scope(c); \
1081 return 0; \
1082 } \
1083}
1084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085#define VISIT_SLICE(C, V, CTX) {\
1086 if (!compiler_visit_slice((C), (V), (CTX))) \
1087 return 0; \
1088}
1089
1090#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001091 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001093 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001094 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095 if (!compiler_visit_ ## TYPE((C), elt)) \
1096 return 0; \
1097 } \
1098}
1099
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001100#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001101 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001102 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001103 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001105 if (!compiler_visit_ ## TYPE((C), elt)) { \
1106 compiler_exit_scope(c); \
1107 return 0; \
1108 } \
1109 } \
1110}
1111
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112static int
1113compiler_isdocstring(stmt_ty s)
1114{
1115 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001116 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117 return s->v.Expr.value->kind == Str_kind;
1118}
1119
1120/* Compile a sequence of statements, checking for a docstring. */
1121
1122static int
1123compiler_body(struct compiler *c, asdl_seq *stmts)
1124{
1125 int i = 0;
1126 stmt_ty st;
1127
1128 if (!asdl_seq_LEN(stmts))
1129 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001131 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1132 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 i = 1;
1134 VISIT(c, expr, st->v.Expr.value);
1135 if (!compiler_nameop(c, __doc__, Store))
1136 return 0;
1137 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001138 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001139 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return 1;
1141}
1142
1143static PyCodeObject *
1144compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001145{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001146 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001147 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 static PyObject *module;
1149 if (!module) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001150 module = PyUnicode_FromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 if (!module)
1152 return NULL;
1153 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001154 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1155 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001156 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 switch (mod->kind) {
1158 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001159 if (!compiler_body(c, mod->v.Module.body)) {
1160 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163 break;
1164 case Interactive_kind:
1165 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 break;
1169 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001170 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001171 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 break;
1173 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001174 PyErr_SetString(PyExc_SystemError,
1175 "suite should not be possible");
1176 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001177 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001178 PyErr_Format(PyExc_SystemError,
1179 "module kind %d should not be possible",
1180 mod->kind);
1181 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001182 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 co = assemble(c, addNone);
1184 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001185 return co;
1186}
1187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188/* The test for LOCAL must come before the test for FREE in order to
1189 handle classes where name is both local and free. The local var is
1190 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001191*/
1192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193static int
1194get_ref_type(struct compiler *c, PyObject *name)
1195{
1196 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001197 if (scope == 0) {
1198 char buf[350];
1199 PyOS_snprintf(buf, sizeof(buf),
1200 "unknown scope for %.100s in %.100s(%s) in %s\n"
1201 "symbols: %s\nlocals: %s\nglobals: %s\n",
1202 PyString_AS_STRING(name),
1203 PyString_AS_STRING(c->u->u_name),
1204 PyObject_REPR(c->u->u_ste->ste_id),
1205 c->c_filename,
1206 PyObject_REPR(c->u->u_ste->ste_symbols),
1207 PyObject_REPR(c->u->u_varnames),
1208 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001210 Py_FatalError(buf);
1211 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001212
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001213 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214}
1215
1216static int
1217compiler_lookup_arg(PyObject *dict, PyObject *name)
1218{
1219 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001222 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001224 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001226 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001227 return PyInt_AS_LONG(v);
1228}
1229
1230static int
1231compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1232{
1233 int i, free = PyCode_GetNumFree(co);
1234 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001235 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1236 ADDOP_I(c, MAKE_FUNCTION, args);
1237 return 1;
1238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239 for (i = 0; i < free; ++i) {
1240 /* Bypass com_addop_varname because it will generate
1241 LOAD_DEREF but LOAD_CLOSURE is needed.
1242 */
1243 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1244 int arg, reftype;
1245
1246 /* Special case: If a class contains a method with a
1247 free variable that has the same name as a method,
1248 the name will be considered free *and* local in the
1249 class. It should be handled by the closure, as
1250 well as by the normal name loookup logic.
1251 */
1252 reftype = get_ref_type(c, name);
1253 if (reftype == CELL)
1254 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1255 else /* (reftype == FREE) */
1256 arg = compiler_lookup_arg(c->u->u_freevars, name);
1257 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001258 fprintf(stderr,
1259 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 "freevars of %s: %s\n",
1261 PyObject_REPR(name),
1262 PyString_AS_STRING(c->u->u_name),
1263 reftype, arg,
1264 PyString_AS_STRING(co->co_name),
1265 PyObject_REPR(co->co_freevars));
1266 Py_FatalError("compiler_make_closure()");
1267 }
1268 ADDOP_I(c, LOAD_CLOSURE, arg);
1269 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001270 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 ADDOP_I(c, MAKE_CLOSURE, args);
1273 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274}
1275
1276static int
1277compiler_decorators(struct compiler *c, asdl_seq* decos)
1278{
1279 int i;
1280
1281 if (!decos)
1282 return 1;
1283
1284 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001285 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286 }
1287 return 1;
1288}
1289
1290static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001291compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1292 asdl_seq *kw_defaults)
1293{
1294 int i, default_count = 0;
1295 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001296 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001297 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1298 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001299 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001300 if (!compiler_visit_expr(c, default_)) {
1301 return -1;
1302 }
1303 default_count++;
1304 }
1305 }
1306 return default_count;
1307}
1308
1309static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001310compiler_visit_argannotation(struct compiler *c, identifier id,
1311 expr_ty annotation, PyObject *names)
1312{
1313 if (annotation) {
1314 VISIT(c, expr, annotation);
1315 if (PyList_Append(names, id))
1316 return -1;
1317 }
1318 return 0;
1319}
1320
1321static int
1322compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1323 PyObject *names)
1324{
1325 int i, error;
1326 for (i = 0; i < asdl_seq_LEN(args); i++) {
1327 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001328 error = compiler_visit_argannotation(
1329 c,
1330 arg->arg,
1331 arg->annotation,
1332 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001333 if (error)
1334 return error;
1335 }
1336 return 0;
1337}
1338
1339static int
1340compiler_visit_annotations(struct compiler *c, arguments_ty args,
1341 expr_ty returns)
1342{
Guido van Rossum0240b922007-02-26 21:23:50 +00001343 /* Push arg annotations and a list of the argument names. Return the #
1344 of items pushed. The expressions are evaluated out-of-order wrt the
1345 source code.
1346
1347 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1348 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001349 static identifier return_str;
1350 PyObject *names;
1351 int len;
1352 names = PyList_New(0);
1353 if (!names)
1354 return -1;
1355
1356 if (compiler_visit_argannotations(c, args->args, names))
1357 goto error;
1358 if (args->varargannotation &&
1359 compiler_visit_argannotation(c, args->vararg,
1360 args->varargannotation, names))
1361 goto error;
1362 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1363 goto error;
1364 if (args->kwargannotation &&
1365 compiler_visit_argannotation(c, args->kwarg,
1366 args->kwargannotation, names))
1367 goto error;
1368
1369 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001370 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001371 if (!return_str)
1372 goto error;
1373 }
1374 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1375 goto error;
1376 }
1377
1378 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001379 if (len > 65534) {
1380 /* len must fit in 16 bits, and len is incremented below */
1381 PyErr_SetString(PyExc_SyntaxError,
1382 "too many annotations");
1383 goto error;
1384 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001385 if (len) {
1386 /* convert names to a tuple and place on stack */
1387 PyObject *elt;
1388 int i;
1389 PyObject *s = PyTuple_New(len);
1390 if (!s)
1391 goto error;
1392 for (i = 0; i < len; i++) {
1393 elt = PyList_GET_ITEM(names, i);
1394 Py_INCREF(elt);
1395 PyTuple_SET_ITEM(s, i, elt);
1396 }
1397 ADDOP_O(c, LOAD_CONST, s, consts);
1398 Py_DECREF(s);
1399 len++; /* include the just-pushed tuple */
1400 }
1401 Py_DECREF(names);
1402 return len;
1403
1404error:
1405 Py_DECREF(names);
1406 return -1;
1407}
1408
1409static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410compiler_function(struct compiler *c, stmt_ty s)
1411{
1412 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001413 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001415 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001416 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001417 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001418 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001419 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420
1421 assert(s->kind == FunctionDef_kind);
1422
1423 if (!compiler_decorators(c, decos))
1424 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001425 if (args->kwonlyargs) {
1426 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1427 args->kw_defaults);
1428 if (res < 0)
1429 return 0;
1430 kw_default_count = res;
1431 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432 if (args->defaults)
1433 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001434 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001435 if (num_annotations < 0)
1436 return 0;
1437 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001438
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1440 s->lineno))
1441 return 0;
1442
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001443 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001444 docstring = compiler_isdocstring(st);
1445 if (docstring)
1446 first_const = st->v.Expr.value->v.Str.s;
1447 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001448 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001449 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001450 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001453 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001455 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001457 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1458 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459 }
1460 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001461 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462 if (co == NULL)
1463 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464
Guido van Rossum4f72a782006-10-27 23:31:49 +00001465 arglength = asdl_seq_LEN(args->defaults);
1466 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001467 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001468 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001469 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470
Neal Norwitzc1505362006-12-28 06:47:50 +00001471 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1473 ADDOP_I(c, CALL_FUNCTION, 1);
1474 }
1475
1476 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1477}
1478
1479static int
1480compiler_class(struct compiler *c, stmt_ty s)
1481{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001482 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001484 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001485 PySTEntryObject *ste;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001486 int err, i;
1487 asdl_seq* decos = s->v.ClassDef.decorator_list;
1488
1489 if (!compiler_decorators(c, decos))
1490 return 0;
1491
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001492 /* initialize statics */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001493 if (locals == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001494 locals = PyUnicode_FromString("__locals__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001495 if (locals == NULL)
1496 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001499 /* ultimately generate code for:
1500 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1501 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001502 <func> is a function/closure created from the class body;
1503 it has a single argument (__locals__) where the dict
1504 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001505 <name> is the class name
1506 <bases> is the positional arguments and *varargs argument
1507 <keywords> is the keyword arguments and **kwds argument
1508 This borrows from compiler_call.
1509 */
1510
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001511 /* 0. Create a fake argument named __locals__ */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001512 ste = PySymtable_Lookup(c->c_st, s);
1513 if (ste == NULL)
1514 return 0;
1515 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001516 err = PyList_Append(ste->ste_varnames, locals);
1517 Py_DECREF(ste);
1518 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001519 return 0;
1520
1521 /* 1. compile the class body into a code object */
1522 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1523 return 0;
1524 /* this block represents what we do in the new scope */
1525 {
1526 /* use the class name for name mangling */
1527 Py_INCREF(s->v.ClassDef.name);
1528 c->u->u_private = s->v.ClassDef.name;
1529 /* force it to have one mandatory argument */
1530 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001531 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001532 ADDOP_I(c, LOAD_FAST, 0);
1533 /* ... and store it into f_locals */
1534 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001535 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001536 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001537 if (!str || !compiler_nameop(c, str, Load)) {
1538 Py_XDECREF(str);
1539 compiler_exit_scope(c);
1540 return 0;
1541 }
1542 Py_DECREF(str);
1543 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001544 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001545 if (!str || !compiler_nameop(c, str, Store)) {
1546 Py_XDECREF(str);
1547 compiler_exit_scope(c);
1548 return 0;
1549 }
1550 Py_DECREF(str);
1551 /* compile the body proper */
1552 if (!compiler_body(c, s->v.ClassDef.body)) {
1553 compiler_exit_scope(c);
1554 return 0;
1555 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001556 /* return the (empty) __class__ cell */
1557 str = PyUnicode_InternFromString("__class__");
1558 if (str == NULL) {
1559 compiler_exit_scope(c);
1560 return 0;
1561 }
1562 i = compiler_lookup_arg(c->u->u_cellvars, str);
1563 Py_DECREF(str);
1564 if (i == -1) {
1565 /* This happens when nobody references the cell */
1566 PyErr_Clear();
1567 /* Return None */
1568 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1569 }
1570 else {
1571 /* Return the cell where to store __class__ */
1572 ADDOP_I(c, LOAD_CLOSURE, i);
1573 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001574 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1575 /* create the code object */
1576 co = assemble(c, 1);
1577 }
1578 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001579 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001580 if (co == NULL)
1581 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001582
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001583 /* 2. load the 'build_class' function */
1584 ADDOP(c, LOAD_BUILD_CLASS);
1585
1586 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001587 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001588 Py_DECREF(co);
1589
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001590 /* 4. load class name */
1591 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1592
1593 /* 5. generate the rest of the code for the call */
1594 if (!compiler_call_helper(c, 2,
1595 s->v.ClassDef.bases,
1596 s->v.ClassDef.keywords,
1597 s->v.ClassDef.starargs,
1598 s->v.ClassDef.kwargs))
1599 return 0;
1600
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001601 /* 6. apply decorators */
1602 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1603 ADDOP_I(c, CALL_FUNCTION, 1);
1604 }
1605
1606 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001607 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1608 return 0;
1609 return 1;
1610}
1611
1612static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001613compiler_ifexp(struct compiler *c, expr_ty e)
1614{
1615 basicblock *end, *next;
1616
1617 assert(e->kind == IfExp_kind);
1618 end = compiler_new_block(c);
1619 if (end == NULL)
1620 return 0;
1621 next = compiler_new_block(c);
1622 if (next == NULL)
1623 return 0;
1624 VISIT(c, expr, e->v.IfExp.test);
1625 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1626 ADDOP(c, POP_TOP);
1627 VISIT(c, expr, e->v.IfExp.body);
1628 ADDOP_JREL(c, JUMP_FORWARD, end);
1629 compiler_use_next_block(c, next);
1630 ADDOP(c, POP_TOP);
1631 VISIT(c, expr, e->v.IfExp.orelse);
1632 compiler_use_next_block(c, end);
1633 return 1;
1634}
1635
1636static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637compiler_lambda(struct compiler *c, expr_ty e)
1638{
1639 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001640 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001641 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001642 arguments_ty args = e->v.Lambda.args;
1643 assert(e->kind == Lambda_kind);
1644
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001645 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001646 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001647 if (!name)
1648 return 0;
1649 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001650
Guido van Rossum4f72a782006-10-27 23:31:49 +00001651 if (args->kwonlyargs) {
1652 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1653 args->kw_defaults);
1654 if (res < 0) return 0;
1655 kw_default_count = res;
1656 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657 if (args->defaults)
1658 VISIT_SEQ(c, expr, args->defaults);
1659 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1660 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001661
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001663 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001664 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1665 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001666 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001667 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668 if (co == NULL)
1669 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670
Guido van Rossum4f72a782006-10-27 23:31:49 +00001671 arglength = asdl_seq_LEN(args->defaults);
1672 arglength |= kw_default_count << 8;
1673 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001674 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675
1676 return 1;
1677}
1678
1679static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680compiler_if(struct compiler *c, stmt_ty s)
1681{
1682 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001683 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001684 assert(s->kind == If_kind);
1685 end = compiler_new_block(c);
1686 if (end == NULL)
1687 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001688 next = compiler_new_block(c);
1689 if (next == NULL)
1690 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001691
1692 constant = expr_constant(s->v.If.test);
1693 /* constant = 0: "if 0"
1694 * constant = 1: "if 1", "if 2", ...
1695 * constant = -1: rest */
1696 if (constant == 0) {
1697 if (s->v.If.orelse)
1698 VISIT_SEQ(c, stmt, s->v.If.orelse);
1699 } else if (constant == 1) {
1700 VISIT_SEQ(c, stmt, s->v.If.body);
1701 } else {
1702 VISIT(c, expr, s->v.If.test);
1703 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1704 ADDOP(c, POP_TOP);
1705 VISIT_SEQ(c, stmt, s->v.If.body);
1706 ADDOP_JREL(c, JUMP_FORWARD, end);
1707 compiler_use_next_block(c, next);
1708 ADDOP(c, POP_TOP);
1709 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001710 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001711 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001712 compiler_use_next_block(c, end);
1713 return 1;
1714}
1715
1716static int
1717compiler_for(struct compiler *c, stmt_ty s)
1718{
1719 basicblock *start, *cleanup, *end;
1720
1721 start = compiler_new_block(c);
1722 cleanup = compiler_new_block(c);
1723 end = compiler_new_block(c);
1724 if (start == NULL || end == NULL || cleanup == NULL)
1725 return 0;
1726 ADDOP_JREL(c, SETUP_LOOP, end);
1727 if (!compiler_push_fblock(c, LOOP, start))
1728 return 0;
1729 VISIT(c, expr, s->v.For.iter);
1730 ADDOP(c, GET_ITER);
1731 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001732 /* XXX(nnorwitz): is there a better way to handle this?
1733 for loops are special, we want to be able to trace them
1734 each time around, so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001735 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001736 ADDOP_JREL(c, FOR_ITER, cleanup);
1737 VISIT(c, expr, s->v.For.target);
1738 VISIT_SEQ(c, stmt, s->v.For.body);
1739 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1740 compiler_use_next_block(c, cleanup);
1741 ADDOP(c, POP_BLOCK);
1742 compiler_pop_fblock(c, LOOP, start);
1743 VISIT_SEQ(c, stmt, s->v.For.orelse);
1744 compiler_use_next_block(c, end);
1745 return 1;
1746}
1747
1748static int
1749compiler_while(struct compiler *c, stmt_ty s)
1750{
1751 basicblock *loop, *orelse, *end, *anchor = NULL;
1752 int constant = expr_constant(s->v.While.test);
1753
1754 if (constant == 0)
1755 return 1;
1756 loop = compiler_new_block(c);
1757 end = compiler_new_block(c);
1758 if (constant == -1) {
1759 anchor = compiler_new_block(c);
1760 if (anchor == NULL)
1761 return 0;
1762 }
1763 if (loop == NULL || end == NULL)
1764 return 0;
1765 if (s->v.While.orelse) {
1766 orelse = compiler_new_block(c);
1767 if (orelse == NULL)
1768 return 0;
1769 }
1770 else
1771 orelse = NULL;
1772
1773 ADDOP_JREL(c, SETUP_LOOP, end);
1774 compiler_use_next_block(c, loop);
1775 if (!compiler_push_fblock(c, LOOP, loop))
1776 return 0;
1777 if (constant == -1) {
1778 VISIT(c, expr, s->v.While.test);
1779 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1780 ADDOP(c, POP_TOP);
1781 }
1782 VISIT_SEQ(c, stmt, s->v.While.body);
1783 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1784
1785 /* XXX should the two POP instructions be in a separate block
1786 if there is no else clause ?
1787 */
1788
1789 if (constant == -1) {
1790 compiler_use_next_block(c, anchor);
1791 ADDOP(c, POP_TOP);
1792 ADDOP(c, POP_BLOCK);
1793 }
1794 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001795 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796 VISIT_SEQ(c, stmt, s->v.While.orelse);
1797 compiler_use_next_block(c, end);
1798
1799 return 1;
1800}
1801
1802static int
1803compiler_continue(struct compiler *c)
1804{
1805 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001806 static const char IN_FINALLY_ERROR_MSG[] =
1807 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 int i;
1809
1810 if (!c->u->u_nfblocks)
1811 return compiler_error(c, LOOP_ERROR_MSG);
1812 i = c->u->u_nfblocks - 1;
1813 switch (c->u->u_fblock[i].fb_type) {
1814 case LOOP:
1815 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1816 break;
1817 case EXCEPT:
1818 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001819 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1820 /* Prevent continue anywhere under a finally
1821 even if hidden in a sub-try or except. */
1822 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1823 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1824 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825 if (i == -1)
1826 return compiler_error(c, LOOP_ERROR_MSG);
1827 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1828 break;
1829 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001830 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 }
1832
1833 return 1;
1834}
1835
1836/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1837
1838 SETUP_FINALLY L
1839 <code for body>
1840 POP_BLOCK
1841 LOAD_CONST <None>
1842 L: <code for finalbody>
1843 END_FINALLY
1844
1845 The special instructions use the block stack. Each block
1846 stack entry contains the instruction that created it (here
1847 SETUP_FINALLY), the level of the value stack at the time the
1848 block stack entry was created, and a label (here L).
1849
1850 SETUP_FINALLY:
1851 Pushes the current value stack level and the label
1852 onto the block stack.
1853 POP_BLOCK:
1854 Pops en entry from the block stack, and pops the value
1855 stack until its level is the same as indicated on the
1856 block stack. (The label is ignored.)
1857 END_FINALLY:
1858 Pops a variable number of entries from the *value* stack
1859 and re-raises the exception they specify. The number of
1860 entries popped depends on the (pseudo) exception type.
1861
1862 The block stack is unwound when an exception is raised:
1863 when a SETUP_FINALLY entry is found, the exception is pushed
1864 onto the value stack (and the exception condition is cleared),
1865 and the interpreter jumps to the label gotten from the block
1866 stack.
1867*/
1868
1869static int
1870compiler_try_finally(struct compiler *c, stmt_ty s)
1871{
1872 basicblock *body, *end;
1873 body = compiler_new_block(c);
1874 end = compiler_new_block(c);
1875 if (body == NULL || end == NULL)
1876 return 0;
1877
1878 ADDOP_JREL(c, SETUP_FINALLY, end);
1879 compiler_use_next_block(c, body);
1880 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1881 return 0;
1882 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1883 ADDOP(c, POP_BLOCK);
1884 compiler_pop_fblock(c, FINALLY_TRY, body);
1885
1886 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1887 compiler_use_next_block(c, end);
1888 if (!compiler_push_fblock(c, FINALLY_END, end))
1889 return 0;
1890 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1891 ADDOP(c, END_FINALLY);
1892 compiler_pop_fblock(c, FINALLY_END, end);
1893
1894 return 1;
1895}
1896
1897/*
1898 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1899 (The contents of the value stack is shown in [], with the top
1900 at the right; 'tb' is trace-back info, 'val' the exception's
1901 associated value, and 'exc' the exception.)
1902
1903 Value stack Label Instruction Argument
1904 [] SETUP_EXCEPT L1
1905 [] <code for S>
1906 [] POP_BLOCK
1907 [] JUMP_FORWARD L0
1908
1909 [tb, val, exc] L1: DUP )
1910 [tb, val, exc, exc] <evaluate E1> )
1911 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1912 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1913 [tb, val, exc, 1] POP )
1914 [tb, val, exc] POP
1915 [tb, val] <assign to V1> (or POP if no V1)
1916 [tb] POP
1917 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001918 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919
1920 [tb, val, exc, 0] L2: POP
1921 [tb, val, exc] DUP
1922 .............................etc.......................
1923
1924 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001925 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926
1927 [] L0: <next statement>
1928
1929 Of course, parts are not generated if Vi or Ei is not present.
1930*/
1931static int
1932compiler_try_except(struct compiler *c, stmt_ty s)
1933{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001934 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935 int i, n;
1936
1937 body = compiler_new_block(c);
1938 except = compiler_new_block(c);
1939 orelse = compiler_new_block(c);
1940 end = compiler_new_block(c);
1941 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1942 return 0;
1943 ADDOP_JREL(c, SETUP_EXCEPT, except);
1944 compiler_use_next_block(c, body);
1945 if (!compiler_push_fblock(c, EXCEPT, body))
1946 return 0;
1947 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1948 ADDOP(c, POP_BLOCK);
1949 compiler_pop_fblock(c, EXCEPT, body);
1950 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1951 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1952 compiler_use_next_block(c, except);
1953 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001954 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955 s->v.TryExcept.handlers, i);
1956 if (!handler->type && i < n-1)
1957 return compiler_error(c, "default 'except:' must be last");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001958 c->u->u_lineno_set = 0;
1959 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 except = compiler_new_block(c);
1961 if (except == NULL)
1962 return 0;
1963 if (handler->type) {
1964 ADDOP(c, DUP_TOP);
1965 VISIT(c, expr, handler->type);
1966 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1967 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1968 ADDOP(c, POP_TOP);
1969 }
1970 ADDOP(c, POP_TOP);
1971 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001972 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001973
1974 cleanup_end = compiler_new_block(c);
1975 cleanup_body = compiler_new_block(c);
1976 if(!(cleanup_end || cleanup_body))
1977 return 0;
1978
Guido van Rossum16be03e2007-01-10 18:51:35 +00001979 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001980 ADDOP(c, POP_TOP);
1981
1982 /*
1983 try:
1984 # body
1985 except type as name:
1986 try:
1987 # body
1988 finally:
1989 name = None
1990 del name
1991 */
1992
1993 /* second try: */
1994 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
1995 compiler_use_next_block(c, cleanup_body);
1996 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
1997 return 0;
1998
1999 /* second # body */
2000 VISIT_SEQ(c, stmt, handler->body);
2001 ADDOP(c, POP_BLOCK);
2002 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2003
2004 /* finally: */
2005 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2006 compiler_use_next_block(c, cleanup_end);
2007 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2008 return 0;
2009
2010 /* name = None */
2011 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00002012 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002013
Guido van Rossum16be03e2007-01-10 18:51:35 +00002014 /* del name */
2015 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002016
2017 ADDOP(c, END_FINALLY);
2018 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019 }
2020 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00002021 ADDOP(c, POP_TOP);
2022 ADDOP(c, POP_TOP);
2023 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025 ADDOP_JREL(c, JUMP_FORWARD, end);
2026 compiler_use_next_block(c, except);
2027 if (handler->type)
2028 ADDOP(c, POP_TOP);
2029 }
2030 ADDOP(c, END_FINALLY);
2031 compiler_use_next_block(c, orelse);
2032 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2033 compiler_use_next_block(c, end);
2034 return 1;
2035}
2036
2037static int
2038compiler_import_as(struct compiler *c, identifier name, identifier asname)
2039{
2040 /* The IMPORT_NAME opcode was already generated. This function
2041 merely needs to bind the result to a name.
2042
2043 If there is a dot in name, we need to split it and emit a
2044 LOAD_ATTR for each name.
2045 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002046 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2047 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048 if (dot) {
2049 /* Consume the base module name to get the first attribute */
2050 src = dot + 1;
2051 while (dot) {
2052 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002053 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002054 dot = Py_UNICODE_strchr(src, '.');
2055 attr = PyUnicode_FromUnicode(src,
2056 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002057 if (!attr)
2058 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002060 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 src = dot + 1;
2062 }
2063 }
2064 return compiler_nameop(c, asname, Store);
2065}
2066
2067static int
2068compiler_import(struct compiler *c, stmt_ty s)
2069{
2070 /* The Import node stores a module name like a.b.c as a single
2071 string. This is convenient for all cases except
2072 import a.b.c as d
2073 where we need to parse that string to extract the individual
2074 module names.
2075 XXX Perhaps change the representation to make this case simpler?
2076 */
2077 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002078
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002080 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002082 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083
Guido van Rossum45aecf42006-03-15 04:58:47 +00002084 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002085 if (level == NULL)
2086 return 0;
2087
2088 ADDOP_O(c, LOAD_CONST, level, consts);
2089 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2091 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2092
2093 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002094 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 if (!r)
2096 return r;
2097 }
2098 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002100 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2101 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002103 tmp = PyUnicode_FromUnicode(base,
2104 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002105 r = compiler_nameop(c, tmp, Store);
2106 if (dot) {
2107 Py_DECREF(tmp);
2108 }
2109 if (!r)
2110 return r;
2111 }
2112 }
2113 return 1;
2114}
2115
2116static int
2117compiler_from_import(struct compiler *c, stmt_ty s)
2118{
2119 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120
2121 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002122 PyObject *level;
2123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 if (!names)
2125 return 0;
2126
Guido van Rossum45aecf42006-03-15 04:58:47 +00002127 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002128 if (!level) {
2129 Py_DECREF(names);
2130 return 0;
2131 }
2132
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 /* build up the names */
2134 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002135 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 Py_INCREF(alias->name);
2137 PyTuple_SET_ITEM(names, i, alias->name);
2138 }
2139
2140 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002141 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2142 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002143 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 Py_DECREF(names);
2145 return compiler_error(c,
2146 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002147 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148
2149 }
2150 }
2151
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002152 ADDOP_O(c, LOAD_CONST, level, consts);
2153 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002155 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002156 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2157 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002158 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159 identifier store_name;
2160
Martin v. Löwis5b222132007-06-10 09:51:05 +00002161 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162 assert(n == 1);
2163 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002164 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165 }
2166
2167 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2168 store_name = alias->name;
2169 if (alias->asname)
2170 store_name = alias->asname;
2171
2172 if (!compiler_nameop(c, store_name, Store)) {
2173 Py_DECREF(names);
2174 return 0;
2175 }
2176 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002177 /* remove imported module */
2178 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179 return 1;
2180}
2181
2182static int
2183compiler_assert(struct compiler *c, stmt_ty s)
2184{
2185 static PyObject *assertion_error = NULL;
2186 basicblock *end;
2187
2188 if (Py_OptimizeFlag)
2189 return 1;
2190 if (assertion_error == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002191 assertion_error = PyUnicode_FromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192 if (assertion_error == NULL)
2193 return 0;
2194 }
2195 VISIT(c, expr, s->v.Assert.test);
2196 end = compiler_new_block(c);
2197 if (end == NULL)
2198 return 0;
2199 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2200 ADDOP(c, POP_TOP);
2201 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2202 if (s->v.Assert.msg) {
2203 VISIT(c, expr, s->v.Assert.msg);
2204 ADDOP_I(c, RAISE_VARARGS, 2);
2205 }
2206 else {
2207 ADDOP_I(c, RAISE_VARARGS, 1);
2208 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002209 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210 ADDOP(c, POP_TOP);
2211 return 1;
2212}
2213
2214static int
2215compiler_visit_stmt(struct compiler *c, stmt_ty s)
2216{
2217 int i, n;
2218
Thomas Wouters89f507f2006-12-13 04:49:30 +00002219 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002221 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002224 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002226 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002228 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229 if (c->u->u_ste->ste_type != FunctionBlock)
2230 return compiler_error(c, "'return' outside function");
2231 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002232 VISIT(c, expr, s->v.Return.value);
2233 }
2234 else
2235 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2236 ADDOP(c, RETURN_VALUE);
2237 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002238 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239 VISIT_SEQ(c, expr, s->v.Delete.targets)
2240 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002241 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 n = asdl_seq_LEN(s->v.Assign.targets);
2243 VISIT(c, expr, s->v.Assign.value);
2244 for (i = 0; i < n; i++) {
2245 if (i < n - 1)
2246 ADDOP(c, DUP_TOP);
2247 VISIT(c, expr,
2248 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2249 }
2250 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002251 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002253 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002255 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002257 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002259 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 n = 0;
2261 if (s->v.Raise.type) {
2262 VISIT(c, expr, s->v.Raise.type);
2263 n++;
2264 if (s->v.Raise.inst) {
2265 VISIT(c, expr, s->v.Raise.inst);
2266 n++;
2267 if (s->v.Raise.tback) {
2268 VISIT(c, expr, s->v.Raise.tback);
2269 n++;
2270 }
2271 }
2272 }
2273 ADDOP_I(c, RAISE_VARARGS, n);
2274 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002275 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002277 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002279 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002281 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002283 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002285 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002286 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002288 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002290 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 ADDOP(c, PRINT_EXPR);
2292 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002293 else if (s->v.Expr.value->kind != Str_kind &&
2294 s->v.Expr.value->kind != Num_kind) {
2295 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 ADDOP(c, POP_TOP);
2297 }
2298 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002299 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002301 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002302 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303 return compiler_error(c, "'break' outside loop");
2304 ADDOP(c, BREAK_LOOP);
2305 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002306 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002308 case With_kind:
2309 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 }
2311 return 1;
2312}
2313
2314static int
2315unaryop(unaryop_ty op)
2316{
2317 switch (op) {
2318 case Invert:
2319 return UNARY_INVERT;
2320 case Not:
2321 return UNARY_NOT;
2322 case UAdd:
2323 return UNARY_POSITIVE;
2324 case USub:
2325 return UNARY_NEGATIVE;
2326 }
2327 return 0;
2328}
2329
2330static int
2331binop(struct compiler *c, operator_ty op)
2332{
2333 switch (op) {
2334 case Add:
2335 return BINARY_ADD;
2336 case Sub:
2337 return BINARY_SUBTRACT;
2338 case Mult:
2339 return BINARY_MULTIPLY;
2340 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002341 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342 case Mod:
2343 return BINARY_MODULO;
2344 case Pow:
2345 return BINARY_POWER;
2346 case LShift:
2347 return BINARY_LSHIFT;
2348 case RShift:
2349 return BINARY_RSHIFT;
2350 case BitOr:
2351 return BINARY_OR;
2352 case BitXor:
2353 return BINARY_XOR;
2354 case BitAnd:
2355 return BINARY_AND;
2356 case FloorDiv:
2357 return BINARY_FLOOR_DIVIDE;
2358 }
2359 return 0;
2360}
2361
2362static int
2363cmpop(cmpop_ty op)
2364{
2365 switch (op) {
2366 case Eq:
2367 return PyCmp_EQ;
2368 case NotEq:
2369 return PyCmp_NE;
2370 case Lt:
2371 return PyCmp_LT;
2372 case LtE:
2373 return PyCmp_LE;
2374 case Gt:
2375 return PyCmp_GT;
2376 case GtE:
2377 return PyCmp_GE;
2378 case Is:
2379 return PyCmp_IS;
2380 case IsNot:
2381 return PyCmp_IS_NOT;
2382 case In:
2383 return PyCmp_IN;
2384 case NotIn:
2385 return PyCmp_NOT_IN;
2386 }
2387 return PyCmp_BAD;
2388}
2389
2390static int
2391inplace_binop(struct compiler *c, operator_ty op)
2392{
2393 switch (op) {
2394 case Add:
2395 return INPLACE_ADD;
2396 case Sub:
2397 return INPLACE_SUBTRACT;
2398 case Mult:
2399 return INPLACE_MULTIPLY;
2400 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002401 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002402 case Mod:
2403 return INPLACE_MODULO;
2404 case Pow:
2405 return INPLACE_POWER;
2406 case LShift:
2407 return INPLACE_LSHIFT;
2408 case RShift:
2409 return INPLACE_RSHIFT;
2410 case BitOr:
2411 return INPLACE_OR;
2412 case BitXor:
2413 return INPLACE_XOR;
2414 case BitAnd:
2415 return INPLACE_AND;
2416 case FloorDiv:
2417 return INPLACE_FLOOR_DIVIDE;
2418 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002419 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002420 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421 return 0;
2422}
2423
2424static int
2425compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2426{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002427 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2429
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002430 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002431 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432 /* XXX AugStore isn't used anywhere! */
2433
2434 /* First check for assignment to __debug__. Param? */
2435 if ((ctx == Store || ctx == AugStore || ctx == Del)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002436 && !PyUnicode_CompareWithASCIIString(name, "__debug__")) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 return compiler_error(c, "can not assign to __debug__");
2438 }
2439
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002440 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002441 if (!mangled)
2442 return 0;
2443
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 op = 0;
2445 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002446 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447 switch (scope) {
2448 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002449 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 optype = OP_DEREF;
2451 break;
2452 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002453 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 optype = OP_DEREF;
2455 break;
2456 case LOCAL:
2457 if (c->u->u_ste->ste_type == FunctionBlock)
2458 optype = OP_FAST;
2459 break;
2460 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002461 if (c->u->u_ste->ste_type == FunctionBlock &&
2462 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 optype = OP_GLOBAL;
2464 break;
2465 case GLOBAL_EXPLICIT:
2466 optype = OP_GLOBAL;
2467 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002468 default:
2469 /* scope can be 0 */
2470 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 }
2472
2473 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002474 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475
2476 switch (optype) {
2477 case OP_DEREF:
2478 switch (ctx) {
2479 case Load: op = LOAD_DEREF; break;
2480 case Store: op = STORE_DEREF; break;
2481 case AugLoad:
2482 case AugStore:
2483 break;
2484 case Del:
2485 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002486 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002488 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002489 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002492 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002493 PyErr_SetString(PyExc_SystemError,
2494 "param invalid for deref variable");
2495 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496 }
2497 break;
2498 case OP_FAST:
2499 switch (ctx) {
2500 case Load: op = LOAD_FAST; break;
2501 case Store: op = STORE_FAST; break;
2502 case Del: op = DELETE_FAST; break;
2503 case AugLoad:
2504 case AugStore:
2505 break;
2506 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002507 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002508 PyErr_SetString(PyExc_SystemError,
2509 "param invalid for local variable");
2510 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002512 ADDOP_O(c, op, mangled, varnames);
2513 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514 return 1;
2515 case OP_GLOBAL:
2516 switch (ctx) {
2517 case Load: op = LOAD_GLOBAL; break;
2518 case Store: op = STORE_GLOBAL; break;
2519 case Del: op = DELETE_GLOBAL; break;
2520 case AugLoad:
2521 case AugStore:
2522 break;
2523 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002524 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002525 PyErr_SetString(PyExc_SystemError,
2526 "param invalid for global variable");
2527 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002528 }
2529 break;
2530 case OP_NAME:
2531 switch (ctx) {
2532 case Load: op = LOAD_NAME; break;
2533 case Store: op = STORE_NAME; break;
2534 case Del: op = DELETE_NAME; break;
2535 case AugLoad:
2536 case AugStore:
2537 break;
2538 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002539 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002540 PyErr_SetString(PyExc_SystemError,
2541 "param invalid for name variable");
2542 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 }
2544 break;
2545 }
2546
2547 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002548 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002549 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002550 if (arg < 0)
2551 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002552 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553}
2554
2555static int
2556compiler_boolop(struct compiler *c, expr_ty e)
2557{
2558 basicblock *end;
2559 int jumpi, i, n;
2560 asdl_seq *s;
2561
2562 assert(e->kind == BoolOp_kind);
2563 if (e->v.BoolOp.op == And)
2564 jumpi = JUMP_IF_FALSE;
2565 else
2566 jumpi = JUMP_IF_TRUE;
2567 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002568 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569 return 0;
2570 s = e->v.BoolOp.values;
2571 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002572 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002574 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575 ADDOP_JREL(c, jumpi, end);
2576 ADDOP(c, POP_TOP)
2577 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002578 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579 compiler_use_next_block(c, end);
2580 return 1;
2581}
2582
2583static int
2584compiler_list(struct compiler *c, expr_ty e)
2585{
2586 int n = asdl_seq_LEN(e->v.List.elts);
2587 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002588 int i, seen_star = 0;
2589 for (i = 0; i < n; i++) {
2590 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2591 if (elt->kind == Starred_kind && !seen_star) {
2592 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2593 seen_star = 1;
2594 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2595 } else if (elt->kind == Starred_kind) {
2596 return compiler_error(c,
2597 "two starred expressions in assignment");
2598 }
2599 }
2600 if (!seen_star) {
2601 ADDOP_I(c, UNPACK_SEQUENCE, n);
2602 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 }
2604 VISIT_SEQ(c, expr, e->v.List.elts);
2605 if (e->v.List.ctx == Load) {
2606 ADDOP_I(c, BUILD_LIST, n);
2607 }
2608 return 1;
2609}
2610
2611static int
2612compiler_tuple(struct compiler *c, expr_ty e)
2613{
2614 int n = asdl_seq_LEN(e->v.Tuple.elts);
2615 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002616 int i, seen_star = 0;
2617 for (i = 0; i < n; i++) {
2618 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2619 if (elt->kind == Starred_kind && !seen_star) {
2620 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2621 seen_star = 1;
2622 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2623 } else if (elt->kind == Starred_kind) {
2624 return compiler_error(c,
2625 "two starred expressions in assignment");
2626 }
2627 }
2628 if (!seen_star) {
2629 ADDOP_I(c, UNPACK_SEQUENCE, n);
2630 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 }
2632 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2633 if (e->v.Tuple.ctx == Load) {
2634 ADDOP_I(c, BUILD_TUPLE, n);
2635 }
2636 return 1;
2637}
2638
2639static int
2640compiler_compare(struct compiler *c, expr_ty e)
2641{
2642 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002643 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644
2645 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2646 VISIT(c, expr, e->v.Compare.left);
2647 n = asdl_seq_LEN(e->v.Compare.ops);
2648 assert(n > 0);
2649 if (n > 1) {
2650 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 if (cleanup == NULL)
2652 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002653 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002654 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655 }
2656 for (i = 1; i < n; i++) {
2657 ADDOP(c, DUP_TOP);
2658 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002660 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002661 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2663 NEXT_BLOCK(c);
2664 ADDOP(c, POP_TOP);
2665 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002666 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002667 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002669 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002671 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 if (n > 1) {
2673 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002674 if (end == NULL)
2675 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 ADDOP_JREL(c, JUMP_FORWARD, end);
2677 compiler_use_next_block(c, cleanup);
2678 ADDOP(c, ROT_TWO);
2679 ADDOP(c, POP_TOP);
2680 compiler_use_next_block(c, end);
2681 }
2682 return 1;
2683}
2684
2685static int
2686compiler_call(struct compiler *c, expr_ty e)
2687{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002689 return compiler_call_helper(c, 0,
2690 e->v.Call.args,
2691 e->v.Call.keywords,
2692 e->v.Call.starargs,
2693 e->v.Call.kwargs);
2694}
2695
2696/* shared code between compiler_call and compiler_class */
2697static int
2698compiler_call_helper(struct compiler *c,
2699 int n, /* Args already pushed */
2700 asdl_seq *args,
2701 asdl_seq *keywords,
2702 expr_ty starargs,
2703 expr_ty kwargs)
2704{
2705 int code = 0;
2706
2707 n += asdl_seq_LEN(args);
2708 VISIT_SEQ(c, expr, args);
2709 if (keywords) {
2710 VISIT_SEQ(c, keyword, keywords);
2711 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002713 if (starargs) {
2714 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 code |= 1;
2716 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002717 if (kwargs) {
2718 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 code |= 2;
2720 }
2721 switch (code) {
2722 case 0:
2723 ADDOP_I(c, CALL_FUNCTION, n);
2724 break;
2725 case 1:
2726 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2727 break;
2728 case 2:
2729 ADDOP_I(c, CALL_FUNCTION_KW, n);
2730 break;
2731 case 3:
2732 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2733 break;
2734 }
2735 return 1;
2736}
2737
Nick Coghlan650f0d02007-04-15 12:05:43 +00002738
2739/* List and set comprehensions and generator expressions work by creating a
2740 nested function to perform the actual iteration. This means that the
2741 iteration variables don't leak into the current scope.
2742 The defined function is called immediately following its definition, with the
2743 result of that call being the result of the expression.
2744 The LC/SC version returns the populated container, while the GE version is
2745 flagged in symtable.c as a generator, so it returns the generator object
2746 when the function is called.
2747 This code *knows* that the loop cannot contain break, continue, or return,
2748 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2749
2750 Possible cleanups:
2751 - iterate over the generator sequence instead of using recursion
2752*/
2753
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002755compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
2756 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002757 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758{
2759 /* generate code for the iterator, then each of the ifs,
2760 and then write to the element */
2761
Nick Coghlan650f0d02007-04-15 12:05:43 +00002762 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002764 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002765
2766 start = compiler_new_block(c);
2767 skip = compiler_new_block(c);
2768 if_cleanup = compiler_new_block(c);
2769 anchor = compiler_new_block(c);
2770
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002771 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002772 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774
Nick Coghlan650f0d02007-04-15 12:05:43 +00002775 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777 if (gen_index == 0) {
2778 /* Receive outermost iter as an implicit argument */
2779 c->u->u_argcount = 1;
2780 ADDOP_I(c, LOAD_FAST, 0);
2781 }
2782 else {
2783 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002784 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785 ADDOP(c, GET_ITER);
2786 }
2787 compiler_use_next_block(c, start);
2788 ADDOP_JREL(c, FOR_ITER, anchor);
2789 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002790 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002792 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002793 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002795 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 VISIT(c, expr, e);
2797 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2798 NEXT_BLOCK(c);
2799 ADDOP(c, POP_TOP);
2800 }
2801
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002802 if (++gen_index < asdl_seq_LEN(generators))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002803 if (!compiler_comprehension_generator(c, tmpname,
2804 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002805 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002806 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Nick Coghlan650f0d02007-04-15 12:05:43 +00002808 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002809 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002810 /* comprehension specific code */
2811 switch (type) {
2812 case COMP_GENEXP:
2813 VISIT(c, expr, elt);
2814 ADDOP(c, YIELD_VALUE);
2815 ADDOP(c, POP_TOP);
2816 break;
2817 case COMP_LISTCOMP:
2818 if (!compiler_nameop(c, tmpname, Load))
2819 return 0;
2820 VISIT(c, expr, elt);
2821 ADDOP(c, LIST_APPEND);
2822 break;
2823 case COMP_SETCOMP:
2824 if (!compiler_nameop(c, tmpname, Load))
2825 return 0;
2826 VISIT(c, expr, elt);
2827 ADDOP(c, SET_ADD);
2828 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002829 case COMP_DICTCOMP:
2830 if (!compiler_nameop(c, tmpname, Load))
2831 return 0;
2832 /* With 'd[k] = v', v is evaluated before k, so we do
2833 the same. STORE_SUBSCR requires (item, map, key),
2834 so we still end up ROTing once. */
2835 VISIT(c, expr, val);
2836 ADDOP(c, ROT_TWO);
2837 VISIT(c, expr, elt);
2838 ADDOP(c, STORE_SUBSCR);
2839 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002840 default:
2841 return 0;
2842 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
2844 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 for (i = 0; i < n; i++) {
2847 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002848 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851 ADDOP(c, POP_TOP);
2852 }
2853 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2854 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855
2856 return 1;
2857}
2858
2859static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002860compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002861 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002862{
2863 PyCodeObject *co = NULL;
2864 identifier tmp = NULL;
2865 expr_ty outermost_iter;
2866
2867 outermost_iter = ((comprehension_ty)
2868 asdl_seq_GET(generators, 0))->iter;
2869
2870 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2871 goto error;
2872
2873 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002874 int op;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875 tmp = compiler_new_tmpname(c);
2876 if (!tmp)
2877 goto error_in_scope;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002878 switch (type) {
2879 case COMP_LISTCOMP:
2880 op = BUILD_LIST;
2881 break;
2882 case COMP_SETCOMP:
2883 op = BUILD_SET;
2884 break;
2885 case COMP_DICTCOMP:
2886 op = BUILD_MAP;
2887 break;
2888 default:
2889 PyErr_Format(PyExc_SystemError,
2890 "unknown comprehension type %d", type);
2891 goto error_in_scope;
2892 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002893
Guido van Rossum992d4a32007-07-11 13:09:30 +00002894 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002895 ADDOP(c, DUP_TOP);
2896 if (!compiler_nameop(c, tmp, Store))
2897 goto error_in_scope;
2898 }
2899
Guido van Rossum992d4a32007-07-11 13:09:30 +00002900 if (!compiler_comprehension_generator(c, tmp, generators, 0, elt,
2901 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002902 goto error_in_scope;
2903
2904 if (type != COMP_GENEXP) {
2905 ADDOP(c, RETURN_VALUE);
2906 }
2907
2908 co = assemble(c, 1);
2909 compiler_exit_scope(c);
2910 if (co == NULL)
2911 goto error;
2912
2913 if (!compiler_make_closure(c, co, 0))
2914 goto error;
2915 Py_DECREF(co);
2916 Py_XDECREF(tmp);
2917
2918 VISIT(c, expr, outermost_iter);
2919 ADDOP(c, GET_ITER);
2920 ADDOP_I(c, CALL_FUNCTION, 1);
2921 return 1;
2922error_in_scope:
2923 compiler_exit_scope(c);
2924error:
2925 Py_XDECREF(co);
2926 Py_XDECREF(tmp);
2927 return 0;
2928}
2929
2930static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931compiler_genexp(struct compiler *c, expr_ty e)
2932{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002933 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002934 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002935 name = PyUnicode_FromString("<genexp>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002936 if (!name)
2937 return 0;
2938 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002939 assert(e->kind == GeneratorExp_kind);
2940 return compiler_comprehension(c, e, COMP_GENEXP, name,
2941 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002942 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943}
2944
2945static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002946compiler_listcomp(struct compiler *c, expr_ty e)
2947{
2948 static identifier name;
2949 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002950 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002951 if (!name)
2952 return 0;
2953 }
2954 assert(e->kind == ListComp_kind);
2955 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2956 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002957 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002958}
2959
2960static int
2961compiler_setcomp(struct compiler *c, expr_ty e)
2962{
2963 static identifier name;
2964 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002965 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002966 if (!name)
2967 return 0;
2968 }
2969 assert(e->kind == SetComp_kind);
2970 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2971 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002972 e->v.SetComp.elt, NULL);
2973}
2974
2975
2976static int
2977compiler_dictcomp(struct compiler *c, expr_ty e)
2978{
2979 static identifier name;
2980 if (!name) {
2981 name = PyString_FromString("<dictcomp>");
2982 if (!name)
2983 return 0;
2984 }
2985 assert(e->kind == DictComp_kind);
2986 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2987 e->v.DictComp.generators,
2988 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002989}
2990
2991
2992static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993compiler_visit_keyword(struct compiler *c, keyword_ty k)
2994{
2995 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2996 VISIT(c, expr, k->value);
2997 return 1;
2998}
2999
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003000/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001 whether they are true or false.
3002
3003 Return values: 1 for true, 0 for false, -1 for non-constant.
3004 */
3005
3006static int
3007expr_constant(expr_ty e)
3008{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003009 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003011 case Ellipsis_kind:
3012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013 case Num_kind:
3014 return PyObject_IsTrue(e->v.Num.n);
3015 case Str_kind:
3016 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003017 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003018 /* optimize away names that can't be reassigned */
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003019 id = PyString_AS_STRING(
3020 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003021 if (strcmp(id, "True") == 0) return 1;
3022 if (strcmp(id, "False") == 0) return 0;
3023 if (strcmp(id, "None") == 0) return 0;
3024 if (strcmp(id, "__debug__") == 0)
3025 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003026 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 default:
3028 return -1;
3029 }
3030}
3031
Guido van Rossumc2e20742006-02-27 22:32:47 +00003032/*
3033 Implements the with statement from PEP 343.
3034
3035 The semantics outlined in that PEP are as follows:
3036
3037 with EXPR as VAR:
3038 BLOCK
3039
3040 It is implemented roughly as:
3041
Thomas Wouters477c8d52006-05-27 19:21:47 +00003042 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003043 exit = context.__exit__ # not calling it
3044 value = context.__enter__()
3045 try:
3046 VAR = value # if VAR present in the syntax
3047 BLOCK
3048 finally:
3049 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003050 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003051 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003052 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003053 exit(*exc)
3054 */
3055static int
3056compiler_with(struct compiler *c, stmt_ty s)
3057{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003058 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003059 basicblock *block, *finally;
3060 identifier tmpexit, tmpvalue = NULL;
3061
3062 assert(s->kind == With_kind);
3063
Guido van Rossumc2e20742006-02-27 22:32:47 +00003064 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003065 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003066 if (!enter_attr)
3067 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003068 }
3069 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003070 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003071 if (!exit_attr)
3072 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003073 }
3074
3075 block = compiler_new_block(c);
3076 finally = compiler_new_block(c);
3077 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003078 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079
3080 /* Create a temporary variable to hold context.__exit__ */
3081 tmpexit = compiler_new_tmpname(c);
3082 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003083 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003084 PyArena_AddPyObject(c->c_arena, tmpexit);
3085
3086 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003087 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003088 We need to do this rather than preserving it on the stack
3089 because SETUP_FINALLY remembers the stack level.
3090 We need to do the assignment *inside* the try/finally
3091 so that context.__exit__() is called when the assignment
3092 fails. But we need to call context.__enter__() *before*
3093 the try/finally so that if it fails we won't call
3094 context.__exit__().
3095 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003096 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003097 if (tmpvalue == NULL)
3098 return 0;
3099 PyArena_AddPyObject(c->c_arena, tmpvalue);
3100 }
3101
Thomas Wouters477c8d52006-05-27 19:21:47 +00003102 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003103 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003104
3105 /* Squirrel away context.__exit__ */
3106 ADDOP(c, DUP_TOP);
3107 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3108 if (!compiler_nameop(c, tmpexit, Store))
3109 return 0;
3110
3111 /* Call context.__enter__() */
3112 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3113 ADDOP_I(c, CALL_FUNCTION, 0);
3114
3115 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 /* Store it in tmpvalue */
3117 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003118 return 0;
3119 }
3120 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003121 /* Discard result from context.__enter__() */
3122 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003123 }
3124
3125 /* Start the try block */
3126 ADDOP_JREL(c, SETUP_FINALLY, finally);
3127
3128 compiler_use_next_block(c, block);
3129 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003130 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003131 }
3132
3133 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 /* Bind saved result of context.__enter__() to VAR */
3135 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003136 !compiler_nameop(c, tmpvalue, Del))
3137 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003139 }
3140
3141 /* BLOCK code */
3142 VISIT_SEQ(c, stmt, s->v.With.body);
3143
3144 /* End of try block; start the finally block */
3145 ADDOP(c, POP_BLOCK);
3146 compiler_pop_fblock(c, FINALLY_TRY, block);
3147
3148 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3149 compiler_use_next_block(c, finally);
3150 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003151 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003152
3153 /* Finally block starts; push tmpexit and issue our magic opcode. */
3154 if (!compiler_nameop(c, tmpexit, Load) ||
3155 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003157 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003158
3159 /* Finally block ends. */
3160 ADDOP(c, END_FINALLY);
3161 compiler_pop_fblock(c, FINALLY_END, finally);
3162 return 1;
3163}
3164
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165static int
3166compiler_visit_expr(struct compiler *c, expr_ty e)
3167{
3168 int i, n;
3169
Thomas Wouters89f507f2006-12-13 04:49:30 +00003170 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003171 set a new line number for the next instruction.
3172 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173 if (e->lineno > c->u->u_lineno) {
3174 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003175 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176 }
3177 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003178 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003180 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181 VISIT(c, expr, e->v.BinOp.left);
3182 VISIT(c, expr, e->v.BinOp.right);
3183 ADDOP(c, binop(c, e->v.BinOp.op));
3184 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003185 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186 VISIT(c, expr, e->v.UnaryOp.operand);
3187 ADDOP(c, unaryop(e->v.UnaryOp.op));
3188 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003189 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003191 case IfExp_kind:
3192 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 /* XXX get rid of arg? */
3195 ADDOP_I(c, BUILD_MAP, 0);
3196 n = asdl_seq_LEN(e->v.Dict.values);
3197 /* We must arrange things just right for STORE_SUBSCR.
3198 It wants the stack to look like (value) (dict) (key) */
3199 for (i = 0; i < n; i++) {
3200 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003201 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003202 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003204 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003205 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 ADDOP(c, STORE_SUBSCR);
3207 }
3208 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003209 case Set_kind:
3210 n = asdl_seq_LEN(e->v.Set.elts);
3211 VISIT_SEQ(c, expr, e->v.Set.elts);
3212 ADDOP_I(c, BUILD_SET, n);
3213 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003214 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003215 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003216 case ListComp_kind:
3217 return compiler_listcomp(c, e);
3218 case SetComp_kind:
3219 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003220 case DictComp_kind:
3221 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 case Yield_kind:
3223 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003224 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225 if (e->v.Yield.value) {
3226 VISIT(c, expr, e->v.Yield.value);
3227 }
3228 else {
3229 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3230 }
3231 ADDOP(c, YIELD_VALUE);
3232 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003233 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003237 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3239 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003240 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003241 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3242 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003243 case Bytes_kind:
3244 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3245 ADDOP(c, MAKE_BYTES);
3246 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003247 case Ellipsis_kind:
3248 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3249 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003251 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 if (e->v.Attribute.ctx != AugStore)
3253 VISIT(c, expr, e->v.Attribute.value);
3254 switch (e->v.Attribute.ctx) {
3255 case AugLoad:
3256 ADDOP(c, DUP_TOP);
3257 /* Fall through to load */
3258 case Load:
3259 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3260 break;
3261 case AugStore:
3262 ADDOP(c, ROT_TWO);
3263 /* Fall through to save */
3264 case Store:
3265 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3266 break;
3267 case Del:
3268 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3269 break;
3270 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003271 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003272 PyErr_SetString(PyExc_SystemError,
3273 "param invalid in attribute expression");
3274 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 }
3276 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003277 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278 switch (e->v.Subscript.ctx) {
3279 case AugLoad:
3280 VISIT(c, expr, e->v.Subscript.value);
3281 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3282 break;
3283 case Load:
3284 VISIT(c, expr, e->v.Subscript.value);
3285 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3286 break;
3287 case AugStore:
3288 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3289 break;
3290 case Store:
3291 VISIT(c, expr, e->v.Subscript.value);
3292 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3293 break;
3294 case Del:
3295 VISIT(c, expr, e->v.Subscript.value);
3296 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3297 break;
3298 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003299 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003300 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003301 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003302 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 }
3304 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003305 case Starred_kind:
3306 switch (e->v.Starred.ctx) {
3307 case Store:
3308 /* In all legitimate cases, the Starred node was already replaced
3309 * by compiler_list/compiler_tuple. XXX: is that okay? */
3310 return compiler_error(c,
3311 "starred assignment target must be in a list or tuple");
3312 default:
3313 return compiler_error(c,
3314 "can use starred expression only as assignment target");
3315 }
3316 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003317 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3319 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003320 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003322 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323 return compiler_tuple(c, e);
3324 }
3325 return 1;
3326}
3327
3328static int
3329compiler_augassign(struct compiler *c, stmt_ty s)
3330{
3331 expr_ty e = s->v.AugAssign.target;
3332 expr_ty auge;
3333
3334 assert(s->kind == AugAssign_kind);
3335
3336 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003337 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003339 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003340 if (auge == NULL)
3341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342 VISIT(c, expr, auge);
3343 VISIT(c, expr, s->v.AugAssign.value);
3344 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3345 auge->v.Attribute.ctx = AugStore;
3346 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347 break;
3348 case Subscript_kind:
3349 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003350 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003351 if (auge == NULL)
3352 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353 VISIT(c, expr, auge);
3354 VISIT(c, expr, s->v.AugAssign.value);
3355 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003356 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003358 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003360 if (!compiler_nameop(c, e->v.Name.id, Load))
3361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003362 VISIT(c, expr, s->v.AugAssign.value);
3363 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3364 return compiler_nameop(c, e->v.Name.id, Store);
3365 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003366 PyErr_Format(PyExc_SystemError,
3367 "invalid node type (%d) for augmented assignment",
3368 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003369 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003370 }
3371 return 1;
3372}
3373
3374static int
3375compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3376{
3377 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003378 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3379 PyErr_SetString(PyExc_SystemError,
3380 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003382 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003383 f = &c->u->u_fblock[c->u->u_nfblocks++];
3384 f->fb_type = t;
3385 f->fb_block = b;
3386 return 1;
3387}
3388
3389static void
3390compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3391{
3392 struct compiler_unit *u = c->u;
3393 assert(u->u_nfblocks > 0);
3394 u->u_nfblocks--;
3395 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3396 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3397}
3398
Thomas Wouters89f507f2006-12-13 04:49:30 +00003399static int
3400compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003401 int i;
3402 struct compiler_unit *u = c->u;
3403 for (i = 0; i < u->u_nfblocks; ++i) {
3404 if (u->u_fblock[i].fb_type == LOOP)
3405 return 1;
3406 }
3407 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003408}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003409/* Raises a SyntaxError and returns 0.
3410 If something goes wrong, a different exception may be raised.
3411*/
3412
3413static int
3414compiler_error(struct compiler *c, const char *errstr)
3415{
3416 PyObject *loc;
3417 PyObject *u = NULL, *v = NULL;
3418
3419 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3420 if (!loc) {
3421 Py_INCREF(Py_None);
3422 loc = Py_None;
3423 }
3424 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3425 Py_None, loc);
3426 if (!u)
3427 goto exit;
3428 v = Py_BuildValue("(zO)", errstr, u);
3429 if (!v)
3430 goto exit;
3431 PyErr_SetObject(PyExc_SyntaxError, v);
3432 exit:
3433 Py_DECREF(loc);
3434 Py_XDECREF(u);
3435 Py_XDECREF(v);
3436 return 0;
3437}
3438
3439static int
3440compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003441 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003443 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003445 /* XXX this code is duplicated */
3446 switch (ctx) {
3447 case AugLoad: /* fall through to Load */
3448 case Load: op = BINARY_SUBSCR; break;
3449 case AugStore:/* fall through to Store */
3450 case Store: op = STORE_SUBSCR; break;
3451 case Del: op = DELETE_SUBSCR; break;
3452 case Param:
3453 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003454 "invalid %s kind %d in subscript\n",
3455 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003456 return 0;
3457 }
3458 if (ctx == AugLoad) {
3459 ADDOP_I(c, DUP_TOPX, 2);
3460 }
3461 else if (ctx == AugStore) {
3462 ADDOP(c, ROT_THREE);
3463 }
3464 ADDOP(c, op);
3465 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466}
3467
3468static int
3469compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3470{
3471 int n = 2;
3472 assert(s->kind == Slice_kind);
3473
3474 /* only handles the cases where BUILD_SLICE is emitted */
3475 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003476 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477 }
3478 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003479 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003483 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484 }
3485 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003486 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003487 }
3488
3489 if (s->v.Slice.step) {
3490 n++;
3491 VISIT(c, expr, s->v.Slice.step);
3492 }
3493 ADDOP_I(c, BUILD_SLICE, n);
3494 return 1;
3495}
3496
3497static int
3498compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3499{
3500 int op = 0, slice_offset = 0, stack_count = 0;
3501
3502 assert(s->v.Slice.step == NULL);
3503 if (s->v.Slice.lower) {
3504 slice_offset++;
3505 stack_count++;
3506 if (ctx != AugStore)
3507 VISIT(c, expr, s->v.Slice.lower);
3508 }
3509 if (s->v.Slice.upper) {
3510 slice_offset += 2;
3511 stack_count++;
3512 if (ctx != AugStore)
3513 VISIT(c, expr, s->v.Slice.upper);
3514 }
3515
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003516 if (ctx == AugLoad) {
3517 switch (stack_count) {
3518 case 0: ADDOP(c, DUP_TOP); break;
3519 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3520 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3521 }
3522 }
3523 else if (ctx == AugStore) {
3524 switch (stack_count) {
3525 case 0: ADDOP(c, ROT_TWO); break;
3526 case 1: ADDOP(c, ROT_THREE); break;
3527 case 2: ADDOP(c, ROT_FOUR); break;
3528 }
3529 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530
3531 switch (ctx) {
3532 case AugLoad: /* fall through to Load */
3533 case Load: op = SLICE; break;
3534 case AugStore:/* fall through to Store */
3535 case Store: op = STORE_SLICE; break;
3536 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003537 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003538 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003539 PyErr_SetString(PyExc_SystemError,
3540 "param invalid in simple slice");
3541 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542 }
3543
3544 ADDOP(c, op + slice_offset);
3545 return 1;
3546}
3547
3548static int
3549compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3550 expr_context_ty ctx)
3551{
3552 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 case Slice_kind:
3554 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 case Index_kind:
3556 VISIT(c, expr, s->v.Index.value);
3557 break;
3558 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003559 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003560 PyErr_SetString(PyExc_SystemError,
3561 "extended slice invalid in nested slice");
3562 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 }
3564 return 1;
3565}
3566
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567static int
3568compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3569{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003570 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003572 case Index_kind:
3573 kindname = "index";
3574 if (ctx != AugStore) {
3575 VISIT(c, expr, s->v.Index.value);
3576 }
3577 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003579 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 if (!s->v.Slice.step)
3581 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003582 if (ctx != AugStore) {
3583 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584 return 0;
3585 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003586 break;
3587 case ExtSlice_kind:
3588 kindname = "extended slice";
3589 if (ctx != AugStore) {
3590 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3591 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003592 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003593 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003594 if (!compiler_visit_nested_slice(c, sub, ctx))
3595 return 0;
3596 }
3597 ADDOP_I(c, BUILD_TUPLE, n);
3598 }
3599 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003600 default:
3601 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003602 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003603 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003605 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606}
3607
Thomas Wouters89f507f2006-12-13 04:49:30 +00003608/* End of the compiler section, beginning of the assembler section */
3609
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610/* do depth-first search of basic block graph, starting with block.
3611 post records the block indices in post-order.
3612
3613 XXX must handle implicit jumps from one block to next
3614*/
3615
Thomas Wouters89f507f2006-12-13 04:49:30 +00003616struct assembler {
3617 PyObject *a_bytecode; /* string containing bytecode */
3618 int a_offset; /* offset into bytecode */
3619 int a_nblocks; /* number of reachable blocks */
3620 basicblock **a_postorder; /* list of blocks in dfs postorder */
3621 PyObject *a_lnotab; /* string containing lnotab */
3622 int a_lnotab_off; /* offset into lnotab */
3623 int a_lineno; /* last lineno of emitted instruction */
3624 int a_lineno_off; /* bytecode offset of last lineno */
3625};
3626
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627static void
3628dfs(struct compiler *c, basicblock *b, struct assembler *a)
3629{
3630 int i;
3631 struct instr *instr = NULL;
3632
3633 if (b->b_seen)
3634 return;
3635 b->b_seen = 1;
3636 if (b->b_next != NULL)
3637 dfs(c, b->b_next, a);
3638 for (i = 0; i < b->b_iused; i++) {
3639 instr = &b->b_instr[i];
3640 if (instr->i_jrel || instr->i_jabs)
3641 dfs(c, instr->i_target, a);
3642 }
3643 a->a_postorder[a->a_nblocks++] = b;
3644}
3645
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003646static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3648{
3649 int i;
3650 struct instr *instr;
3651 if (b->b_seen || b->b_startdepth >= depth)
3652 return maxdepth;
3653 b->b_seen = 1;
3654 b->b_startdepth = depth;
3655 for (i = 0; i < b->b_iused; i++) {
3656 instr = &b->b_instr[i];
3657 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3658 if (depth > maxdepth)
3659 maxdepth = depth;
3660 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3661 if (instr->i_jrel || instr->i_jabs) {
3662 maxdepth = stackdepth_walk(c, instr->i_target,
3663 depth, maxdepth);
3664 if (instr->i_opcode == JUMP_ABSOLUTE ||
3665 instr->i_opcode == JUMP_FORWARD) {
3666 goto out; /* remaining code is dead */
3667 }
3668 }
3669 }
3670 if (b->b_next)
3671 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3672out:
3673 b->b_seen = 0;
3674 return maxdepth;
3675}
3676
3677/* Find the flow path that needs the largest stack. We assume that
3678 * cycles in the flow graph have no net effect on the stack depth.
3679 */
3680static int
3681stackdepth(struct compiler *c)
3682{
3683 basicblock *b, *entryblock;
3684 entryblock = NULL;
3685 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3686 b->b_seen = 0;
3687 b->b_startdepth = INT_MIN;
3688 entryblock = b;
3689 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003690 if (!entryblock)
3691 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003692 return stackdepth_walk(c, entryblock, 0, 0);
3693}
3694
3695static int
3696assemble_init(struct assembler *a, int nblocks, int firstlineno)
3697{
3698 memset(a, 0, sizeof(struct assembler));
3699 a->a_lineno = firstlineno;
3700 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3701 if (!a->a_bytecode)
3702 return 0;
3703 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3704 if (!a->a_lnotab)
3705 return 0;
3706 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003707 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003708 if (!a->a_postorder) {
3709 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003711 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003712 return 1;
3713}
3714
3715static void
3716assemble_free(struct assembler *a)
3717{
3718 Py_XDECREF(a->a_bytecode);
3719 Py_XDECREF(a->a_lnotab);
3720 if (a->a_postorder)
3721 PyObject_Free(a->a_postorder);
3722}
3723
3724/* Return the size of a basic block in bytes. */
3725
3726static int
3727instrsize(struct instr *instr)
3728{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003729 if (!instr->i_hasarg)
3730 return 1;
3731 if (instr->i_oparg > 0xffff)
3732 return 6;
3733 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734}
3735
3736static int
3737blocksize(basicblock *b)
3738{
3739 int i;
3740 int size = 0;
3741
3742 for (i = 0; i < b->b_iused; i++)
3743 size += instrsize(&b->b_instr[i]);
3744 return size;
3745}
3746
3747/* All about a_lnotab.
3748
3749c_lnotab is an array of unsigned bytes disguised as a Python string.
3750It is used to map bytecode offsets to source code line #s (when needed
3751for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003752
Tim Peters2a7f3842001-06-09 09:26:21 +00003753The array is conceptually a list of
3754 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003755pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003756
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003757 byte code offset source code line number
3758 0 1
3759 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003760 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003761 350 307
3762 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003763
3764The first trick is that these numbers aren't stored, only the increments
3765from one row to the next (this doesn't really work, but it's a start):
3766
3767 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3768
3769The second trick is that an unsigned byte can't hold negative values, or
3770values larger than 255, so (a) there's a deep assumption that byte code
3771offsets and their corresponding line #s both increase monotonically, and (b)
3772if at least one column jumps by more than 255 from one row to the next, more
3773than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003774from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003775part. A user of c_lnotab desiring to find the source line number
3776corresponding to a bytecode address A should do something like this
3777
3778 lineno = addr = 0
3779 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003780 addr += addr_incr
3781 if addr > A:
3782 return lineno
3783 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003784
3785In order for this to work, when the addr field increments by more than 255,
3786the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003787increment is < 256. So, in the example above, assemble_lnotab (it used
3788to be called com_set_lineno) should not (as was actually done until 2.2)
3789expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003790 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003791*/
3792
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003793static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003795{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 int d_bytecode, d_lineno;
3797 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003798 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799
3800 d_bytecode = a->a_offset - a->a_lineno_off;
3801 d_lineno = i->i_lineno - a->a_lineno;
3802
3803 assert(d_bytecode >= 0);
3804 assert(d_lineno >= 0);
3805
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003806 /* XXX(nnorwitz): is there a better way to handle this?
3807 for loops are special, we want to be able to trace them
3808 each time around, so we need to set an extra line number. */
3809 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003810 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003811
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003813 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 nbytes = a->a_lnotab_off + 2 * ncodes;
3815 len = PyString_GET_SIZE(a->a_lnotab);
3816 if (nbytes >= len) {
3817 if (len * 2 < nbytes)
3818 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003819 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 len *= 2;
3821 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3822 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003823 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003824 lnotab = (unsigned char *)
3825 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003826 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 *lnotab++ = 255;
3828 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003829 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830 d_bytecode -= ncodes * 255;
3831 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003832 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833 assert(d_bytecode <= 255);
3834 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003835 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836 nbytes = a->a_lnotab_off + 2 * ncodes;
3837 len = PyString_GET_SIZE(a->a_lnotab);
3838 if (nbytes >= len) {
3839 if (len * 2 < nbytes)
3840 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003841 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842 len *= 2;
3843 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3844 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003845 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003846 lnotab = (unsigned char *)
3847 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003849 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003851 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003852 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003853 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003854 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855 d_lineno -= ncodes * 255;
3856 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003857 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 len = PyString_GET_SIZE(a->a_lnotab);
3860 if (a->a_lnotab_off + 2 >= len) {
3861 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003862 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003863 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003864 lnotab = (unsigned char *)
3865 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867 a->a_lnotab_off += 2;
3868 if (d_bytecode) {
3869 *lnotab++ = d_bytecode;
3870 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003871 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003872 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 *lnotab++ = 0;
3874 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003875 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 a->a_lineno = i->i_lineno;
3877 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003878 return 1;
3879}
3880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881/* assemble_emit()
3882 Extend the bytecode with a new instruction.
3883 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003884*/
3885
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003886static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003888{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003889 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003890 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 char *code;
3892
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003893 size = instrsize(i);
3894 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003896 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003897 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003899 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 if (a->a_offset + size >= len) {
3901 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003902 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003903 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3905 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003906 if (size == 6) {
3907 assert(i->i_hasarg);
3908 *code++ = (char)EXTENDED_ARG;
3909 *code++ = ext & 0xff;
3910 *code++ = ext >> 8;
3911 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003912 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003914 if (i->i_hasarg) {
3915 assert(size == 3 || size == 6);
3916 *code++ = arg & 0xff;
3917 *code++ = arg >> 8;
3918 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003919 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003920}
3921
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003922static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003924{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003925 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003926 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003927 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003929 /* Compute the size of each block and fixup jump args.
3930 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003931start:
3932 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003934 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935 bsize = blocksize(b);
3936 b->b_offset = totsize;
3937 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003938 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003939 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3941 bsize = b->b_offset;
3942 for (i = 0; i < b->b_iused; i++) {
3943 struct instr *instr = &b->b_instr[i];
3944 /* Relative jumps are computed relative to
3945 the instruction pointer after fetching
3946 the jump instruction.
3947 */
3948 bsize += instrsize(instr);
3949 if (instr->i_jabs)
3950 instr->i_oparg = instr->i_target->b_offset;
3951 else if (instr->i_jrel) {
3952 int delta = instr->i_target->b_offset - bsize;
3953 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003954 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003955 else
3956 continue;
3957 if (instr->i_oparg > 0xffff)
3958 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003959 }
3960 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003961
3962 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003963 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003964 with a better solution.
3965
3966 In the meantime, should the goto be dropped in favor
3967 of a loop?
3968
3969 The issue is that in the first loop blocksize() is called
3970 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003971 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003972 i_oparg is calculated in the second loop above.
3973
3974 So we loop until we stop seeing new EXTENDED_ARGs.
3975 The only EXTENDED_ARGs that could be popping up are
3976 ones in jump instructions. So this should converge
3977 fairly quickly.
3978 */
3979 if (last_extended_arg_count != extended_arg_count) {
3980 last_extended_arg_count = extended_arg_count;
3981 goto start;
3982 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003983}
3984
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003985static PyObject *
3986dict_keys_inorder(PyObject *dict, int offset)
3987{
3988 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003989 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003990
3991 tuple = PyTuple_New(size);
3992 if (tuple == NULL)
3993 return NULL;
3994 while (PyDict_Next(dict, &pos, &k, &v)) {
3995 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003996 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003997 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003998 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003999 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004000 PyTuple_SET_ITEM(tuple, i - offset, k);
4001 }
4002 return tuple;
4003}
4004
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004005static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004006compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004007{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004008 PySTEntryObject *ste = c->u->u_ste;
4009 int flags = 0, n;
4010 if (ste->ste_type != ModuleBlock)
4011 flags |= CO_NEWLOCALS;
4012 if (ste->ste_type == FunctionBlock) {
4013 if (!ste->ste_unoptimized)
4014 flags |= CO_OPTIMIZED;
4015 if (ste->ste_nested)
4016 flags |= CO_NESTED;
4017 if (ste->ste_generator)
4018 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004019 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020 if (ste->ste_varargs)
4021 flags |= CO_VARARGS;
4022 if (ste->ste_varkeywords)
4023 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004024 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004026
4027 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004028 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030 n = PyDict_Size(c->u->u_freevars);
4031 if (n < 0)
4032 return -1;
4033 if (n == 0) {
4034 n = PyDict_Size(c->u->u_cellvars);
4035 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004036 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004037 if (n == 0) {
4038 flags |= CO_NOFREE;
4039 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004040 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004041
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004042 return flags;
4043}
4044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004045static PyCodeObject *
4046makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004047{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004048 PyObject *tmp;
4049 PyCodeObject *co = NULL;
4050 PyObject *consts = NULL;
4051 PyObject *names = NULL;
4052 PyObject *varnames = NULL;
4053 PyObject *filename = NULL;
4054 PyObject *name = NULL;
4055 PyObject *freevars = NULL;
4056 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004057 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004058 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004060 tmp = dict_keys_inorder(c->u->u_consts, 0);
4061 if (!tmp)
4062 goto error;
4063 consts = PySequence_List(tmp); /* optimize_code requires a list */
4064 Py_DECREF(tmp);
4065
4066 names = dict_keys_inorder(c->u->u_names, 0);
4067 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4068 if (!consts || !names || !varnames)
4069 goto error;
4070
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004071 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4072 if (!cellvars)
4073 goto error;
4074 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4075 if (!freevars)
4076 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077 filename = PyString_FromString(c->c_filename);
4078 if (!filename)
4079 goto error;
4080
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004081 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082 flags = compute_code_flags(c);
4083 if (flags < 0)
4084 goto error;
4085
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004086 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004087 if (!bytecode)
4088 goto error;
4089
4090 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4091 if (!tmp)
4092 goto error;
4093 Py_DECREF(consts);
4094 consts = tmp;
4095
Guido van Rossum4f72a782006-10-27 23:31:49 +00004096 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4097 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098 bytecode, consts, names, varnames,
4099 freevars, cellvars,
4100 filename, c->u->u_name,
4101 c->u->u_firstlineno,
4102 a->a_lnotab);
4103 error:
4104 Py_XDECREF(consts);
4105 Py_XDECREF(names);
4106 Py_XDECREF(varnames);
4107 Py_XDECREF(filename);
4108 Py_XDECREF(name);
4109 Py_XDECREF(freevars);
4110 Py_XDECREF(cellvars);
4111 Py_XDECREF(bytecode);
4112 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004113}
4114
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004115
4116/* For debugging purposes only */
4117#if 0
4118static void
4119dump_instr(const struct instr *i)
4120{
4121 const char *jrel = i->i_jrel ? "jrel " : "";
4122 const char *jabs = i->i_jabs ? "jabs " : "";
4123 char arg[128];
4124
4125 *arg = '\0';
4126 if (i->i_hasarg)
4127 sprintf(arg, "arg: %d ", i->i_oparg);
4128
4129 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4130 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4131}
4132
4133static void
4134dump_basicblock(const basicblock *b)
4135{
4136 const char *seen = b->b_seen ? "seen " : "";
4137 const char *b_return = b->b_return ? "return " : "";
4138 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4139 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4140 if (b->b_instr) {
4141 int i;
4142 for (i = 0; i < b->b_iused; i++) {
4143 fprintf(stderr, " [%02d] ", i);
4144 dump_instr(b->b_instr + i);
4145 }
4146 }
4147}
4148#endif
4149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150static PyCodeObject *
4151assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004152{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 basicblock *b, *entryblock;
4154 struct assembler a;
4155 int i, j, nblocks;
4156 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158 /* Make sure every block that falls off the end returns None.
4159 XXX NEXT_BLOCK() isn't quite right, because if the last
4160 block ends with a jump or return b_next shouldn't set.
4161 */
4162 if (!c->u->u_curblock->b_return) {
4163 NEXT_BLOCK(c);
4164 if (addNone)
4165 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4166 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004167 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004168
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169 nblocks = 0;
4170 entryblock = NULL;
4171 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4172 nblocks++;
4173 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004174 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004175
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004176 /* Set firstlineno if it wasn't explicitly set. */
4177 if (!c->u->u_firstlineno) {
4178 if (entryblock && entryblock->b_instr)
4179 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4180 else
4181 c->u->u_firstlineno = 1;
4182 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4184 goto error;
4185 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004186
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004188 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190 /* Emit code in reverse postorder from dfs. */
4191 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004192 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004193 for (j = 0; j < b->b_iused; j++)
4194 if (!assemble_emit(&a, &b->b_instr[j]))
4195 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004196 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4199 goto error;
4200 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4201 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004202
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004203 co = makecode(c, &a);
4204 error:
4205 assemble_free(&a);
4206 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004207}