blob: ab51c7bb26b0e00d0545a05b537df91a4844efb8 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Guido van Rossumd8faa362007-04-27 19:54:29 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Nick Coghlan650f0d02007-04-15 12:05:43 +000042#define COMP_GENEXP 0
43#define COMP_LISTCOMP 1
44#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000045#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
50 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000072 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000073 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
88enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
89
90struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000091 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092 basicblock *fb_block;
93};
94
95/* The following items change on entry and exit of code blocks.
96 They must be saved and restored when returning to a block.
97*/
98struct compiler_unit {
99 PySTEntryObject *u_ste;
100
101 PyObject *u_name;
102 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000103 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000104 the argument for opcodes that refer to those collections.
105 */
106 PyObject *u_consts; /* all constants */
107 PyObject *u_names; /* all names */
108 PyObject *u_varnames; /* local variables */
109 PyObject *u_cellvars; /* cell variables */
110 PyObject *u_freevars; /* free variables */
111
112 PyObject *u_private; /* for private name mangling */
113
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000114 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000115 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 /* Pointer to the most recently allocated block. By following b_list
117 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
122 int u_nfblocks;
123 struct fblockinfo u_fblock[CO_MAXBLOCKS];
124
125 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000126 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000127 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128 has been generated with current lineno */
129};
130
131/* This struct captures the global state of a compilation.
132
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133The u pointer points to the current compilation unit, while units
134for enclosing blocks are stored in c_stack. The u and c_stack are
135managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136*/
137
138struct compiler {
139 const char *c_filename;
140 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142 PyCompilerFlags *c_flags;
143
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 struct compiler_unit *u; /* compiler state for current block */
148 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151};
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153static int compiler_enter_scope(struct compiler *, identifier, void *, int);
154static void compiler_free(struct compiler *);
155static basicblock *compiler_new_block(struct compiler *);
156static int compiler_next_instr(struct compiler *, basicblock *);
157static int compiler_addop(struct compiler *, int);
158static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
159static int compiler_addop_i(struct compiler *, int, int);
160static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161static basicblock *compiler_use_new_block(struct compiler *);
162static int compiler_error(struct compiler *, const char *);
163static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
164
165static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
166static int compiler_visit_stmt(struct compiler *, stmt_ty);
167static int compiler_visit_keyword(struct compiler *, keyword_ty);
168static int compiler_visit_expr(struct compiler *, expr_ty);
169static int compiler_augassign(struct compiler *, stmt_ty);
170static int compiler_visit_slice(struct compiler *, slice_ty,
171 expr_context_ty);
172
173static int compiler_push_fblock(struct compiler *, enum fblocktype,
174 basicblock *);
175static void compiler_pop_fblock(struct compiler *, enum fblocktype,
176 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177/* Returns true if there is a loop on the fblock stack. */
178static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179
180static int inplace_binop(struct compiler *, operator_ty);
181static int expr_constant(expr_ty e);
182
Guido van Rossumc2e20742006-02-27 22:32:47 +0000183static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000184static int compiler_call_helper(struct compiler *c, int n,
185 asdl_seq *args,
186 asdl_seq *keywords,
187 expr_ty starargs,
188 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static PyCodeObject *assemble(struct compiler *, int addNone);
191static PyObject *__doc__;
192
193PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000195{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 /* Name mangling: __private becomes _classname__private.
197 This is independent from how the name is used. */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000198 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
199 Py_UNICODE *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200 size_t nlen, plen;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000201 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000202 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000203 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000206 p = PyUnicode_AS_UNICODE(privateobj);
207 nlen = Py_UNICODE_strlen(name);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 /* Don't mangle __id__ or names with dots.
209
210 The only time a name with a dot can occur is when
211 we are compiling an import statement that has a
212 package name.
213
214 TODO(jhylton): Decide whether we want to support
215 mangling of the module name, e.g. __M.X.
216 */
217 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Martin v. Löwis5b222132007-06-10 09:51:05 +0000218 || Py_UNICODE_strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 /* Strip leading underscores from class name */
223 while (*p == '_')
224 p++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000225 if (*p == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000229 plen = Py_UNICODE_strlen(p);
230 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000231 if (!ident)
232 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000234 buffer = PyUnicode_AS_UNICODE(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 buffer[0] = '_';
Martin v. Löwis5b222132007-06-10 09:51:05 +0000236 Py_UNICODE_strncpy(buffer+1, p, plen);
237 Py_UNICODE_strcpy(buffer+1+plen, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000238 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000239}
240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241static int
242compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000243{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000245
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000246 c->c_stack = PyList_New(0);
247 if (!c->c_stack)
248 return 0;
249
250 return 1;
251}
252
253PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000254PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256{
257 struct compiler c;
258 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000259 PyCompilerFlags local_flags;
260 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000262 if (!__doc__) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000263 __doc__ = PyUnicode_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 if (!__doc__)
265 return NULL;
266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267
268 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000269 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000271 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272 c.c_future = PyFuture_FromAST(mod, filename);
273 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000274 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000275 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000276 local_flags.cf_flags = 0;
277 flags = &local_flags;
278 }
279 merged = c.c_future->ff_features | flags->cf_flags;
280 c.c_future->ff_features = merged;
281 flags->cf_flags = merged;
282 c.c_flags = flags;
283 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284
285 c.c_st = PySymtable_Build(mod, filename, c.c_future);
286 if (c.c_st == NULL) {
287 if (!PyErr_Occurred())
288 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000289 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290 }
291
292 /* XXX initialize to NULL for now, need to handle */
293 c.c_encoding = NULL;
294
295 co = compiler_mod(&c, mod);
296
Thomas Wouters1175c432006-02-27 22:49:54 +0000297 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000299 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300 return co;
301}
302
303PyCodeObject *
304PyNode_Compile(struct _node *n, const char *filename)
305{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000306 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000307 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000308 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000309 if (!arena)
310 return NULL;
311 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000312 if (mod)
313 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000314 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000315 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000316}
317
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321 if (c->c_st)
322 PySymtable_Free(c->c_st);
323 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000326}
327
Guido van Rossum79f25d91997-04-29 20:08:16 +0000328static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000330{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000331 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000332 PyObject *v, *k;
333 PyObject *dict = PyDict_New();
334 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000335
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336 n = PyList_Size(list);
337 for (i = 0; i < n; i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000338 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339 if (!v) {
340 Py_DECREF(dict);
341 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000342 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000343 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000344 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
346 Py_XDECREF(k);
347 Py_DECREF(v);
348 Py_DECREF(dict);
349 return NULL;
350 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000351 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354 return dict;
355}
356
357/* Return new dict containing names from src that match scope(s).
358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359src is a symbol table dictionary. If the scope of a name matches
360either scope_type or flag is set, insert it into the new dict. The
361values are integers, starting at offset and increasing by one for
362each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363*/
364
365static PyObject *
366dictbytype(PyObject *src, int scope_type, int flag, int offset)
367{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000368 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369 PyObject *k, *v, *dest = PyDict_New();
370
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000371 assert(offset >= 0);
372 if (dest == NULL)
373 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374
375 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000377 long vi;
Christian Heimes217cfd12007-12-02 14:31:20 +0000378 assert(PyLong_Check(v));
379 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000380 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000382 if (scope == scope_type || vi & flag) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000383 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 if (item == NULL) {
385 Py_DECREF(dest);
386 return NULL;
387 }
388 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000389 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000390 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
391 Py_DECREF(item);
392 Py_DECREF(dest);
393 Py_XDECREF(tuple);
394 return NULL;
395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399 }
400 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000401}
402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403static void
404compiler_unit_check(struct compiler_unit *u)
405{
406 basicblock *block;
407 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Christian Heimes77c02eb2008-02-09 02:18:51 +0000408 assert((void *)block != (void *)0xcbcbcbcb);
409 assert((void *)block != (void *)0xfbfbfbfb);
410 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000411 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
Christian Heimes2202f872008-02-06 14:31:34 +0000655/* Set the i_lineno member of the instruction at offset off if the
656 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 already been set. If it has been set, the call has no effect.
658
Christian Heimes2202f872008-02-06 14:31:34 +0000659 The line number is reset in the following cases:
660 - when entering a new scope
661 - on each statement
662 - on each expression that start a new line
663 - before the "except" clause
664 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000665*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667static void
668compiler_set_lineno(struct compiler *c, int off)
669{
670 basicblock *b;
671 if (c->u->u_lineno_set)
672 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000673 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000674 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000675 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
678static int
679opcode_stack_effect(int opcode, int oparg)
680{
681 switch (opcode) {
682 case POP_TOP:
683 return -1;
684 case ROT_TWO:
685 case ROT_THREE:
686 return 0;
687 case DUP_TOP:
688 return 1;
689 case ROT_FOUR:
690 return 0;
691
692 case UNARY_POSITIVE:
693 case UNARY_NEGATIVE:
694 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000695 case UNARY_INVERT:
696 return 0;
697
Nick Coghlan650f0d02007-04-15 12:05:43 +0000698 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000699 case LIST_APPEND:
700 return -2;
701
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000702 case BINARY_POWER:
703 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704 case BINARY_MODULO:
705 case BINARY_ADD:
706 case BINARY_SUBTRACT:
707 case BINARY_SUBSCR:
708 case BINARY_FLOOR_DIVIDE:
709 case BINARY_TRUE_DIVIDE:
710 return -1;
711 case INPLACE_FLOOR_DIVIDE:
712 case INPLACE_TRUE_DIVIDE:
713 return -1;
714
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000715 case INPLACE_ADD:
716 case INPLACE_SUBTRACT:
717 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000718 case INPLACE_MODULO:
719 return -1;
720 case STORE_SUBSCR:
721 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000722 case STORE_MAP:
723 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724 case DELETE_SUBSCR:
725 return -2;
726
727 case BINARY_LSHIFT:
728 case BINARY_RSHIFT:
729 case BINARY_AND:
730 case BINARY_XOR:
731 case BINARY_OR:
732 return -1;
733 case INPLACE_POWER:
734 return -1;
735 case GET_ITER:
736 return 0;
737
738 case PRINT_EXPR:
739 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000740 case LOAD_BUILD_CLASS:
741 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742 case INPLACE_LSHIFT:
743 case INPLACE_RSHIFT:
744 case INPLACE_AND:
745 case INPLACE_XOR:
746 case INPLACE_OR:
747 return -1;
748 case BREAK_LOOP:
749 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000750 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000751 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000752 case STORE_LOCALS:
753 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754 case RETURN_VALUE:
755 return -1;
756 case IMPORT_STAR:
757 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758 case YIELD_VALUE:
759 return 0;
760
761 case POP_BLOCK:
762 return 0;
763 case END_FINALLY:
764 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765
766 case STORE_NAME:
767 return -1;
768 case DELETE_NAME:
769 return 0;
770 case UNPACK_SEQUENCE:
771 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000772 case UNPACK_EX:
773 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774 case FOR_ITER:
775 return 1;
776
777 case STORE_ATTR:
778 return -2;
779 case DELETE_ATTR:
780 return -1;
781 case STORE_GLOBAL:
782 return -1;
783 case DELETE_GLOBAL:
784 return 0;
785 case DUP_TOPX:
786 return oparg;
787 case LOAD_CONST:
788 return 1;
789 case LOAD_NAME:
790 return 1;
791 case BUILD_TUPLE:
792 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000793 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794 return 1-oparg;
795 case BUILD_MAP:
796 return 1;
797 case LOAD_ATTR:
798 return 0;
799 case COMPARE_OP:
800 return -1;
801 case IMPORT_NAME:
802 return 0;
803 case IMPORT_FROM:
804 return 1;
805
806 case JUMP_FORWARD:
807 case JUMP_IF_FALSE:
808 case JUMP_IF_TRUE:
809 case JUMP_ABSOLUTE:
810 return 0;
811
812 case LOAD_GLOBAL:
813 return 1;
814
815 case CONTINUE_LOOP:
816 return 0;
817 case SETUP_LOOP:
818 return 0;
819 case SETUP_EXCEPT:
820 case SETUP_FINALLY:
821 return 3; /* actually pushed by an exception */
822
823 case LOAD_FAST:
824 return 1;
825 case STORE_FAST:
826 return -1;
827 case DELETE_FAST:
828 return 0;
829
830 case RAISE_VARARGS:
831 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000832#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833 case CALL_FUNCTION:
834 return -NARGS(oparg);
835 case CALL_FUNCTION_VAR:
836 case CALL_FUNCTION_KW:
837 return -NARGS(oparg)-1;
838 case CALL_FUNCTION_VAR_KW:
839 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000840 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000841 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000842 case MAKE_CLOSURE:
843 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000844#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845 case BUILD_SLICE:
846 if (oparg == 3)
847 return -2;
848 else
849 return -1;
850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000851 case LOAD_CLOSURE:
852 return 1;
853 case LOAD_DEREF:
854 return 1;
855 case STORE_DEREF:
856 return -1;
857 default:
858 fprintf(stderr, "opcode = %d\n", opcode);
859 Py_FatalError("opcode_stack_effect()");
860
861 }
862 return 0; /* not reachable */
863}
864
865/* Add an opcode with no argument.
866 Returns 0 on failure, 1 on success.
867*/
868
869static int
870compiler_addop(struct compiler *c, int opcode)
871{
872 basicblock *b;
873 struct instr *i;
874 int off;
875 off = compiler_next_instr(c, c->u->u_curblock);
876 if (off < 0)
877 return 0;
878 b = c->u->u_curblock;
879 i = &b->b_instr[off];
880 i->i_opcode = opcode;
881 i->i_hasarg = 0;
882 if (opcode == RETURN_VALUE)
883 b->b_return = 1;
884 compiler_set_lineno(c, off);
885 return 1;
886}
887
888static int
889compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
890{
891 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000892 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000893 unsigned char *p, *q;
894 Py_complex z;
895 double d;
896 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000897
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000898 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000899 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
900 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000901 d = PyFloat_AS_DOUBLE(o);
902 p = (unsigned char*) &d;
903 /* all we need is to make the tuple different in either the 0.0
904 * or -0.0 case from all others, just to avoid the "coercion".
905 */
906 if (*p==0 && p[sizeof(double)-1]==0)
907 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
908 else
909 t = PyTuple_Pack(2, o, o->ob_type);
910 }
911 else if (PyComplex_Check(o)) {
912 /* complex case is even messier: we need to make complex(x,
913 0.) different from complex(x, -0.) and complex(0., y)
914 different from complex(-0., y), for any x and y. In
915 particular, all four complex zeros should be
916 distinguished.*/
917 z = PyComplex_AsCComplex(o);
918 p = (unsigned char*) &(z.real);
919 q = (unsigned char*) &(z.imag);
920 /* all that matters here is that on IEEE platforms
921 real_part_zero will be true if z.real == 0., and false if
922 z.real == -0. In fact, real_part_zero will also be true
923 for some other rarely occurring nonzero floats, but this
924 doesn't matter. Similar comments apply to
925 imag_part_zero. */
926 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
927 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
928 if (real_part_zero && imag_part_zero) {
929 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
930 }
931 else if (real_part_zero && !imag_part_zero) {
932 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
933 }
934 else if (!real_part_zero && imag_part_zero) {
935 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
936 }
937 else {
938 t = PyTuple_Pack(2, o, o->ob_type);
939 }
940 }
941 else {
942 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000943 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000944 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000945 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
947 v = PyDict_GetItem(dict, t);
948 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000949 if (PyErr_Occurred())
950 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000951 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000952 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953 if (!v) {
954 Py_DECREF(t);
955 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000956 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957 if (PyDict_SetItem(dict, t, v) < 0) {
958 Py_DECREF(t);
959 Py_DECREF(v);
960 return -1;
961 }
962 Py_DECREF(v);
963 }
964 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000965 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000966 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000967 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968}
969
970static int
971compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
972 PyObject *o)
973{
974 int arg = compiler_add_o(c, dict, o);
975 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000976 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977 return compiler_addop_i(c, opcode, arg);
978}
979
980static int
981compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983{
984 int arg;
985 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
986 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000987 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 arg = compiler_add_o(c, dict, mangled);
989 Py_DECREF(mangled);
990 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992 return compiler_addop_i(c, opcode, arg);
993}
994
995/* Add an opcode with an integer argument.
996 Returns 0 on failure, 1 on success.
997*/
998
999static int
1000compiler_addop_i(struct compiler *c, int opcode, int oparg)
1001{
1002 struct instr *i;
1003 int off;
1004 off = compiler_next_instr(c, c->u->u_curblock);
1005 if (off < 0)
1006 return 0;
1007 i = &c->u->u_curblock->b_instr[off];
1008 i->i_opcode = opcode;
1009 i->i_oparg = oparg;
1010 i->i_hasarg = 1;
1011 compiler_set_lineno(c, off);
1012 return 1;
1013}
1014
1015static int
1016compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1017{
1018 struct instr *i;
1019 int off;
1020
1021 assert(b != NULL);
1022 off = compiler_next_instr(c, c->u->u_curblock);
1023 if (off < 0)
1024 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025 i = &c->u->u_curblock->b_instr[off];
1026 i->i_opcode = opcode;
1027 i->i_target = b;
1028 i->i_hasarg = 1;
1029 if (absolute)
1030 i->i_jabs = 1;
1031 else
1032 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001033 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034 return 1;
1035}
1036
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001037/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1038 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001039 it as the current block. NEXT_BLOCK() also creates an implicit jump
1040 from the current block to the new block.
1041*/
1042
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043/* The returns inside these macros make it impossible to decref objects
1044 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045*/
1046
1047
1048#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001049 if (compiler_use_new_block((C)) == NULL) \
1050 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051}
1052
1053#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001054 if (compiler_next_block((C)) == NULL) \
1055 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056}
1057
1058#define ADDOP(C, OP) { \
1059 if (!compiler_addop((C), (OP))) \
1060 return 0; \
1061}
1062
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001063#define ADDOP_IN_SCOPE(C, OP) { \
1064 if (!compiler_addop((C), (OP))) { \
1065 compiler_exit_scope(c); \
1066 return 0; \
1067 } \
1068}
1069
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070#define ADDOP_O(C, OP, O, TYPE) { \
1071 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1072 return 0; \
1073}
1074
1075#define ADDOP_NAME(C, OP, O, TYPE) { \
1076 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1077 return 0; \
1078}
1079
1080#define ADDOP_I(C, OP, O) { \
1081 if (!compiler_addop_i((C), (OP), (O))) \
1082 return 0; \
1083}
1084
1085#define ADDOP_JABS(C, OP, O) { \
1086 if (!compiler_addop_j((C), (OP), (O), 1)) \
1087 return 0; \
1088}
1089
1090#define ADDOP_JREL(C, OP, O) { \
1091 if (!compiler_addop_j((C), (OP), (O), 0)) \
1092 return 0; \
1093}
1094
1095/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1096 the ASDL name to synthesize the name of the C type and the visit function.
1097*/
1098
1099#define VISIT(C, TYPE, V) {\
1100 if (!compiler_visit_ ## TYPE((C), (V))) \
1101 return 0; \
1102}
1103
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001104#define VISIT_IN_SCOPE(C, TYPE, V) {\
1105 if (!compiler_visit_ ## TYPE((C), (V))) { \
1106 compiler_exit_scope(c); \
1107 return 0; \
1108 } \
1109}
1110
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111#define VISIT_SLICE(C, V, CTX) {\
1112 if (!compiler_visit_slice((C), (V), (CTX))) \
1113 return 0; \
1114}
1115
1116#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001117 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001119 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001120 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121 if (!compiler_visit_ ## TYPE((C), elt)) \
1122 return 0; \
1123 } \
1124}
1125
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001126#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001127 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001128 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001129 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001131 if (!compiler_visit_ ## TYPE((C), elt)) { \
1132 compiler_exit_scope(c); \
1133 return 0; \
1134 } \
1135 } \
1136}
1137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138static int
1139compiler_isdocstring(stmt_ty s)
1140{
1141 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001142 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143 return s->v.Expr.value->kind == Str_kind;
1144}
1145
1146/* Compile a sequence of statements, checking for a docstring. */
1147
1148static int
1149compiler_body(struct compiler *c, asdl_seq *stmts)
1150{
1151 int i = 0;
1152 stmt_ty st;
1153
1154 if (!asdl_seq_LEN(stmts))
1155 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001156 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001157 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1158 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 i = 1;
1160 VISIT(c, expr, st->v.Expr.value);
1161 if (!compiler_nameop(c, __doc__, Store))
1162 return 0;
1163 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001164 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001165 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166 return 1;
1167}
1168
1169static PyCodeObject *
1170compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001171{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001172 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001173 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 static PyObject *module;
1175 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001176 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 if (!module)
1178 return NULL;
1179 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001180 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1181 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001182 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 switch (mod->kind) {
1184 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001185 if (!compiler_body(c, mod->v.Module.body)) {
1186 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001188 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 break;
1190 case Interactive_kind:
1191 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001192 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001193 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 break;
1195 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001196 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001197 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 break;
1199 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001200 PyErr_SetString(PyExc_SystemError,
1201 "suite should not be possible");
1202 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001203 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001204 PyErr_Format(PyExc_SystemError,
1205 "module kind %d should not be possible",
1206 mod->kind);
1207 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 co = assemble(c, addNone);
1210 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001211 return co;
1212}
1213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214/* The test for LOCAL must come before the test for FREE in order to
1215 handle classes where name is both local and free. The local var is
1216 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001217*/
1218
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219static int
1220get_ref_type(struct compiler *c, PyObject *name)
1221{
1222 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001223 if (scope == 0) {
1224 char buf[350];
1225 PyOS_snprintf(buf, sizeof(buf),
1226 "unknown scope for %.100s in %.100s(%s) in %s\n"
1227 "symbols: %s\nlocals: %s\nglobals: %s\n",
1228 PyString_AS_STRING(name),
1229 PyString_AS_STRING(c->u->u_name),
1230 PyObject_REPR(c->u->u_ste->ste_id),
1231 c->c_filename,
1232 PyObject_REPR(c->u->u_ste->ste_symbols),
1233 PyObject_REPR(c->u->u_varnames),
1234 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001236 Py_FatalError(buf);
1237 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001238
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001239 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001240}
1241
1242static int
1243compiler_lookup_arg(PyObject *dict, PyObject *name)
1244{
1245 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001246 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001248 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001250 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001252 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001253 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254}
1255
1256static int
1257compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1258{
1259 int i, free = PyCode_GetNumFree(co);
1260 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001261 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1262 ADDOP_I(c, MAKE_FUNCTION, args);
1263 return 1;
1264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 for (i = 0; i < free; ++i) {
1266 /* Bypass com_addop_varname because it will generate
1267 LOAD_DEREF but LOAD_CLOSURE is needed.
1268 */
1269 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1270 int arg, reftype;
1271
1272 /* Special case: If a class contains a method with a
1273 free variable that has the same name as a method,
1274 the name will be considered free *and* local in the
1275 class. It should be handled by the closure, as
1276 well as by the normal name loookup logic.
1277 */
1278 reftype = get_ref_type(c, name);
1279 if (reftype == CELL)
1280 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1281 else /* (reftype == FREE) */
1282 arg = compiler_lookup_arg(c->u->u_freevars, name);
1283 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001284 fprintf(stderr,
1285 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286 "freevars of %s: %s\n",
1287 PyObject_REPR(name),
1288 PyString_AS_STRING(c->u->u_name),
1289 reftype, arg,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001290 PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291 PyObject_REPR(co->co_freevars));
1292 Py_FatalError("compiler_make_closure()");
1293 }
1294 ADDOP_I(c, LOAD_CLOSURE, arg);
1295 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001296 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001298 ADDOP_I(c, MAKE_CLOSURE, args);
1299 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300}
1301
1302static int
1303compiler_decorators(struct compiler *c, asdl_seq* decos)
1304{
1305 int i;
1306
1307 if (!decos)
1308 return 1;
1309
1310 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001311 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 }
1313 return 1;
1314}
1315
1316static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001317compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1318 asdl_seq *kw_defaults)
1319{
1320 int i, default_count = 0;
1321 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001322 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001323 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1324 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001325 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001326 if (!compiler_visit_expr(c, default_)) {
1327 return -1;
1328 }
1329 default_count++;
1330 }
1331 }
1332 return default_count;
1333}
1334
1335static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001336compiler_visit_argannotation(struct compiler *c, identifier id,
1337 expr_ty annotation, PyObject *names)
1338{
1339 if (annotation) {
1340 VISIT(c, expr, annotation);
1341 if (PyList_Append(names, id))
1342 return -1;
1343 }
1344 return 0;
1345}
1346
1347static int
1348compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1349 PyObject *names)
1350{
1351 int i, error;
1352 for (i = 0; i < asdl_seq_LEN(args); i++) {
1353 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001354 error = compiler_visit_argannotation(
1355 c,
1356 arg->arg,
1357 arg->annotation,
1358 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001359 if (error)
1360 return error;
1361 }
1362 return 0;
1363}
1364
1365static int
1366compiler_visit_annotations(struct compiler *c, arguments_ty args,
1367 expr_ty returns)
1368{
Guido van Rossum0240b922007-02-26 21:23:50 +00001369 /* Push arg annotations and a list of the argument names. Return the #
1370 of items pushed. The expressions are evaluated out-of-order wrt the
1371 source code.
1372
1373 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1374 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001375 static identifier return_str;
1376 PyObject *names;
1377 int len;
1378 names = PyList_New(0);
1379 if (!names)
1380 return -1;
1381
1382 if (compiler_visit_argannotations(c, args->args, names))
1383 goto error;
1384 if (args->varargannotation &&
1385 compiler_visit_argannotation(c, args->vararg,
1386 args->varargannotation, names))
1387 goto error;
1388 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1389 goto error;
1390 if (args->kwargannotation &&
1391 compiler_visit_argannotation(c, args->kwarg,
1392 args->kwargannotation, names))
1393 goto error;
1394
1395 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001396 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001397 if (!return_str)
1398 goto error;
1399 }
1400 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1401 goto error;
1402 }
1403
1404 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001405 if (len > 65534) {
1406 /* len must fit in 16 bits, and len is incremented below */
1407 PyErr_SetString(PyExc_SyntaxError,
1408 "too many annotations");
1409 goto error;
1410 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001411 if (len) {
1412 /* convert names to a tuple and place on stack */
1413 PyObject *elt;
1414 int i;
1415 PyObject *s = PyTuple_New(len);
1416 if (!s)
1417 goto error;
1418 for (i = 0; i < len; i++) {
1419 elt = PyList_GET_ITEM(names, i);
1420 Py_INCREF(elt);
1421 PyTuple_SET_ITEM(s, i, elt);
1422 }
1423 ADDOP_O(c, LOAD_CONST, s, consts);
1424 Py_DECREF(s);
1425 len++; /* include the just-pushed tuple */
1426 }
1427 Py_DECREF(names);
1428 return len;
1429
1430error:
1431 Py_DECREF(names);
1432 return -1;
1433}
1434
1435static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436compiler_function(struct compiler *c, stmt_ty s)
1437{
1438 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001439 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001441 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001442 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001443 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001444 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001445 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446
1447 assert(s->kind == FunctionDef_kind);
1448
1449 if (!compiler_decorators(c, decos))
1450 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001451 if (args->kwonlyargs) {
1452 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1453 args->kw_defaults);
1454 if (res < 0)
1455 return 0;
1456 kw_default_count = res;
1457 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458 if (args->defaults)
1459 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001460 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001461 if (num_annotations < 0)
1462 return 0;
1463 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001464
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1466 s->lineno))
1467 return 0;
1468
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001469 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001470 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001471 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001472 first_const = st->v.Expr.value->v.Str.s;
1473 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001474 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001475 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001476 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001479 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001483 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1484 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485 }
1486 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001487 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 if (co == NULL)
1489 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490
Guido van Rossum4f72a782006-10-27 23:31:49 +00001491 arglength = asdl_seq_LEN(args->defaults);
1492 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001493 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001494 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001495 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
Neal Norwitzc1505362006-12-28 06:47:50 +00001497 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1499 ADDOP_I(c, CALL_FUNCTION, 1);
1500 }
1501
1502 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1503}
1504
1505static int
1506compiler_class(struct compiler *c, stmt_ty s)
1507{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001508 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001510 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001511 PySTEntryObject *ste;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001512 int err, i;
1513 asdl_seq* decos = s->v.ClassDef.decorator_list;
1514
1515 if (!compiler_decorators(c, decos))
1516 return 0;
1517
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001518 /* initialize statics */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001519 if (locals == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001520 locals = PyUnicode_InternFromString("__locals__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001521 if (locals == NULL)
1522 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001523 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001525 /* ultimately generate code for:
1526 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1527 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001528 <func> is a function/closure created from the class body;
1529 it has a single argument (__locals__) where the dict
1530 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001531 <name> is the class name
1532 <bases> is the positional arguments and *varargs argument
1533 <keywords> is the keyword arguments and **kwds argument
1534 This borrows from compiler_call.
1535 */
1536
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001537 /* 0. Create a fake argument named __locals__ */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001538 ste = PySymtable_Lookup(c->c_st, s);
1539 if (ste == NULL)
1540 return 0;
1541 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001542 err = PyList_Append(ste->ste_varnames, locals);
1543 Py_DECREF(ste);
1544 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001545 return 0;
1546
1547 /* 1. compile the class body into a code object */
1548 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1549 return 0;
1550 /* this block represents what we do in the new scope */
1551 {
1552 /* use the class name for name mangling */
1553 Py_INCREF(s->v.ClassDef.name);
1554 c->u->u_private = s->v.ClassDef.name;
1555 /* force it to have one mandatory argument */
1556 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001557 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001558 ADDOP_I(c, LOAD_FAST, 0);
1559 /* ... and store it into f_locals */
1560 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001561 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001562 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001563 if (!str || !compiler_nameop(c, str, Load)) {
1564 Py_XDECREF(str);
1565 compiler_exit_scope(c);
1566 return 0;
1567 }
1568 Py_DECREF(str);
1569 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001570 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001571 if (!str || !compiler_nameop(c, str, Store)) {
1572 Py_XDECREF(str);
1573 compiler_exit_scope(c);
1574 return 0;
1575 }
1576 Py_DECREF(str);
1577 /* compile the body proper */
1578 if (!compiler_body(c, s->v.ClassDef.body)) {
1579 compiler_exit_scope(c);
1580 return 0;
1581 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001582 /* return the (empty) __class__ cell */
1583 str = PyUnicode_InternFromString("__class__");
1584 if (str == NULL) {
1585 compiler_exit_scope(c);
1586 return 0;
1587 }
1588 i = compiler_lookup_arg(c->u->u_cellvars, str);
1589 Py_DECREF(str);
1590 if (i == -1) {
1591 /* This happens when nobody references the cell */
1592 PyErr_Clear();
1593 /* Return None */
1594 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1595 }
1596 else {
1597 /* Return the cell where to store __class__ */
1598 ADDOP_I(c, LOAD_CLOSURE, i);
1599 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001600 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1601 /* create the code object */
1602 co = assemble(c, 1);
1603 }
1604 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001605 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001606 if (co == NULL)
1607 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001608
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001609 /* 2. load the 'build_class' function */
1610 ADDOP(c, LOAD_BUILD_CLASS);
1611
1612 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001613 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001614 Py_DECREF(co);
1615
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001616 /* 4. load class name */
1617 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1618
1619 /* 5. generate the rest of the code for the call */
1620 if (!compiler_call_helper(c, 2,
1621 s->v.ClassDef.bases,
1622 s->v.ClassDef.keywords,
1623 s->v.ClassDef.starargs,
1624 s->v.ClassDef.kwargs))
1625 return 0;
1626
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001627 /* 6. apply decorators */
1628 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1629 ADDOP_I(c, CALL_FUNCTION, 1);
1630 }
1631
1632 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1634 return 0;
1635 return 1;
1636}
1637
1638static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001639compiler_ifexp(struct compiler *c, expr_ty e)
1640{
1641 basicblock *end, *next;
1642
1643 assert(e->kind == IfExp_kind);
1644 end = compiler_new_block(c);
1645 if (end == NULL)
1646 return 0;
1647 next = compiler_new_block(c);
1648 if (next == NULL)
1649 return 0;
1650 VISIT(c, expr, e->v.IfExp.test);
1651 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1652 ADDOP(c, POP_TOP);
1653 VISIT(c, expr, e->v.IfExp.body);
1654 ADDOP_JREL(c, JUMP_FORWARD, end);
1655 compiler_use_next_block(c, next);
1656 ADDOP(c, POP_TOP);
1657 VISIT(c, expr, e->v.IfExp.orelse);
1658 compiler_use_next_block(c, end);
1659 return 1;
1660}
1661
1662static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663compiler_lambda(struct compiler *c, expr_ty e)
1664{
1665 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001666 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001667 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668 arguments_ty args = e->v.Lambda.args;
1669 assert(e->kind == Lambda_kind);
1670
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001671 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001672 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001673 if (!name)
1674 return 0;
1675 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676
Guido van Rossum4f72a782006-10-27 23:31:49 +00001677 if (args->kwonlyargs) {
1678 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1679 args->kw_defaults);
1680 if (res < 0) return 0;
1681 kw_default_count = res;
1682 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683 if (args->defaults)
1684 VISIT_SEQ(c, expr, args->defaults);
1685 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1686 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001687
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001689 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001690 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1691 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001693 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694 if (co == NULL)
1695 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696
Guido van Rossum4f72a782006-10-27 23:31:49 +00001697 arglength = asdl_seq_LEN(args->defaults);
1698 arglength |= kw_default_count << 8;
1699 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001700 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701
1702 return 1;
1703}
1704
1705static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706compiler_if(struct compiler *c, stmt_ty s)
1707{
1708 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001709 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710 assert(s->kind == If_kind);
1711 end = compiler_new_block(c);
1712 if (end == NULL)
1713 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001714 next = compiler_new_block(c);
1715 if (next == NULL)
1716 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001717
1718 constant = expr_constant(s->v.If.test);
1719 /* constant = 0: "if 0"
1720 * constant = 1: "if 1", "if 2", ...
1721 * constant = -1: rest */
1722 if (constant == 0) {
1723 if (s->v.If.orelse)
1724 VISIT_SEQ(c, stmt, s->v.If.orelse);
1725 } else if (constant == 1) {
1726 VISIT_SEQ(c, stmt, s->v.If.body);
1727 } else {
1728 VISIT(c, expr, s->v.If.test);
1729 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1730 ADDOP(c, POP_TOP);
1731 VISIT_SEQ(c, stmt, s->v.If.body);
1732 ADDOP_JREL(c, JUMP_FORWARD, end);
1733 compiler_use_next_block(c, next);
1734 ADDOP(c, POP_TOP);
1735 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001736 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001737 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001738 compiler_use_next_block(c, end);
1739 return 1;
1740}
1741
1742static int
1743compiler_for(struct compiler *c, stmt_ty s)
1744{
1745 basicblock *start, *cleanup, *end;
1746
1747 start = compiler_new_block(c);
1748 cleanup = compiler_new_block(c);
1749 end = compiler_new_block(c);
1750 if (start == NULL || end == NULL || cleanup == NULL)
1751 return 0;
1752 ADDOP_JREL(c, SETUP_LOOP, end);
1753 if (!compiler_push_fblock(c, LOOP, start))
1754 return 0;
1755 VISIT(c, expr, s->v.For.iter);
1756 ADDOP(c, GET_ITER);
1757 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001758 /* for expressions must be traced on each iteration,
1759 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001760 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001761 ADDOP_JREL(c, FOR_ITER, cleanup);
1762 VISIT(c, expr, s->v.For.target);
1763 VISIT_SEQ(c, stmt, s->v.For.body);
1764 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1765 compiler_use_next_block(c, cleanup);
1766 ADDOP(c, POP_BLOCK);
1767 compiler_pop_fblock(c, LOOP, start);
1768 VISIT_SEQ(c, stmt, s->v.For.orelse);
1769 compiler_use_next_block(c, end);
1770 return 1;
1771}
1772
1773static int
1774compiler_while(struct compiler *c, stmt_ty s)
1775{
1776 basicblock *loop, *orelse, *end, *anchor = NULL;
1777 int constant = expr_constant(s->v.While.test);
1778
Christian Heimes969fe572008-01-25 11:23:10 +00001779 if (constant == 0) {
1780 if (s->v.While.orelse)
1781 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001783 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 loop = compiler_new_block(c);
1785 end = compiler_new_block(c);
1786 if (constant == -1) {
1787 anchor = compiler_new_block(c);
1788 if (anchor == NULL)
1789 return 0;
1790 }
1791 if (loop == NULL || end == NULL)
1792 return 0;
1793 if (s->v.While.orelse) {
1794 orelse = compiler_new_block(c);
1795 if (orelse == NULL)
1796 return 0;
1797 }
1798 else
1799 orelse = NULL;
1800
1801 ADDOP_JREL(c, SETUP_LOOP, end);
1802 compiler_use_next_block(c, loop);
1803 if (!compiler_push_fblock(c, LOOP, loop))
1804 return 0;
1805 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001806 /* while expressions must be traced on each iteration,
1807 so we need to set an extra line number. */
1808 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 VISIT(c, expr, s->v.While.test);
1810 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1811 ADDOP(c, POP_TOP);
1812 }
1813 VISIT_SEQ(c, stmt, s->v.While.body);
1814 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1815
1816 /* XXX should the two POP instructions be in a separate block
1817 if there is no else clause ?
1818 */
1819
1820 if (constant == -1) {
1821 compiler_use_next_block(c, anchor);
1822 ADDOP(c, POP_TOP);
1823 ADDOP(c, POP_BLOCK);
1824 }
1825 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001826 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 VISIT_SEQ(c, stmt, s->v.While.orelse);
1828 compiler_use_next_block(c, end);
1829
1830 return 1;
1831}
1832
1833static int
1834compiler_continue(struct compiler *c)
1835{
1836 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001837 static const char IN_FINALLY_ERROR_MSG[] =
1838 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001839 int i;
1840
1841 if (!c->u->u_nfblocks)
1842 return compiler_error(c, LOOP_ERROR_MSG);
1843 i = c->u->u_nfblocks - 1;
1844 switch (c->u->u_fblock[i].fb_type) {
1845 case LOOP:
1846 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1847 break;
1848 case EXCEPT:
1849 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001850 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1851 /* Prevent continue anywhere under a finally
1852 even if hidden in a sub-try or except. */
1853 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1854 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1855 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856 if (i == -1)
1857 return compiler_error(c, LOOP_ERROR_MSG);
1858 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1859 break;
1860 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001861 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 }
1863
1864 return 1;
1865}
1866
1867/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1868
1869 SETUP_FINALLY L
1870 <code for body>
1871 POP_BLOCK
1872 LOAD_CONST <None>
1873 L: <code for finalbody>
1874 END_FINALLY
1875
1876 The special instructions use the block stack. Each block
1877 stack entry contains the instruction that created it (here
1878 SETUP_FINALLY), the level of the value stack at the time the
1879 block stack entry was created, and a label (here L).
1880
1881 SETUP_FINALLY:
1882 Pushes the current value stack level and the label
1883 onto the block stack.
1884 POP_BLOCK:
1885 Pops en entry from the block stack, and pops the value
1886 stack until its level is the same as indicated on the
1887 block stack. (The label is ignored.)
1888 END_FINALLY:
1889 Pops a variable number of entries from the *value* stack
1890 and re-raises the exception they specify. The number of
1891 entries popped depends on the (pseudo) exception type.
1892
1893 The block stack is unwound when an exception is raised:
1894 when a SETUP_FINALLY entry is found, the exception is pushed
1895 onto the value stack (and the exception condition is cleared),
1896 and the interpreter jumps to the label gotten from the block
1897 stack.
1898*/
1899
1900static int
1901compiler_try_finally(struct compiler *c, stmt_ty s)
1902{
1903 basicblock *body, *end;
1904 body = compiler_new_block(c);
1905 end = compiler_new_block(c);
1906 if (body == NULL || end == NULL)
1907 return 0;
1908
1909 ADDOP_JREL(c, SETUP_FINALLY, end);
1910 compiler_use_next_block(c, body);
1911 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1912 return 0;
1913 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1914 ADDOP(c, POP_BLOCK);
1915 compiler_pop_fblock(c, FINALLY_TRY, body);
1916
1917 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1918 compiler_use_next_block(c, end);
1919 if (!compiler_push_fblock(c, FINALLY_END, end))
1920 return 0;
1921 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1922 ADDOP(c, END_FINALLY);
1923 compiler_pop_fblock(c, FINALLY_END, end);
1924
1925 return 1;
1926}
1927
1928/*
1929 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1930 (The contents of the value stack is shown in [], with the top
1931 at the right; 'tb' is trace-back info, 'val' the exception's
1932 associated value, and 'exc' the exception.)
1933
1934 Value stack Label Instruction Argument
1935 [] SETUP_EXCEPT L1
1936 [] <code for S>
1937 [] POP_BLOCK
1938 [] JUMP_FORWARD L0
1939
1940 [tb, val, exc] L1: DUP )
1941 [tb, val, exc, exc] <evaluate E1> )
1942 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1943 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1944 [tb, val, exc, 1] POP )
1945 [tb, val, exc] POP
1946 [tb, val] <assign to V1> (or POP if no V1)
1947 [tb] POP
1948 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001949 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950
1951 [tb, val, exc, 0] L2: POP
1952 [tb, val, exc] DUP
1953 .............................etc.......................
1954
1955 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001956 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
1958 [] L0: <next statement>
1959
1960 Of course, parts are not generated if Vi or Ei is not present.
1961*/
1962static int
1963compiler_try_except(struct compiler *c, stmt_ty s)
1964{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001965 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966 int i, n;
1967
1968 body = compiler_new_block(c);
1969 except = compiler_new_block(c);
1970 orelse = compiler_new_block(c);
1971 end = compiler_new_block(c);
1972 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1973 return 0;
1974 ADDOP_JREL(c, SETUP_EXCEPT, except);
1975 compiler_use_next_block(c, body);
1976 if (!compiler_push_fblock(c, EXCEPT, body))
1977 return 0;
1978 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1979 ADDOP(c, POP_BLOCK);
1980 compiler_pop_fblock(c, EXCEPT, body);
1981 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1982 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1983 compiler_use_next_block(c, except);
1984 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001985 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986 s->v.TryExcept.handlers, i);
1987 if (!handler->type && i < n-1)
1988 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001989 c->u->u_lineno_set = 0;
1990 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 except = compiler_new_block(c);
1992 if (except == NULL)
1993 return 0;
1994 if (handler->type) {
1995 ADDOP(c, DUP_TOP);
1996 VISIT(c, expr, handler->type);
1997 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1998 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1999 ADDOP(c, POP_TOP);
2000 }
2001 ADDOP(c, POP_TOP);
2002 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00002003 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002004
2005 cleanup_end = compiler_new_block(c);
2006 cleanup_body = compiler_new_block(c);
2007 if(!(cleanup_end || cleanup_body))
2008 return 0;
2009
Guido van Rossum16be03e2007-01-10 18:51:35 +00002010 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002011 ADDOP(c, POP_TOP);
2012
2013 /*
2014 try:
2015 # body
2016 except type as name:
2017 try:
2018 # body
2019 finally:
2020 name = None
2021 del name
2022 */
2023
2024 /* second try: */
2025 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2026 compiler_use_next_block(c, cleanup_body);
2027 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2028 return 0;
2029
2030 /* second # body */
2031 VISIT_SEQ(c, stmt, handler->body);
2032 ADDOP(c, POP_BLOCK);
2033 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2034
2035 /* finally: */
2036 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2037 compiler_use_next_block(c, cleanup_end);
2038 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2039 return 0;
2040
2041 /* name = None */
2042 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00002043 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002044
Guido van Rossum16be03e2007-01-10 18:51:35 +00002045 /* del name */
2046 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002047
2048 ADDOP(c, END_FINALLY);
2049 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 }
2051 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00002052 ADDOP(c, POP_TOP);
2053 ADDOP(c, POP_TOP);
2054 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056 ADDOP_JREL(c, JUMP_FORWARD, end);
2057 compiler_use_next_block(c, except);
2058 if (handler->type)
2059 ADDOP(c, POP_TOP);
2060 }
2061 ADDOP(c, END_FINALLY);
2062 compiler_use_next_block(c, orelse);
2063 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2064 compiler_use_next_block(c, end);
2065 return 1;
2066}
2067
2068static int
2069compiler_import_as(struct compiler *c, identifier name, identifier asname)
2070{
2071 /* The IMPORT_NAME opcode was already generated. This function
2072 merely needs to bind the result to a name.
2073
2074 If there is a dot in name, we need to split it and emit a
2075 LOAD_ATTR for each name.
2076 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002077 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2078 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 if (dot) {
2080 /* Consume the base module name to get the first attribute */
2081 src = dot + 1;
2082 while (dot) {
2083 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002084 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002085 dot = Py_UNICODE_strchr(src, '.');
2086 attr = PyUnicode_FromUnicode(src,
2087 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002088 if (!attr)
2089 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002091 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 src = dot + 1;
2093 }
2094 }
2095 return compiler_nameop(c, asname, Store);
2096}
2097
2098static int
2099compiler_import(struct compiler *c, stmt_ty s)
2100{
2101 /* The Import node stores a module name like a.b.c as a single
2102 string. This is convenient for all cases except
2103 import a.b.c as d
2104 where we need to parse that string to extract the individual
2105 module names.
2106 XXX Perhaps change the representation to make this case simpler?
2107 */
2108 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002109
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002111 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002113 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114
Christian Heimes217cfd12007-12-02 14:31:20 +00002115 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002116 if (level == NULL)
2117 return 0;
2118
2119 ADDOP_O(c, LOAD_CONST, level, consts);
2120 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2122 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2123
2124 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002125 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002126 if (!r)
2127 return r;
2128 }
2129 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002131 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2132 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002134 tmp = PyUnicode_FromUnicode(base,
2135 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 r = compiler_nameop(c, tmp, Store);
2137 if (dot) {
2138 Py_DECREF(tmp);
2139 }
2140 if (!r)
2141 return r;
2142 }
2143 }
2144 return 1;
2145}
2146
2147static int
2148compiler_from_import(struct compiler *c, stmt_ty s)
2149{
2150 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151
2152 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002153 PyObject *level;
2154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 if (!names)
2156 return 0;
2157
Christian Heimes217cfd12007-12-02 14:31:20 +00002158 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002159 if (!level) {
2160 Py_DECREF(names);
2161 return 0;
2162 }
2163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164 /* build up the names */
2165 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002166 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 Py_INCREF(alias->name);
2168 PyTuple_SET_ITEM(names, i, alias->name);
2169 }
2170
2171 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002172 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2173 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002174 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175 Py_DECREF(names);
2176 return compiler_error(c,
2177 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002178 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179
2180 }
2181 }
2182
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002183 ADDOP_O(c, LOAD_CONST, level, consts);
2184 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002186 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002187 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2188 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002189 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 identifier store_name;
2191
Martin v. Löwis5b222132007-06-10 09:51:05 +00002192 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 assert(n == 1);
2194 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 }
2197
2198 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2199 store_name = alias->name;
2200 if (alias->asname)
2201 store_name = alias->asname;
2202
2203 if (!compiler_nameop(c, store_name, Store)) {
2204 Py_DECREF(names);
2205 return 0;
2206 }
2207 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002208 /* remove imported module */
2209 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210 return 1;
2211}
2212
2213static int
2214compiler_assert(struct compiler *c, stmt_ty s)
2215{
2216 static PyObject *assertion_error = NULL;
2217 basicblock *end;
2218
2219 if (Py_OptimizeFlag)
2220 return 1;
2221 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002222 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 if (assertion_error == NULL)
2224 return 0;
2225 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002226 if (s->v.Assert.test->kind == Tuple_kind &&
2227 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2228 const char* msg =
2229 "assertion is always true, perhaps remove parentheses?";
2230 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2231 c->u->u_lineno, NULL, NULL) == -1)
2232 return 0;
2233 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 VISIT(c, expr, s->v.Assert.test);
2235 end = compiler_new_block(c);
2236 if (end == NULL)
2237 return 0;
2238 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2239 ADDOP(c, POP_TOP);
2240 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2241 if (s->v.Assert.msg) {
2242 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002243 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 }
Collin Winter828f04a2007-08-31 00:04:24 +00002245 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002246 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247 ADDOP(c, POP_TOP);
2248 return 1;
2249}
2250
2251static int
2252compiler_visit_stmt(struct compiler *c, stmt_ty s)
2253{
2254 int i, n;
2255
Thomas Wouters89f507f2006-12-13 04:49:30 +00002256 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002258 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002261 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002263 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002265 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 if (c->u->u_ste->ste_type != FunctionBlock)
2267 return compiler_error(c, "'return' outside function");
2268 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269 VISIT(c, expr, s->v.Return.value);
2270 }
2271 else
2272 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2273 ADDOP(c, RETURN_VALUE);
2274 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002275 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 VISIT_SEQ(c, expr, s->v.Delete.targets)
2277 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002278 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 n = asdl_seq_LEN(s->v.Assign.targets);
2280 VISIT(c, expr, s->v.Assign.value);
2281 for (i = 0; i < n; i++) {
2282 if (i < n - 1)
2283 ADDOP(c, DUP_TOP);
2284 VISIT(c, expr,
2285 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2286 }
2287 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002288 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002290 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002292 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002294 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002295 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002296 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002298 if (s->v.Raise.exc) {
2299 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002301 if (s->v.Raise.cause) {
2302 VISIT(c, expr, s->v.Raise.cause);
2303 n++;
2304 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 }
2306 ADDOP_I(c, RAISE_VARARGS, n);
2307 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002308 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002310 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002312 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002314 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002316 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002318 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002319 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002321 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002323 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324 ADDOP(c, PRINT_EXPR);
2325 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002326 else if (s->v.Expr.value->kind != Str_kind &&
2327 s->v.Expr.value->kind != Num_kind) {
2328 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 ADDOP(c, POP_TOP);
2330 }
2331 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002332 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002334 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002335 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336 return compiler_error(c, "'break' outside loop");
2337 ADDOP(c, BREAK_LOOP);
2338 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002339 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002341 case With_kind:
2342 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343 }
2344 return 1;
2345}
2346
2347static int
2348unaryop(unaryop_ty op)
2349{
2350 switch (op) {
2351 case Invert:
2352 return UNARY_INVERT;
2353 case Not:
2354 return UNARY_NOT;
2355 case UAdd:
2356 return UNARY_POSITIVE;
2357 case USub:
2358 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002359 default:
2360 PyErr_Format(PyExc_SystemError,
2361 "unary op %d should not be possible", op);
2362 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364}
2365
2366static int
2367binop(struct compiler *c, operator_ty op)
2368{
2369 switch (op) {
2370 case Add:
2371 return BINARY_ADD;
2372 case Sub:
2373 return BINARY_SUBTRACT;
2374 case Mult:
2375 return BINARY_MULTIPLY;
2376 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002377 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002378 case Mod:
2379 return BINARY_MODULO;
2380 case Pow:
2381 return BINARY_POWER;
2382 case LShift:
2383 return BINARY_LSHIFT;
2384 case RShift:
2385 return BINARY_RSHIFT;
2386 case BitOr:
2387 return BINARY_OR;
2388 case BitXor:
2389 return BINARY_XOR;
2390 case BitAnd:
2391 return BINARY_AND;
2392 case FloorDiv:
2393 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002394 default:
2395 PyErr_Format(PyExc_SystemError,
2396 "binary op %d should not be possible", op);
2397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002398 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399}
2400
2401static int
2402cmpop(cmpop_ty op)
2403{
2404 switch (op) {
2405 case Eq:
2406 return PyCmp_EQ;
2407 case NotEq:
2408 return PyCmp_NE;
2409 case Lt:
2410 return PyCmp_LT;
2411 case LtE:
2412 return PyCmp_LE;
2413 case Gt:
2414 return PyCmp_GT;
2415 case GtE:
2416 return PyCmp_GE;
2417 case Is:
2418 return PyCmp_IS;
2419 case IsNot:
2420 return PyCmp_IS_NOT;
2421 case In:
2422 return PyCmp_IN;
2423 case NotIn:
2424 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002425 default:
2426 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428}
2429
2430static int
2431inplace_binop(struct compiler *c, operator_ty op)
2432{
2433 switch (op) {
2434 case Add:
2435 return INPLACE_ADD;
2436 case Sub:
2437 return INPLACE_SUBTRACT;
2438 case Mult:
2439 return INPLACE_MULTIPLY;
2440 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002441 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442 case Mod:
2443 return INPLACE_MODULO;
2444 case Pow:
2445 return INPLACE_POWER;
2446 case LShift:
2447 return INPLACE_LSHIFT;
2448 case RShift:
2449 return INPLACE_RSHIFT;
2450 case BitOr:
2451 return INPLACE_OR;
2452 case BitXor:
2453 return INPLACE_XOR;
2454 case BitAnd:
2455 return INPLACE_AND;
2456 case FloorDiv:
2457 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002458 default:
2459 PyErr_Format(PyExc_SystemError,
2460 "inplace binary op %d should not be possible", op);
2461 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463}
2464
2465static int
2466compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2467{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002468 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2470
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002471 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002472 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473 /* XXX AugStore isn't used anywhere! */
2474
2475 /* First check for assignment to __debug__. Param? */
2476 if ((ctx == Store || ctx == AugStore || ctx == Del)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002477 && !PyUnicode_CompareWithASCIIString(name, "__debug__")) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 return compiler_error(c, "can not assign to __debug__");
2479 }
2480
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002481 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002482 if (!mangled)
2483 return 0;
2484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 op = 0;
2486 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002487 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 switch (scope) {
2489 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002490 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 optype = OP_DEREF;
2492 break;
2493 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002494 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495 optype = OP_DEREF;
2496 break;
2497 case LOCAL:
2498 if (c->u->u_ste->ste_type == FunctionBlock)
2499 optype = OP_FAST;
2500 break;
2501 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002502 if (c->u->u_ste->ste_type == FunctionBlock &&
2503 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504 optype = OP_GLOBAL;
2505 break;
2506 case GLOBAL_EXPLICIT:
2507 optype = OP_GLOBAL;
2508 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002509 default:
2510 /* scope can be 0 */
2511 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002512 }
2513
2514 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002515 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516
2517 switch (optype) {
2518 case OP_DEREF:
2519 switch (ctx) {
2520 case Load: op = LOAD_DEREF; break;
2521 case Store: op = STORE_DEREF; break;
2522 case AugLoad:
2523 case AugStore:
2524 break;
2525 case Del:
2526 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002527 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002528 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002529 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002530 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002533 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002534 PyErr_SetString(PyExc_SystemError,
2535 "param invalid for deref variable");
2536 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 }
2538 break;
2539 case OP_FAST:
2540 switch (ctx) {
2541 case Load: op = LOAD_FAST; break;
2542 case Store: op = STORE_FAST; break;
2543 case Del: op = DELETE_FAST; break;
2544 case AugLoad:
2545 case AugStore:
2546 break;
2547 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002548 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002549 PyErr_SetString(PyExc_SystemError,
2550 "param invalid for local variable");
2551 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002553 ADDOP_O(c, op, mangled, varnames);
2554 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002555 return 1;
2556 case OP_GLOBAL:
2557 switch (ctx) {
2558 case Load: op = LOAD_GLOBAL; break;
2559 case Store: op = STORE_GLOBAL; break;
2560 case Del: op = DELETE_GLOBAL; break;
2561 case AugLoad:
2562 case AugStore:
2563 break;
2564 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002565 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002566 PyErr_SetString(PyExc_SystemError,
2567 "param invalid for global variable");
2568 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569 }
2570 break;
2571 case OP_NAME:
2572 switch (ctx) {
2573 case Load: op = LOAD_NAME; break;
2574 case Store: op = STORE_NAME; break;
2575 case Del: op = DELETE_NAME; break;
2576 case AugLoad:
2577 case AugStore:
2578 break;
2579 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002580 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002581 PyErr_SetString(PyExc_SystemError,
2582 "param invalid for name variable");
2583 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584 }
2585 break;
2586 }
2587
2588 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002589 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002590 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002591 if (arg < 0)
2592 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002593 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594}
2595
2596static int
2597compiler_boolop(struct compiler *c, expr_ty e)
2598{
2599 basicblock *end;
2600 int jumpi, i, n;
2601 asdl_seq *s;
2602
2603 assert(e->kind == BoolOp_kind);
2604 if (e->v.BoolOp.op == And)
2605 jumpi = JUMP_IF_FALSE;
2606 else
2607 jumpi = JUMP_IF_TRUE;
2608 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002609 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610 return 0;
2611 s = e->v.BoolOp.values;
2612 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002613 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002615 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 ADDOP_JREL(c, jumpi, end);
2617 ADDOP(c, POP_TOP)
2618 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002619 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620 compiler_use_next_block(c, end);
2621 return 1;
2622}
2623
2624static int
2625compiler_list(struct compiler *c, expr_ty e)
2626{
2627 int n = asdl_seq_LEN(e->v.List.elts);
2628 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002629 int i, seen_star = 0;
2630 for (i = 0; i < n; i++) {
2631 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2632 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002633 if ((i >= (1 << 8)) ||
2634 (n-i-1 >= (INT_MAX >> 8)))
2635 return compiler_error(c,
2636 "too many expressions in "
2637 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002638 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2639 seen_star = 1;
2640 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2641 } else if (elt->kind == Starred_kind) {
2642 return compiler_error(c,
2643 "two starred expressions in assignment");
2644 }
2645 }
2646 if (!seen_star) {
2647 ADDOP_I(c, UNPACK_SEQUENCE, n);
2648 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 }
2650 VISIT_SEQ(c, expr, e->v.List.elts);
2651 if (e->v.List.ctx == Load) {
2652 ADDOP_I(c, BUILD_LIST, n);
2653 }
2654 return 1;
2655}
2656
2657static int
2658compiler_tuple(struct compiler *c, expr_ty e)
2659{
2660 int n = asdl_seq_LEN(e->v.Tuple.elts);
2661 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002662 int i, seen_star = 0;
2663 for (i = 0; i < n; i++) {
2664 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2665 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002666 if ((i >= (1 << 8)) ||
2667 (n-i-1 >= (INT_MAX >> 8)))
2668 return compiler_error(c,
2669 "too many expressions in "
2670 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002671 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2672 seen_star = 1;
2673 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2674 } else if (elt->kind == Starred_kind) {
2675 return compiler_error(c,
2676 "two starred expressions in assignment");
2677 }
2678 }
2679 if (!seen_star) {
2680 ADDOP_I(c, UNPACK_SEQUENCE, n);
2681 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 }
2683 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2684 if (e->v.Tuple.ctx == Load) {
2685 ADDOP_I(c, BUILD_TUPLE, n);
2686 }
2687 return 1;
2688}
2689
2690static int
2691compiler_compare(struct compiler *c, expr_ty e)
2692{
2693 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002694 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695
2696 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2697 VISIT(c, expr, e->v.Compare.left);
2698 n = asdl_seq_LEN(e->v.Compare.ops);
2699 assert(n > 0);
2700 if (n > 1) {
2701 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002702 if (cleanup == NULL)
2703 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002704 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002705 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 }
2707 for (i = 1; i < n; i++) {
2708 ADDOP(c, DUP_TOP);
2709 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002711 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002712 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2714 NEXT_BLOCK(c);
2715 ADDOP(c, POP_TOP);
2716 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002717 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002718 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002720 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002722 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 if (n > 1) {
2724 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002725 if (end == NULL)
2726 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727 ADDOP_JREL(c, JUMP_FORWARD, end);
2728 compiler_use_next_block(c, cleanup);
2729 ADDOP(c, ROT_TWO);
2730 ADDOP(c, POP_TOP);
2731 compiler_use_next_block(c, end);
2732 }
2733 return 1;
2734}
2735
2736static int
2737compiler_call(struct compiler *c, expr_ty e)
2738{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002740 return compiler_call_helper(c, 0,
2741 e->v.Call.args,
2742 e->v.Call.keywords,
2743 e->v.Call.starargs,
2744 e->v.Call.kwargs);
2745}
2746
2747/* shared code between compiler_call and compiler_class */
2748static int
2749compiler_call_helper(struct compiler *c,
2750 int n, /* Args already pushed */
2751 asdl_seq *args,
2752 asdl_seq *keywords,
2753 expr_ty starargs,
2754 expr_ty kwargs)
2755{
2756 int code = 0;
2757
2758 n += asdl_seq_LEN(args);
2759 VISIT_SEQ(c, expr, args);
2760 if (keywords) {
2761 VISIT_SEQ(c, keyword, keywords);
2762 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002764 if (starargs) {
2765 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766 code |= 1;
2767 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002768 if (kwargs) {
2769 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770 code |= 2;
2771 }
2772 switch (code) {
2773 case 0:
2774 ADDOP_I(c, CALL_FUNCTION, n);
2775 break;
2776 case 1:
2777 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2778 break;
2779 case 2:
2780 ADDOP_I(c, CALL_FUNCTION_KW, n);
2781 break;
2782 case 3:
2783 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2784 break;
2785 }
2786 return 1;
2787}
2788
Nick Coghlan650f0d02007-04-15 12:05:43 +00002789
2790/* List and set comprehensions and generator expressions work by creating a
2791 nested function to perform the actual iteration. This means that the
2792 iteration variables don't leak into the current scope.
2793 The defined function is called immediately following its definition, with the
2794 result of that call being the result of the expression.
2795 The LC/SC version returns the populated container, while the GE version is
2796 flagged in symtable.c as a generator, so it returns the generator object
2797 when the function is called.
2798 This code *knows* that the loop cannot contain break, continue, or return,
2799 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2800
2801 Possible cleanups:
2802 - iterate over the generator sequence instead of using recursion
2803*/
2804
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002806compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
2807 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002808 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809{
2810 /* generate code for the iterator, then each of the ifs,
2811 and then write to the element */
2812
Nick Coghlan650f0d02007-04-15 12:05:43 +00002813 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002816
2817 start = compiler_new_block(c);
2818 skip = compiler_new_block(c);
2819 if_cleanup = compiler_new_block(c);
2820 anchor = compiler_new_block(c);
2821
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002822 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002823 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825
Nick Coghlan650f0d02007-04-15 12:05:43 +00002826 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828 if (gen_index == 0) {
2829 /* Receive outermost iter as an implicit argument */
2830 c->u->u_argcount = 1;
2831 ADDOP_I(c, LOAD_FAST, 0);
2832 }
2833 else {
2834 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002835 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836 ADDOP(c, GET_ITER);
2837 }
2838 compiler_use_next_block(c, start);
2839 ADDOP_JREL(c, FOR_ITER, anchor);
2840 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002841 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002843 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002844 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002846 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847 VISIT(c, expr, e);
2848 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2849 NEXT_BLOCK(c);
2850 ADDOP(c, POP_TOP);
2851 }
2852
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002853 if (++gen_index < asdl_seq_LEN(generators))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002854 if (!compiler_comprehension_generator(c, tmpname,
2855 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002856 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002857 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858
Nick Coghlan650f0d02007-04-15 12:05:43 +00002859 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002860 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002861 /* comprehension specific code */
2862 switch (type) {
2863 case COMP_GENEXP:
2864 VISIT(c, expr, elt);
2865 ADDOP(c, YIELD_VALUE);
2866 ADDOP(c, POP_TOP);
2867 break;
2868 case COMP_LISTCOMP:
2869 if (!compiler_nameop(c, tmpname, Load))
2870 return 0;
2871 VISIT(c, expr, elt);
2872 ADDOP(c, LIST_APPEND);
2873 break;
2874 case COMP_SETCOMP:
2875 if (!compiler_nameop(c, tmpname, Load))
2876 return 0;
2877 VISIT(c, expr, elt);
2878 ADDOP(c, SET_ADD);
2879 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002880 case COMP_DICTCOMP:
2881 if (!compiler_nameop(c, tmpname, Load))
2882 return 0;
2883 /* With 'd[k] = v', v is evaluated before k, so we do
2884 the same. STORE_SUBSCR requires (item, map, key),
2885 so we still end up ROTing once. */
2886 VISIT(c, expr, val);
2887 ADDOP(c, ROT_TWO);
2888 VISIT(c, expr, elt);
2889 ADDOP(c, STORE_SUBSCR);
2890 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002891 default:
2892 return 0;
2893 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894
2895 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 for (i = 0; i < n; i++) {
2898 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002899 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002900 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002901
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002902 ADDOP(c, POP_TOP);
2903 }
2904 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2905 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906
2907 return 1;
2908}
2909
2910static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002911compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002912 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002913{
2914 PyCodeObject *co = NULL;
2915 identifier tmp = NULL;
2916 expr_ty outermost_iter;
2917
2918 outermost_iter = ((comprehension_ty)
2919 asdl_seq_GET(generators, 0))->iter;
2920
2921 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2922 goto error;
2923
2924 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002925 int op;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002926 tmp = compiler_new_tmpname(c);
2927 if (!tmp)
2928 goto error_in_scope;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002929 switch (type) {
2930 case COMP_LISTCOMP:
2931 op = BUILD_LIST;
2932 break;
2933 case COMP_SETCOMP:
2934 op = BUILD_SET;
2935 break;
2936 case COMP_DICTCOMP:
2937 op = BUILD_MAP;
2938 break;
2939 default:
2940 PyErr_Format(PyExc_SystemError,
2941 "unknown comprehension type %d", type);
2942 goto error_in_scope;
2943 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002944
Guido van Rossum992d4a32007-07-11 13:09:30 +00002945 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002946 ADDOP(c, DUP_TOP);
2947 if (!compiler_nameop(c, tmp, Store))
2948 goto error_in_scope;
2949 }
2950
Guido van Rossum992d4a32007-07-11 13:09:30 +00002951 if (!compiler_comprehension_generator(c, tmp, generators, 0, elt,
2952 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002953 goto error_in_scope;
2954
2955 if (type != COMP_GENEXP) {
2956 ADDOP(c, RETURN_VALUE);
2957 }
2958
2959 co = assemble(c, 1);
2960 compiler_exit_scope(c);
2961 if (co == NULL)
2962 goto error;
2963
2964 if (!compiler_make_closure(c, co, 0))
2965 goto error;
2966 Py_DECREF(co);
2967 Py_XDECREF(tmp);
2968
2969 VISIT(c, expr, outermost_iter);
2970 ADDOP(c, GET_ITER);
2971 ADDOP_I(c, CALL_FUNCTION, 1);
2972 return 1;
2973error_in_scope:
2974 compiler_exit_scope(c);
2975error:
2976 Py_XDECREF(co);
2977 Py_XDECREF(tmp);
2978 return 0;
2979}
2980
2981static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982compiler_genexp(struct compiler *c, expr_ty e)
2983{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002984 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002985 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002986 name = PyUnicode_FromString("<genexp>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002987 if (!name)
2988 return 0;
2989 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002990 assert(e->kind == GeneratorExp_kind);
2991 return compiler_comprehension(c, e, COMP_GENEXP, name,
2992 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002993 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994}
2995
2996static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002997compiler_listcomp(struct compiler *c, expr_ty e)
2998{
2999 static identifier name;
3000 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003001 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00003002 if (!name)
3003 return 0;
3004 }
3005 assert(e->kind == ListComp_kind);
3006 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3007 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003008 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003009}
3010
3011static int
3012compiler_setcomp(struct compiler *c, expr_ty e)
3013{
3014 static identifier name;
3015 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003016 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00003017 if (!name)
3018 return 0;
3019 }
3020 assert(e->kind == SetComp_kind);
3021 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3022 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003023 e->v.SetComp.elt, NULL);
3024}
3025
3026
3027static int
3028compiler_dictcomp(struct compiler *c, expr_ty e)
3029{
3030 static identifier name;
3031 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003032 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003033 if (!name)
3034 return 0;
3035 }
3036 assert(e->kind == DictComp_kind);
3037 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3038 e->v.DictComp.generators,
3039 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003040}
3041
3042
3043static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044compiler_visit_keyword(struct compiler *c, keyword_ty k)
3045{
3046 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3047 VISIT(c, expr, k->value);
3048 return 1;
3049}
3050
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003051/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052 whether they are true or false.
3053
3054 Return values: 1 for true, 0 for false, -1 for non-constant.
3055 */
3056
3057static int
3058expr_constant(expr_ty e)
3059{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003060 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003062 case Ellipsis_kind:
3063 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064 case Num_kind:
3065 return PyObject_IsTrue(e->v.Num.n);
3066 case Str_kind:
3067 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003068 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003069 /* optimize away names that can't be reassigned */
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003070 id = PyString_AS_STRING(
3071 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003072 if (strcmp(id, "True") == 0) return 1;
3073 if (strcmp(id, "False") == 0) return 0;
3074 if (strcmp(id, "None") == 0) return 0;
3075 if (strcmp(id, "__debug__") == 0)
3076 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003077 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078 default:
3079 return -1;
3080 }
3081}
3082
Guido van Rossumc2e20742006-02-27 22:32:47 +00003083/*
3084 Implements the with statement from PEP 343.
3085
3086 The semantics outlined in that PEP are as follows:
3087
3088 with EXPR as VAR:
3089 BLOCK
3090
3091 It is implemented roughly as:
3092
Thomas Wouters477c8d52006-05-27 19:21:47 +00003093 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003094 exit = context.__exit__ # not calling it
3095 value = context.__enter__()
3096 try:
3097 VAR = value # if VAR present in the syntax
3098 BLOCK
3099 finally:
3100 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003101 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003102 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003103 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003104 exit(*exc)
3105 */
3106static int
3107compiler_with(struct compiler *c, stmt_ty s)
3108{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003109 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003110 basicblock *block, *finally;
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003111 identifier tmpvalue = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003112
3113 assert(s->kind == With_kind);
3114
Guido van Rossumc2e20742006-02-27 22:32:47 +00003115 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003116 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003117 if (!enter_attr)
3118 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003119 }
3120 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003121 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003122 if (!exit_attr)
3123 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003124 }
3125
3126 block = compiler_new_block(c);
3127 finally = compiler_new_block(c);
3128 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003129 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003130
Guido van Rossumc2e20742006-02-27 22:32:47 +00003131 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003132 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003133 We need to do this rather than preserving it on the stack
3134 because SETUP_FINALLY remembers the stack level.
3135 We need to do the assignment *inside* the try/finally
3136 so that context.__exit__() is called when the assignment
3137 fails. But we need to call context.__enter__() *before*
3138 the try/finally so that if it fails we won't call
3139 context.__exit__().
3140 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003141 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003142 if (tmpvalue == NULL)
3143 return 0;
3144 PyArena_AddPyObject(c->c_arena, tmpvalue);
3145 }
3146
Thomas Wouters477c8d52006-05-27 19:21:47 +00003147 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003148 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003149
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003150 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003151 ADDOP(c, DUP_TOP);
3152 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003153 ADDOP(c, ROT_TWO);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003154
3155 /* Call context.__enter__() */
3156 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3157 ADDOP_I(c, CALL_FUNCTION, 0);
3158
3159 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 /* Store it in tmpvalue */
3161 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003162 return 0;
3163 }
3164 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003165 /* Discard result from context.__enter__() */
3166 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003167 }
3168
3169 /* Start the try block */
3170 ADDOP_JREL(c, SETUP_FINALLY, finally);
3171
3172 compiler_use_next_block(c, block);
3173 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003174 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003175 }
3176
3177 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003178 /* Bind saved result of context.__enter__() to VAR */
3179 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003180 !compiler_nameop(c, tmpvalue, Del))
3181 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003182 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003183 }
3184
3185 /* BLOCK code */
3186 VISIT_SEQ(c, stmt, s->v.With.body);
3187
3188 /* End of try block; start the finally block */
3189 ADDOP(c, POP_BLOCK);
3190 compiler_pop_fblock(c, FINALLY_TRY, block);
3191
3192 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3193 compiler_use_next_block(c, finally);
3194 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003196
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003197 /* Finally block starts; context.__exit__ is on the stack under
3198 the exception or return information. Just issue our magic
3199 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003200 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003201
3202 /* Finally block ends. */
3203 ADDOP(c, END_FINALLY);
3204 compiler_pop_fblock(c, FINALLY_END, finally);
3205 return 1;
3206}
3207
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208static int
3209compiler_visit_expr(struct compiler *c, expr_ty e)
3210{
3211 int i, n;
3212
Thomas Wouters89f507f2006-12-13 04:49:30 +00003213 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003214 set a new line number for the next instruction.
3215 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216 if (e->lineno > c->u->u_lineno) {
3217 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003218 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 }
3220 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003223 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224 VISIT(c, expr, e->v.BinOp.left);
3225 VISIT(c, expr, e->v.BinOp.right);
3226 ADDOP(c, binop(c, e->v.BinOp.op));
3227 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003228 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229 VISIT(c, expr, e->v.UnaryOp.operand);
3230 ADDOP(c, unaryop(e->v.UnaryOp.op));
3231 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003232 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003233 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003234 case IfExp_kind:
3235 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003236 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003238 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003240 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003241 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003242 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003243 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003244 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245 }
3246 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003247 case Set_kind:
3248 n = asdl_seq_LEN(e->v.Set.elts);
3249 VISIT_SEQ(c, expr, e->v.Set.elts);
3250 ADDOP_I(c, BUILD_SET, n);
3251 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003252 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003254 case ListComp_kind:
3255 return compiler_listcomp(c, e);
3256 case SetComp_kind:
3257 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003258 case DictComp_kind:
3259 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 case Yield_kind:
3261 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003262 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 if (e->v.Yield.value) {
3264 VISIT(c, expr, e->v.Yield.value);
3265 }
3266 else {
3267 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3268 }
3269 ADDOP(c, YIELD_VALUE);
3270 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003271 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003273 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003275 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3277 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003278 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3280 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003281 case Bytes_kind:
3282 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003283 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003284 case Ellipsis_kind:
3285 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3286 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003288 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289 if (e->v.Attribute.ctx != AugStore)
3290 VISIT(c, expr, e->v.Attribute.value);
3291 switch (e->v.Attribute.ctx) {
3292 case AugLoad:
3293 ADDOP(c, DUP_TOP);
3294 /* Fall through to load */
3295 case Load:
3296 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3297 break;
3298 case AugStore:
3299 ADDOP(c, ROT_TWO);
3300 /* Fall through to save */
3301 case Store:
3302 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3303 break;
3304 case Del:
3305 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3306 break;
3307 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003308 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003309 PyErr_SetString(PyExc_SystemError,
3310 "param invalid in attribute expression");
3311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003312 }
3313 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003314 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315 switch (e->v.Subscript.ctx) {
3316 case AugLoad:
3317 VISIT(c, expr, e->v.Subscript.value);
3318 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3319 break;
3320 case Load:
3321 VISIT(c, expr, e->v.Subscript.value);
3322 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3323 break;
3324 case AugStore:
3325 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3326 break;
3327 case Store:
3328 VISIT(c, expr, e->v.Subscript.value);
3329 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3330 break;
3331 case Del:
3332 VISIT(c, expr, e->v.Subscript.value);
3333 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3334 break;
3335 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003336 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003337 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003338 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003339 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340 }
3341 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003342 case Starred_kind:
3343 switch (e->v.Starred.ctx) {
3344 case Store:
3345 /* In all legitimate cases, the Starred node was already replaced
3346 * by compiler_list/compiler_tuple. XXX: is that okay? */
3347 return compiler_error(c,
3348 "starred assignment target must be in a list or tuple");
3349 default:
3350 return compiler_error(c,
3351 "can use starred expression only as assignment target");
3352 }
3353 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003354 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3356 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003357 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003359 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360 return compiler_tuple(c, e);
3361 }
3362 return 1;
3363}
3364
3365static int
3366compiler_augassign(struct compiler *c, stmt_ty s)
3367{
3368 expr_ty e = s->v.AugAssign.target;
3369 expr_ty auge;
3370
3371 assert(s->kind == AugAssign_kind);
3372
3373 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003374 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003376 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003377 if (auge == NULL)
3378 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003379 VISIT(c, expr, auge);
3380 VISIT(c, expr, s->v.AugAssign.value);
3381 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3382 auge->v.Attribute.ctx = AugStore;
3383 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 break;
3385 case Subscript_kind:
3386 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003387 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003388 if (auge == NULL)
3389 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003390 VISIT(c, expr, auge);
3391 VISIT(c, expr, s->v.AugAssign.value);
3392 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003393 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003395 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003397 if (!compiler_nameop(c, e->v.Name.id, Load))
3398 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399 VISIT(c, expr, s->v.AugAssign.value);
3400 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3401 return compiler_nameop(c, e->v.Name.id, Store);
3402 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003403 PyErr_Format(PyExc_SystemError,
3404 "invalid node type (%d) for augmented assignment",
3405 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003406 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407 }
3408 return 1;
3409}
3410
3411static int
3412compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3413{
3414 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003415 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3416 PyErr_SetString(PyExc_SystemError,
3417 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003418 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003419 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420 f = &c->u->u_fblock[c->u->u_nfblocks++];
3421 f->fb_type = t;
3422 f->fb_block = b;
3423 return 1;
3424}
3425
3426static void
3427compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3428{
3429 struct compiler_unit *u = c->u;
3430 assert(u->u_nfblocks > 0);
3431 u->u_nfblocks--;
3432 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3433 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3434}
3435
Thomas Wouters89f507f2006-12-13 04:49:30 +00003436static int
3437compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003438 int i;
3439 struct compiler_unit *u = c->u;
3440 for (i = 0; i < u->u_nfblocks; ++i) {
3441 if (u->u_fblock[i].fb_type == LOOP)
3442 return 1;
3443 }
3444 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003445}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446/* Raises a SyntaxError and returns 0.
3447 If something goes wrong, a different exception may be raised.
3448*/
3449
3450static int
3451compiler_error(struct compiler *c, const char *errstr)
3452{
3453 PyObject *loc;
3454 PyObject *u = NULL, *v = NULL;
3455
3456 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3457 if (!loc) {
3458 Py_INCREF(Py_None);
3459 loc = Py_None;
3460 }
3461 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3462 Py_None, loc);
3463 if (!u)
3464 goto exit;
3465 v = Py_BuildValue("(zO)", errstr, u);
3466 if (!v)
3467 goto exit;
3468 PyErr_SetObject(PyExc_SyntaxError, v);
3469 exit:
3470 Py_DECREF(loc);
3471 Py_XDECREF(u);
3472 Py_XDECREF(v);
3473 return 0;
3474}
3475
3476static int
3477compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003478 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003480 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003482 /* XXX this code is duplicated */
3483 switch (ctx) {
3484 case AugLoad: /* fall through to Load */
3485 case Load: op = BINARY_SUBSCR; break;
3486 case AugStore:/* fall through to Store */
3487 case Store: op = STORE_SUBSCR; break;
3488 case Del: op = DELETE_SUBSCR; break;
3489 case Param:
3490 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003491 "invalid %s kind %d in subscript\n",
3492 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 return 0;
3494 }
3495 if (ctx == AugLoad) {
3496 ADDOP_I(c, DUP_TOPX, 2);
3497 }
3498 else if (ctx == AugStore) {
3499 ADDOP(c, ROT_THREE);
3500 }
3501 ADDOP(c, op);
3502 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503}
3504
3505static int
3506compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3507{
3508 int n = 2;
3509 assert(s->kind == Slice_kind);
3510
3511 /* only handles the cases where BUILD_SLICE is emitted */
3512 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003513 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 }
3515 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003516 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003518
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003520 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521 }
3522 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003523 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 }
3525
3526 if (s->v.Slice.step) {
3527 n++;
3528 VISIT(c, expr, s->v.Slice.step);
3529 }
3530 ADDOP_I(c, BUILD_SLICE, n);
3531 return 1;
3532}
3533
3534static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3536 expr_context_ty ctx)
3537{
3538 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 case Slice_kind:
3540 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 case Index_kind:
3542 VISIT(c, expr, s->v.Index.value);
3543 break;
3544 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003545 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003546 PyErr_SetString(PyExc_SystemError,
3547 "extended slice invalid in nested slice");
3548 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 }
3550 return 1;
3551}
3552
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553static int
3554compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3555{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003556 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003558 case Index_kind:
3559 kindname = "index";
3560 if (ctx != AugStore) {
3561 VISIT(c, expr, s->v.Index.value);
3562 }
3563 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003565 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003566 if (ctx != AugStore) {
3567 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 return 0;
3569 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003570 break;
3571 case ExtSlice_kind:
3572 kindname = "extended slice";
3573 if (ctx != AugStore) {
3574 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3575 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003576 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003577 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003578 if (!compiler_visit_nested_slice(c, sub, ctx))
3579 return 0;
3580 }
3581 ADDOP_I(c, BUILD_TUPLE, n);
3582 }
3583 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003584 default:
3585 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003586 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003587 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003589 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590}
3591
Thomas Wouters89f507f2006-12-13 04:49:30 +00003592/* End of the compiler section, beginning of the assembler section */
3593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594/* do depth-first search of basic block graph, starting with block.
3595 post records the block indices in post-order.
3596
3597 XXX must handle implicit jumps from one block to next
3598*/
3599
Thomas Wouters89f507f2006-12-13 04:49:30 +00003600struct assembler {
3601 PyObject *a_bytecode; /* string containing bytecode */
3602 int a_offset; /* offset into bytecode */
3603 int a_nblocks; /* number of reachable blocks */
3604 basicblock **a_postorder; /* list of blocks in dfs postorder */
3605 PyObject *a_lnotab; /* string containing lnotab */
3606 int a_lnotab_off; /* offset into lnotab */
3607 int a_lineno; /* last lineno of emitted instruction */
3608 int a_lineno_off; /* bytecode offset of last lineno */
3609};
3610
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611static void
3612dfs(struct compiler *c, basicblock *b, struct assembler *a)
3613{
3614 int i;
3615 struct instr *instr = NULL;
3616
3617 if (b->b_seen)
3618 return;
3619 b->b_seen = 1;
3620 if (b->b_next != NULL)
3621 dfs(c, b->b_next, a);
3622 for (i = 0; i < b->b_iused; i++) {
3623 instr = &b->b_instr[i];
3624 if (instr->i_jrel || instr->i_jabs)
3625 dfs(c, instr->i_target, a);
3626 }
3627 a->a_postorder[a->a_nblocks++] = b;
3628}
3629
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003630static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3632{
3633 int i;
3634 struct instr *instr;
3635 if (b->b_seen || b->b_startdepth >= depth)
3636 return maxdepth;
3637 b->b_seen = 1;
3638 b->b_startdepth = depth;
3639 for (i = 0; i < b->b_iused; i++) {
3640 instr = &b->b_instr[i];
3641 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3642 if (depth > maxdepth)
3643 maxdepth = depth;
3644 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3645 if (instr->i_jrel || instr->i_jabs) {
3646 maxdepth = stackdepth_walk(c, instr->i_target,
3647 depth, maxdepth);
3648 if (instr->i_opcode == JUMP_ABSOLUTE ||
3649 instr->i_opcode == JUMP_FORWARD) {
3650 goto out; /* remaining code is dead */
3651 }
3652 }
3653 }
3654 if (b->b_next)
3655 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3656out:
3657 b->b_seen = 0;
3658 return maxdepth;
3659}
3660
3661/* Find the flow path that needs the largest stack. We assume that
3662 * cycles in the flow graph have no net effect on the stack depth.
3663 */
3664static int
3665stackdepth(struct compiler *c)
3666{
3667 basicblock *b, *entryblock;
3668 entryblock = NULL;
3669 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3670 b->b_seen = 0;
3671 b->b_startdepth = INT_MIN;
3672 entryblock = b;
3673 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003674 if (!entryblock)
3675 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676 return stackdepth_walk(c, entryblock, 0, 0);
3677}
3678
3679static int
3680assemble_init(struct assembler *a, int nblocks, int firstlineno)
3681{
3682 memset(a, 0, sizeof(struct assembler));
3683 a->a_lineno = firstlineno;
3684 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3685 if (!a->a_bytecode)
3686 return 0;
3687 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3688 if (!a->a_lnotab)
3689 return 0;
3690 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003691 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003692 if (!a->a_postorder) {
3693 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003696 return 1;
3697}
3698
3699static void
3700assemble_free(struct assembler *a)
3701{
3702 Py_XDECREF(a->a_bytecode);
3703 Py_XDECREF(a->a_lnotab);
3704 if (a->a_postorder)
3705 PyObject_Free(a->a_postorder);
3706}
3707
3708/* Return the size of a basic block in bytes. */
3709
3710static int
3711instrsize(struct instr *instr)
3712{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003713 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003714 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003715 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003716 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3717 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718}
3719
3720static int
3721blocksize(basicblock *b)
3722{
3723 int i;
3724 int size = 0;
3725
3726 for (i = 0; i < b->b_iused; i++)
3727 size += instrsize(&b->b_instr[i]);
3728 return size;
3729}
3730
3731/* All about a_lnotab.
3732
3733c_lnotab is an array of unsigned bytes disguised as a Python string.
3734It is used to map bytecode offsets to source code line #s (when needed
3735for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003736
Tim Peters2a7f3842001-06-09 09:26:21 +00003737The array is conceptually a list of
3738 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003739pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003740
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003741 byte code offset source code line number
3742 0 1
3743 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003744 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003745 350 307
3746 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003747
3748The first trick is that these numbers aren't stored, only the increments
3749from one row to the next (this doesn't really work, but it's a start):
3750
3751 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3752
3753The second trick is that an unsigned byte can't hold negative values, or
3754values larger than 255, so (a) there's a deep assumption that byte code
3755offsets and their corresponding line #s both increase monotonically, and (b)
3756if at least one column jumps by more than 255 from one row to the next, more
3757than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003758from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003759part. A user of c_lnotab desiring to find the source line number
3760corresponding to a bytecode address A should do something like this
3761
3762 lineno = addr = 0
3763 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003764 addr += addr_incr
3765 if addr > A:
3766 return lineno
3767 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003768
3769In order for this to work, when the addr field increments by more than 255,
3770the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003771increment is < 256. So, in the example above, assemble_lnotab (it used
3772to be called com_set_lineno) should not (as was actually done until 2.2)
3773expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003774 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003775*/
3776
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003777static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003779{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 int d_bytecode, d_lineno;
3781 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003782 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783
3784 d_bytecode = a->a_offset - a->a_lineno_off;
3785 d_lineno = i->i_lineno - a->a_lineno;
3786
3787 assert(d_bytecode >= 0);
3788 assert(d_lineno >= 0);
3789
Christian Heimes2202f872008-02-06 14:31:34 +00003790 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003791 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003792
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003794 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795 nbytes = a->a_lnotab_off + 2 * ncodes;
3796 len = PyString_GET_SIZE(a->a_lnotab);
3797 if (nbytes >= len) {
3798 if (len * 2 < nbytes)
3799 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003800 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801 len *= 2;
3802 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3803 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003804 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003805 lnotab = (unsigned char *)
3806 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003807 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808 *lnotab++ = 255;
3809 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003810 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003811 d_bytecode -= ncodes * 255;
3812 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003813 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 assert(d_bytecode <= 255);
3815 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003816 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817 nbytes = a->a_lnotab_off + 2 * ncodes;
3818 len = PyString_GET_SIZE(a->a_lnotab);
3819 if (nbytes >= len) {
3820 if (len * 2 < nbytes)
3821 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003822 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003823 len *= 2;
3824 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3825 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003826 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003827 lnotab = (unsigned char *)
3828 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003830 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003831 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003832 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003834 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836 d_lineno -= ncodes * 255;
3837 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003838 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003839
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840 len = PyString_GET_SIZE(a->a_lnotab);
3841 if (a->a_lnotab_off + 2 >= len) {
3842 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003843 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003844 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003845 lnotab = (unsigned char *)
3846 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 a->a_lnotab_off += 2;
3849 if (d_bytecode) {
3850 *lnotab++ = d_bytecode;
3851 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003852 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003853 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 *lnotab++ = 0;
3855 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 a->a_lineno = i->i_lineno;
3858 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003859 return 1;
3860}
3861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862/* assemble_emit()
3863 Extend the bytecode with a new instruction.
3864 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003865*/
3866
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003867static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003869{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003870 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003871 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872 char *code;
3873
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003874 size = instrsize(i);
3875 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003877 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003878 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003879 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003880 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 if (a->a_offset + size >= len) {
3882 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003883 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003884 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3886 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003887 if (size == 6) {
3888 assert(i->i_hasarg);
3889 *code++ = (char)EXTENDED_ARG;
3890 *code++ = ext & 0xff;
3891 *code++ = ext >> 8;
3892 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003893 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003895 if (i->i_hasarg) {
3896 assert(size == 3 || size == 6);
3897 *code++ = arg & 0xff;
3898 *code++ = arg >> 8;
3899 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003901}
3902
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003903static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003905{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003907 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003908 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003909
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 /* Compute the size of each block and fixup jump args.
3911 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003912start:
3913 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003915 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916 bsize = blocksize(b);
3917 b->b_offset = totsize;
3918 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003919 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003920 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3922 bsize = b->b_offset;
3923 for (i = 0; i < b->b_iused; i++) {
3924 struct instr *instr = &b->b_instr[i];
3925 /* Relative jumps are computed relative to
3926 the instruction pointer after fetching
3927 the jump instruction.
3928 */
3929 bsize += instrsize(instr);
3930 if (instr->i_jabs)
3931 instr->i_oparg = instr->i_target->b_offset;
3932 else if (instr->i_jrel) {
3933 int delta = instr->i_target->b_offset - bsize;
3934 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003935 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003936 else
3937 continue;
3938 if (instr->i_oparg > 0xffff)
3939 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003940 }
3941 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003942
3943 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003944 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003945 with a better solution.
3946
3947 In the meantime, should the goto be dropped in favor
3948 of a loop?
3949
3950 The issue is that in the first loop blocksize() is called
3951 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003952 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003953 i_oparg is calculated in the second loop above.
3954
3955 So we loop until we stop seeing new EXTENDED_ARGs.
3956 The only EXTENDED_ARGs that could be popping up are
3957 ones in jump instructions. So this should converge
3958 fairly quickly.
3959 */
3960 if (last_extended_arg_count != extended_arg_count) {
3961 last_extended_arg_count = extended_arg_count;
3962 goto start;
3963 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003964}
3965
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003966static PyObject *
3967dict_keys_inorder(PyObject *dict, int offset)
3968{
3969 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003970 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003971
3972 tuple = PyTuple_New(size);
3973 if (tuple == NULL)
3974 return NULL;
3975 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003976 i = PyLong_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003977 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003978 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003979 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003980 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003981 PyTuple_SET_ITEM(tuple, i - offset, k);
3982 }
3983 return tuple;
3984}
3985
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003986static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003987compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003988{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003989 PySTEntryObject *ste = c->u->u_ste;
3990 int flags = 0, n;
3991 if (ste->ste_type != ModuleBlock)
3992 flags |= CO_NEWLOCALS;
3993 if (ste->ste_type == FunctionBlock) {
3994 if (!ste->ste_unoptimized)
3995 flags |= CO_OPTIMIZED;
3996 if (ste->ste_nested)
3997 flags |= CO_NESTED;
3998 if (ste->ste_generator)
3999 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004000 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004001 if (ste->ste_varargs)
4002 flags |= CO_VARARGS;
4003 if (ste->ste_varkeywords)
4004 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004005 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004006 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004007
4008 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004009 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004010
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004011 n = PyDict_Size(c->u->u_freevars);
4012 if (n < 0)
4013 return -1;
4014 if (n == 0) {
4015 n = PyDict_Size(c->u->u_cellvars);
4016 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004017 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004018 if (n == 0) {
4019 flags |= CO_NOFREE;
4020 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004021 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004022
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004023 return flags;
4024}
4025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004026static PyCodeObject *
4027makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004028{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004029 PyObject *tmp;
4030 PyCodeObject *co = NULL;
4031 PyObject *consts = NULL;
4032 PyObject *names = NULL;
4033 PyObject *varnames = NULL;
4034 PyObject *filename = NULL;
4035 PyObject *name = NULL;
4036 PyObject *freevars = NULL;
4037 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004038 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004039 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004040
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004041 tmp = dict_keys_inorder(c->u->u_consts, 0);
4042 if (!tmp)
4043 goto error;
4044 consts = PySequence_List(tmp); /* optimize_code requires a list */
4045 Py_DECREF(tmp);
4046
4047 names = dict_keys_inorder(c->u->u_names, 0);
4048 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4049 if (!consts || !names || !varnames)
4050 goto error;
4051
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004052 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4053 if (!cellvars)
4054 goto error;
4055 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4056 if (!freevars)
4057 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004058 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004059 if (!filename)
4060 goto error;
4061
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004062 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063 flags = compute_code_flags(c);
4064 if (flags < 0)
4065 goto error;
4066
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004067 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068 if (!bytecode)
4069 goto error;
4070
4071 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4072 if (!tmp)
4073 goto error;
4074 Py_DECREF(consts);
4075 consts = tmp;
4076
Guido van Rossum4f72a782006-10-27 23:31:49 +00004077 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4078 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004079 bytecode, consts, names, varnames,
4080 freevars, cellvars,
4081 filename, c->u->u_name,
4082 c->u->u_firstlineno,
4083 a->a_lnotab);
4084 error:
4085 Py_XDECREF(consts);
4086 Py_XDECREF(names);
4087 Py_XDECREF(varnames);
4088 Py_XDECREF(filename);
4089 Py_XDECREF(name);
4090 Py_XDECREF(freevars);
4091 Py_XDECREF(cellvars);
4092 Py_XDECREF(bytecode);
4093 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004094}
4095
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004096
4097/* For debugging purposes only */
4098#if 0
4099static void
4100dump_instr(const struct instr *i)
4101{
4102 const char *jrel = i->i_jrel ? "jrel " : "";
4103 const char *jabs = i->i_jabs ? "jabs " : "";
4104 char arg[128];
4105
4106 *arg = '\0';
4107 if (i->i_hasarg)
4108 sprintf(arg, "arg: %d ", i->i_oparg);
4109
4110 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4111 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4112}
4113
4114static void
4115dump_basicblock(const basicblock *b)
4116{
4117 const char *seen = b->b_seen ? "seen " : "";
4118 const char *b_return = b->b_return ? "return " : "";
4119 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4120 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4121 if (b->b_instr) {
4122 int i;
4123 for (i = 0; i < b->b_iused; i++) {
4124 fprintf(stderr, " [%02d] ", i);
4125 dump_instr(b->b_instr + i);
4126 }
4127 }
4128}
4129#endif
4130
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131static PyCodeObject *
4132assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004133{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134 basicblock *b, *entryblock;
4135 struct assembler a;
4136 int i, j, nblocks;
4137 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004138
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139 /* Make sure every block that falls off the end returns None.
4140 XXX NEXT_BLOCK() isn't quite right, because if the last
4141 block ends with a jump or return b_next shouldn't set.
4142 */
4143 if (!c->u->u_curblock->b_return) {
4144 NEXT_BLOCK(c);
4145 if (addNone)
4146 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4147 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004148 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150 nblocks = 0;
4151 entryblock = NULL;
4152 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4153 nblocks++;
4154 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004155 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004156
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004157 /* Set firstlineno if it wasn't explicitly set. */
4158 if (!c->u->u_firstlineno) {
4159 if (entryblock && entryblock->b_instr)
4160 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4161 else
4162 c->u->u_firstlineno = 1;
4163 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004164 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4165 goto error;
4166 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004167
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004168 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004169 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004170
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004171 /* Emit code in reverse postorder from dfs. */
4172 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004173 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004174 for (j = 0; j < b->b_iused; j++)
4175 if (!assemble_emit(&a, &b->b_instr[j]))
4176 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004177 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4180 goto error;
4181 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4182 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004183
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 co = makecode(c, &a);
4185 error:
4186 assemble_free(&a);
4187 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004188}