blob: 6017b2ca436db72f9d31a5edeb64f556480dbf34 [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;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000763 case POP_EXCEPT:
764 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765 case END_FINALLY:
766 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767
768 case STORE_NAME:
769 return -1;
770 case DELETE_NAME:
771 return 0;
772 case UNPACK_SEQUENCE:
773 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000774 case UNPACK_EX:
775 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776 case FOR_ITER:
777 return 1;
778
779 case STORE_ATTR:
780 return -2;
781 case DELETE_ATTR:
782 return -1;
783 case STORE_GLOBAL:
784 return -1;
785 case DELETE_GLOBAL:
786 return 0;
787 case DUP_TOPX:
788 return oparg;
789 case LOAD_CONST:
790 return 1;
791 case LOAD_NAME:
792 return 1;
793 case BUILD_TUPLE:
794 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000795 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796 return 1-oparg;
797 case BUILD_MAP:
798 return 1;
799 case LOAD_ATTR:
800 return 0;
801 case COMPARE_OP:
802 return -1;
803 case IMPORT_NAME:
804 return 0;
805 case IMPORT_FROM:
806 return 1;
807
808 case JUMP_FORWARD:
809 case JUMP_IF_FALSE:
810 case JUMP_IF_TRUE:
811 case JUMP_ABSOLUTE:
812 return 0;
813
814 case LOAD_GLOBAL:
815 return 1;
816
817 case CONTINUE_LOOP:
818 return 0;
819 case SETUP_LOOP:
820 return 0;
821 case SETUP_EXCEPT:
822 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000823 return 6; /* can push 3 values for the new exception
824 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000825
826 case LOAD_FAST:
827 return 1;
828 case STORE_FAST:
829 return -1;
830 case DELETE_FAST:
831 return 0;
832
833 case RAISE_VARARGS:
834 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000835#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000836 case CALL_FUNCTION:
837 return -NARGS(oparg);
838 case CALL_FUNCTION_VAR:
839 case CALL_FUNCTION_KW:
840 return -NARGS(oparg)-1;
841 case CALL_FUNCTION_VAR_KW:
842 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000843 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000844 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000845 case MAKE_CLOSURE:
846 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000847#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848 case BUILD_SLICE:
849 if (oparg == 3)
850 return -2;
851 else
852 return -1;
853
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854 case LOAD_CLOSURE:
855 return 1;
856 case LOAD_DEREF:
857 return 1;
858 case STORE_DEREF:
859 return -1;
860 default:
861 fprintf(stderr, "opcode = %d\n", opcode);
862 Py_FatalError("opcode_stack_effect()");
863
864 }
865 return 0; /* not reachable */
866}
867
868/* Add an opcode with no argument.
869 Returns 0 on failure, 1 on success.
870*/
871
872static int
873compiler_addop(struct compiler *c, int opcode)
874{
875 basicblock *b;
876 struct instr *i;
877 int off;
878 off = compiler_next_instr(c, c->u->u_curblock);
879 if (off < 0)
880 return 0;
881 b = c->u->u_curblock;
882 i = &b->b_instr[off];
883 i->i_opcode = opcode;
884 i->i_hasarg = 0;
885 if (opcode == RETURN_VALUE)
886 b->b_return = 1;
887 compiler_set_lineno(c, off);
888 return 1;
889}
890
891static int
892compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
893{
894 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000895 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000896 unsigned char *p, *q;
897 Py_complex z;
898 double d;
899 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000900
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000901 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000902 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
903 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000904 d = PyFloat_AS_DOUBLE(o);
905 p = (unsigned char*) &d;
906 /* all we need is to make the tuple different in either the 0.0
907 * or -0.0 case from all others, just to avoid the "coercion".
908 */
909 if (*p==0 && p[sizeof(double)-1]==0)
910 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
911 else
912 t = PyTuple_Pack(2, o, o->ob_type);
913 }
914 else if (PyComplex_Check(o)) {
915 /* complex case is even messier: we need to make complex(x,
916 0.) different from complex(x, -0.) and complex(0., y)
917 different from complex(-0., y), for any x and y. In
918 particular, all four complex zeros should be
919 distinguished.*/
920 z = PyComplex_AsCComplex(o);
921 p = (unsigned char*) &(z.real);
922 q = (unsigned char*) &(z.imag);
923 /* all that matters here is that on IEEE platforms
924 real_part_zero will be true if z.real == 0., and false if
925 z.real == -0. In fact, real_part_zero will also be true
926 for some other rarely occurring nonzero floats, but this
927 doesn't matter. Similar comments apply to
928 imag_part_zero. */
929 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
930 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
931 if (real_part_zero && imag_part_zero) {
932 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
933 }
934 else if (real_part_zero && !imag_part_zero) {
935 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
936 }
937 else if (!real_part_zero && imag_part_zero) {
938 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
939 }
940 else {
941 t = PyTuple_Pack(2, o, o->ob_type);
942 }
943 }
944 else {
945 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000946 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000947 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000948 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000949
950 v = PyDict_GetItem(dict, t);
951 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000952 if (PyErr_Occurred())
953 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000955 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956 if (!v) {
957 Py_DECREF(t);
958 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000959 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000960 if (PyDict_SetItem(dict, t, v) < 0) {
961 Py_DECREF(t);
962 Py_DECREF(v);
963 return -1;
964 }
965 Py_DECREF(v);
966 }
967 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000968 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000970 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000971}
972
973static int
974compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
975 PyObject *o)
976{
977 int arg = compiler_add_o(c, dict, o);
978 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000979 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980 return compiler_addop_i(c, opcode, arg);
981}
982
983static int
984compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000985 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986{
987 int arg;
988 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
989 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000990 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991 arg = compiler_add_o(c, dict, mangled);
992 Py_DECREF(mangled);
993 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000994 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000995 return compiler_addop_i(c, opcode, arg);
996}
997
998/* Add an opcode with an integer argument.
999 Returns 0 on failure, 1 on success.
1000*/
1001
1002static int
1003compiler_addop_i(struct compiler *c, int opcode, int oparg)
1004{
1005 struct instr *i;
1006 int off;
1007 off = compiler_next_instr(c, c->u->u_curblock);
1008 if (off < 0)
1009 return 0;
1010 i = &c->u->u_curblock->b_instr[off];
1011 i->i_opcode = opcode;
1012 i->i_oparg = oparg;
1013 i->i_hasarg = 1;
1014 compiler_set_lineno(c, off);
1015 return 1;
1016}
1017
1018static int
1019compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1020{
1021 struct instr *i;
1022 int off;
1023
1024 assert(b != NULL);
1025 off = compiler_next_instr(c, c->u->u_curblock);
1026 if (off < 0)
1027 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028 i = &c->u->u_curblock->b_instr[off];
1029 i->i_opcode = opcode;
1030 i->i_target = b;
1031 i->i_hasarg = 1;
1032 if (absolute)
1033 i->i_jabs = 1;
1034 else
1035 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001036 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037 return 1;
1038}
1039
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001040/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1041 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001042 it as the current block. NEXT_BLOCK() also creates an implicit jump
1043 from the current block to the new block.
1044*/
1045
Thomas Wouters89f507f2006-12-13 04:49:30 +00001046/* The returns inside these macros make it impossible to decref objects
1047 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048*/
1049
1050
1051#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001052 if (compiler_use_new_block((C)) == NULL) \
1053 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054}
1055
1056#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001057 if (compiler_next_block((C)) == NULL) \
1058 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059}
1060
1061#define ADDOP(C, OP) { \
1062 if (!compiler_addop((C), (OP))) \
1063 return 0; \
1064}
1065
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001066#define ADDOP_IN_SCOPE(C, OP) { \
1067 if (!compiler_addop((C), (OP))) { \
1068 compiler_exit_scope(c); \
1069 return 0; \
1070 } \
1071}
1072
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073#define ADDOP_O(C, OP, O, TYPE) { \
1074 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1075 return 0; \
1076}
1077
1078#define ADDOP_NAME(C, OP, O, TYPE) { \
1079 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1080 return 0; \
1081}
1082
1083#define ADDOP_I(C, OP, O) { \
1084 if (!compiler_addop_i((C), (OP), (O))) \
1085 return 0; \
1086}
1087
1088#define ADDOP_JABS(C, OP, O) { \
1089 if (!compiler_addop_j((C), (OP), (O), 1)) \
1090 return 0; \
1091}
1092
1093#define ADDOP_JREL(C, OP, O) { \
1094 if (!compiler_addop_j((C), (OP), (O), 0)) \
1095 return 0; \
1096}
1097
1098/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1099 the ASDL name to synthesize the name of the C type and the visit function.
1100*/
1101
1102#define VISIT(C, TYPE, V) {\
1103 if (!compiler_visit_ ## TYPE((C), (V))) \
1104 return 0; \
1105}
1106
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001107#define VISIT_IN_SCOPE(C, TYPE, V) {\
1108 if (!compiler_visit_ ## TYPE((C), (V))) { \
1109 compiler_exit_scope(c); \
1110 return 0; \
1111 } \
1112}
1113
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114#define VISIT_SLICE(C, V, CTX) {\
1115 if (!compiler_visit_slice((C), (V), (CTX))) \
1116 return 0; \
1117}
1118
1119#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001120 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001122 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001123 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124 if (!compiler_visit_ ## TYPE((C), elt)) \
1125 return 0; \
1126 } \
1127}
1128
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001129#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001131 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001133 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001134 if (!compiler_visit_ ## TYPE((C), elt)) { \
1135 compiler_exit_scope(c); \
1136 return 0; \
1137 } \
1138 } \
1139}
1140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141static int
1142compiler_isdocstring(stmt_ty s)
1143{
1144 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001145 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 return s->v.Expr.value->kind == Str_kind;
1147}
1148
1149/* Compile a sequence of statements, checking for a docstring. */
1150
1151static int
1152compiler_body(struct compiler *c, asdl_seq *stmts)
1153{
1154 int i = 0;
1155 stmt_ty st;
1156
1157 if (!asdl_seq_LEN(stmts))
1158 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001159 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001160 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1161 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 i = 1;
1163 VISIT(c, expr, st->v.Expr.value);
1164 if (!compiler_nameop(c, __doc__, Store))
1165 return 0;
1166 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001167 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001168 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 return 1;
1170}
1171
1172static PyCodeObject *
1173compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001174{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001175 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001176 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 static PyObject *module;
1178 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001179 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180 if (!module)
1181 return NULL;
1182 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001183 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1184 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001185 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 switch (mod->kind) {
1187 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001188 if (!compiler_body(c, mod->v.Module.body)) {
1189 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001190 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001191 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192 break;
1193 case Interactive_kind:
1194 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001195 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001196 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 break;
1198 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001199 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001200 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 break;
1202 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001203 PyErr_SetString(PyExc_SystemError,
1204 "suite should not be possible");
1205 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001206 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001207 PyErr_Format(PyExc_SystemError,
1208 "module kind %d should not be possible",
1209 mod->kind);
1210 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001211 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 co = assemble(c, addNone);
1213 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001214 return co;
1215}
1216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217/* The test for LOCAL must come before the test for FREE in order to
1218 handle classes where name is both local and free. The local var is
1219 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001220*/
1221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222static int
1223get_ref_type(struct compiler *c, PyObject *name)
1224{
1225 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001226 if (scope == 0) {
1227 char buf[350];
1228 PyOS_snprintf(buf, sizeof(buf),
1229 "unknown scope for %.100s in %.100s(%s) in %s\n"
1230 "symbols: %s\nlocals: %s\nglobals: %s\n",
Christian Heimes72b710a2008-05-26 13:28:38 +00001231 PyBytes_AS_STRING(name),
1232 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001233 PyObject_REPR(c->u->u_ste->ste_id),
1234 c->c_filename,
1235 PyObject_REPR(c->u->u_ste->ste_symbols),
1236 PyObject_REPR(c->u->u_varnames),
1237 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001239 Py_FatalError(buf);
1240 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001241
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001242 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243}
1244
1245static int
1246compiler_lookup_arg(PyObject *dict, PyObject *name)
1247{
1248 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001249 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001253 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001255 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001256 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259static int
1260compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1261{
1262 int i, free = PyCode_GetNumFree(co);
1263 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001264 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1265 ADDOP_I(c, MAKE_FUNCTION, args);
1266 return 1;
1267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268 for (i = 0; i < free; ++i) {
1269 /* Bypass com_addop_varname because it will generate
1270 LOAD_DEREF but LOAD_CLOSURE is needed.
1271 */
1272 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1273 int arg, reftype;
1274
1275 /* Special case: If a class contains a method with a
1276 free variable that has the same name as a method,
1277 the name will be considered free *and* local in the
1278 class. It should be handled by the closure, as
1279 well as by the normal name loookup logic.
1280 */
1281 reftype = get_ref_type(c, name);
1282 if (reftype == CELL)
1283 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1284 else /* (reftype == FREE) */
1285 arg = compiler_lookup_arg(c->u->u_freevars, name);
1286 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001287 fprintf(stderr,
1288 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289 "freevars of %s: %s\n",
1290 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001291 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 reftype, arg,
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001293 PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001294 PyObject_REPR(co->co_freevars));
1295 Py_FatalError("compiler_make_closure()");
1296 }
1297 ADDOP_I(c, LOAD_CLOSURE, arg);
1298 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001299 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001301 ADDOP_I(c, MAKE_CLOSURE, args);
1302 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303}
1304
1305static int
1306compiler_decorators(struct compiler *c, asdl_seq* decos)
1307{
1308 int i;
1309
1310 if (!decos)
1311 return 1;
1312
1313 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001314 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315 }
1316 return 1;
1317}
1318
1319static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001320compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1321 asdl_seq *kw_defaults)
1322{
1323 int i, default_count = 0;
1324 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001325 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001326 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1327 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001328 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001329 if (!compiler_visit_expr(c, default_)) {
1330 return -1;
1331 }
1332 default_count++;
1333 }
1334 }
1335 return default_count;
1336}
1337
1338static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001339compiler_visit_argannotation(struct compiler *c, identifier id,
1340 expr_ty annotation, PyObject *names)
1341{
1342 if (annotation) {
1343 VISIT(c, expr, annotation);
1344 if (PyList_Append(names, id))
1345 return -1;
1346 }
1347 return 0;
1348}
1349
1350static int
1351compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1352 PyObject *names)
1353{
1354 int i, error;
1355 for (i = 0; i < asdl_seq_LEN(args); i++) {
1356 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001357 error = compiler_visit_argannotation(
1358 c,
1359 arg->arg,
1360 arg->annotation,
1361 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001362 if (error)
1363 return error;
1364 }
1365 return 0;
1366}
1367
1368static int
1369compiler_visit_annotations(struct compiler *c, arguments_ty args,
1370 expr_ty returns)
1371{
Guido van Rossum0240b922007-02-26 21:23:50 +00001372 /* Push arg annotations and a list of the argument names. Return the #
1373 of items pushed. The expressions are evaluated out-of-order wrt the
1374 source code.
1375
1376 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1377 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001378 static identifier return_str;
1379 PyObject *names;
1380 int len;
1381 names = PyList_New(0);
1382 if (!names)
1383 return -1;
1384
1385 if (compiler_visit_argannotations(c, args->args, names))
1386 goto error;
1387 if (args->varargannotation &&
1388 compiler_visit_argannotation(c, args->vararg,
1389 args->varargannotation, names))
1390 goto error;
1391 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1392 goto error;
1393 if (args->kwargannotation &&
1394 compiler_visit_argannotation(c, args->kwarg,
1395 args->kwargannotation, names))
1396 goto error;
1397
1398 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001399 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001400 if (!return_str)
1401 goto error;
1402 }
1403 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1404 goto error;
1405 }
1406
1407 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001408 if (len > 65534) {
1409 /* len must fit in 16 bits, and len is incremented below */
1410 PyErr_SetString(PyExc_SyntaxError,
1411 "too many annotations");
1412 goto error;
1413 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001414 if (len) {
1415 /* convert names to a tuple and place on stack */
1416 PyObject *elt;
1417 int i;
1418 PyObject *s = PyTuple_New(len);
1419 if (!s)
1420 goto error;
1421 for (i = 0; i < len; i++) {
1422 elt = PyList_GET_ITEM(names, i);
1423 Py_INCREF(elt);
1424 PyTuple_SET_ITEM(s, i, elt);
1425 }
1426 ADDOP_O(c, LOAD_CONST, s, consts);
1427 Py_DECREF(s);
1428 len++; /* include the just-pushed tuple */
1429 }
1430 Py_DECREF(names);
1431 return len;
1432
1433error:
1434 Py_DECREF(names);
1435 return -1;
1436}
1437
1438static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439compiler_function(struct compiler *c, stmt_ty s)
1440{
1441 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001442 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001444 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001445 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001446 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001447 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001448 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449
1450 assert(s->kind == FunctionDef_kind);
1451
1452 if (!compiler_decorators(c, decos))
1453 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001454 if (args->kwonlyargs) {
1455 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1456 args->kw_defaults);
1457 if (res < 0)
1458 return 0;
1459 kw_default_count = res;
1460 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461 if (args->defaults)
1462 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001463 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001464 if (num_annotations < 0)
1465 return 0;
1466 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001467
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1469 s->lineno))
1470 return 0;
1471
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001472 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001473 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001474 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001475 first_const = st->v.Expr.value->v.Str.s;
1476 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001477 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001478 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001482 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001484 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001486 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1487 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 }
1489 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001490 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491 if (co == NULL)
1492 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493
Guido van Rossum4f72a782006-10-27 23:31:49 +00001494 arglength = asdl_seq_LEN(args->defaults);
1495 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001496 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001497 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001498 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499
Neal Norwitzc1505362006-12-28 06:47:50 +00001500 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1502 ADDOP_I(c, CALL_FUNCTION, 1);
1503 }
1504
1505 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1506}
1507
1508static int
1509compiler_class(struct compiler *c, stmt_ty s)
1510{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001511 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001513 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001514 PySTEntryObject *ste;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001515 int err, i;
1516 asdl_seq* decos = s->v.ClassDef.decorator_list;
1517
1518 if (!compiler_decorators(c, decos))
1519 return 0;
1520
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001521 /* initialize statics */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001522 if (locals == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001523 locals = PyUnicode_InternFromString("__locals__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001524 if (locals == NULL)
1525 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001528 /* ultimately generate code for:
1529 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1530 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001531 <func> is a function/closure created from the class body;
1532 it has a single argument (__locals__) where the dict
1533 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001534 <name> is the class name
1535 <bases> is the positional arguments and *varargs argument
1536 <keywords> is the keyword arguments and **kwds argument
1537 This borrows from compiler_call.
1538 */
1539
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001540 /* 0. Create a fake argument named __locals__ */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001541 ste = PySymtable_Lookup(c->c_st, s);
1542 if (ste == NULL)
1543 return 0;
1544 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001545 err = PyList_Append(ste->ste_varnames, locals);
1546 Py_DECREF(ste);
1547 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001548 return 0;
1549
1550 /* 1. compile the class body into a code object */
1551 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1552 return 0;
1553 /* this block represents what we do in the new scope */
1554 {
1555 /* use the class name for name mangling */
1556 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001557 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001558 c->u->u_private = s->v.ClassDef.name;
1559 /* force it to have one mandatory argument */
1560 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001561 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001562 ADDOP_I(c, LOAD_FAST, 0);
1563 /* ... and store it into f_locals */
1564 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001565 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001566 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001567 if (!str || !compiler_nameop(c, str, Load)) {
1568 Py_XDECREF(str);
1569 compiler_exit_scope(c);
1570 return 0;
1571 }
1572 Py_DECREF(str);
1573 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001574 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001575 if (!str || !compiler_nameop(c, str, Store)) {
1576 Py_XDECREF(str);
1577 compiler_exit_scope(c);
1578 return 0;
1579 }
1580 Py_DECREF(str);
1581 /* compile the body proper */
1582 if (!compiler_body(c, s->v.ClassDef.body)) {
1583 compiler_exit_scope(c);
1584 return 0;
1585 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001586 /* return the (empty) __class__ cell */
1587 str = PyUnicode_InternFromString("__class__");
1588 if (str == NULL) {
1589 compiler_exit_scope(c);
1590 return 0;
1591 }
1592 i = compiler_lookup_arg(c->u->u_cellvars, str);
1593 Py_DECREF(str);
1594 if (i == -1) {
1595 /* This happens when nobody references the cell */
1596 PyErr_Clear();
1597 /* Return None */
1598 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1599 }
1600 else {
1601 /* Return the cell where to store __class__ */
1602 ADDOP_I(c, LOAD_CLOSURE, i);
1603 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001604 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1605 /* create the code object */
1606 co = assemble(c, 1);
1607 }
1608 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001609 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001610 if (co == NULL)
1611 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001612
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001613 /* 2. load the 'build_class' function */
1614 ADDOP(c, LOAD_BUILD_CLASS);
1615
1616 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001617 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001618 Py_DECREF(co);
1619
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001620 /* 4. load class name */
1621 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1622
1623 /* 5. generate the rest of the code for the call */
1624 if (!compiler_call_helper(c, 2,
1625 s->v.ClassDef.bases,
1626 s->v.ClassDef.keywords,
1627 s->v.ClassDef.starargs,
1628 s->v.ClassDef.kwargs))
1629 return 0;
1630
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001631 /* 6. apply decorators */
1632 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1633 ADDOP_I(c, CALL_FUNCTION, 1);
1634 }
1635
1636 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1638 return 0;
1639 return 1;
1640}
1641
1642static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001643compiler_ifexp(struct compiler *c, expr_ty e)
1644{
1645 basicblock *end, *next;
1646
1647 assert(e->kind == IfExp_kind);
1648 end = compiler_new_block(c);
1649 if (end == NULL)
1650 return 0;
1651 next = compiler_new_block(c);
1652 if (next == NULL)
1653 return 0;
1654 VISIT(c, expr, e->v.IfExp.test);
1655 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1656 ADDOP(c, POP_TOP);
1657 VISIT(c, expr, e->v.IfExp.body);
1658 ADDOP_JREL(c, JUMP_FORWARD, end);
1659 compiler_use_next_block(c, next);
1660 ADDOP(c, POP_TOP);
1661 VISIT(c, expr, e->v.IfExp.orelse);
1662 compiler_use_next_block(c, end);
1663 return 1;
1664}
1665
1666static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667compiler_lambda(struct compiler *c, expr_ty e)
1668{
1669 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001670 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001671 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001672 arguments_ty args = e->v.Lambda.args;
1673 assert(e->kind == Lambda_kind);
1674
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001675 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001676 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001677 if (!name)
1678 return 0;
1679 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680
Guido van Rossum4f72a782006-10-27 23:31:49 +00001681 if (args->kwonlyargs) {
1682 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1683 args->kw_defaults);
1684 if (res < 0) return 0;
1685 kw_default_count = res;
1686 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687 if (args->defaults)
1688 VISIT_SEQ(c, expr, args->defaults);
1689 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1690 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001691
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001693 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001694 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1695 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001697 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698 if (co == NULL)
1699 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700
Guido van Rossum4f72a782006-10-27 23:31:49 +00001701 arglength = asdl_seq_LEN(args->defaults);
1702 arglength |= kw_default_count << 8;
1703 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001704 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705
1706 return 1;
1707}
1708
1709static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710compiler_if(struct compiler *c, stmt_ty s)
1711{
1712 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001713 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714 assert(s->kind == If_kind);
1715 end = compiler_new_block(c);
1716 if (end == NULL)
1717 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001718 next = compiler_new_block(c);
1719 if (next == NULL)
1720 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001721
1722 constant = expr_constant(s->v.If.test);
1723 /* constant = 0: "if 0"
1724 * constant = 1: "if 1", "if 2", ...
1725 * constant = -1: rest */
1726 if (constant == 0) {
1727 if (s->v.If.orelse)
1728 VISIT_SEQ(c, stmt, s->v.If.orelse);
1729 } else if (constant == 1) {
1730 VISIT_SEQ(c, stmt, s->v.If.body);
1731 } else {
1732 VISIT(c, expr, s->v.If.test);
1733 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1734 ADDOP(c, POP_TOP);
1735 VISIT_SEQ(c, stmt, s->v.If.body);
1736 ADDOP_JREL(c, JUMP_FORWARD, end);
1737 compiler_use_next_block(c, next);
1738 ADDOP(c, POP_TOP);
1739 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001740 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001741 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001742 compiler_use_next_block(c, end);
1743 return 1;
1744}
1745
1746static int
1747compiler_for(struct compiler *c, stmt_ty s)
1748{
1749 basicblock *start, *cleanup, *end;
1750
1751 start = compiler_new_block(c);
1752 cleanup = compiler_new_block(c);
1753 end = compiler_new_block(c);
1754 if (start == NULL || end == NULL || cleanup == NULL)
1755 return 0;
1756 ADDOP_JREL(c, SETUP_LOOP, end);
1757 if (!compiler_push_fblock(c, LOOP, start))
1758 return 0;
1759 VISIT(c, expr, s->v.For.iter);
1760 ADDOP(c, GET_ITER);
1761 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001762 /* for expressions must be traced on each iteration,
1763 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001764 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765 ADDOP_JREL(c, FOR_ITER, cleanup);
1766 VISIT(c, expr, s->v.For.target);
1767 VISIT_SEQ(c, stmt, s->v.For.body);
1768 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1769 compiler_use_next_block(c, cleanup);
1770 ADDOP(c, POP_BLOCK);
1771 compiler_pop_fblock(c, LOOP, start);
1772 VISIT_SEQ(c, stmt, s->v.For.orelse);
1773 compiler_use_next_block(c, end);
1774 return 1;
1775}
1776
1777static int
1778compiler_while(struct compiler *c, stmt_ty s)
1779{
1780 basicblock *loop, *orelse, *end, *anchor = NULL;
1781 int constant = expr_constant(s->v.While.test);
1782
Christian Heimes969fe572008-01-25 11:23:10 +00001783 if (constant == 0) {
1784 if (s->v.While.orelse)
1785 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001787 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788 loop = compiler_new_block(c);
1789 end = compiler_new_block(c);
1790 if (constant == -1) {
1791 anchor = compiler_new_block(c);
1792 if (anchor == NULL)
1793 return 0;
1794 }
1795 if (loop == NULL || end == NULL)
1796 return 0;
1797 if (s->v.While.orelse) {
1798 orelse = compiler_new_block(c);
1799 if (orelse == NULL)
1800 return 0;
1801 }
1802 else
1803 orelse = NULL;
1804
1805 ADDOP_JREL(c, SETUP_LOOP, end);
1806 compiler_use_next_block(c, loop);
1807 if (!compiler_push_fblock(c, LOOP, loop))
1808 return 0;
1809 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001810 /* while expressions must be traced on each iteration,
1811 so we need to set an extra line number. */
1812 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813 VISIT(c, expr, s->v.While.test);
1814 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1815 ADDOP(c, POP_TOP);
1816 }
1817 VISIT_SEQ(c, stmt, s->v.While.body);
1818 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1819
1820 /* XXX should the two POP instructions be in a separate block
1821 if there is no else clause ?
1822 */
1823
1824 if (constant == -1) {
1825 compiler_use_next_block(c, anchor);
1826 ADDOP(c, POP_TOP);
1827 ADDOP(c, POP_BLOCK);
1828 }
1829 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001830 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 VISIT_SEQ(c, stmt, s->v.While.orelse);
1832 compiler_use_next_block(c, end);
1833
1834 return 1;
1835}
1836
1837static int
1838compiler_continue(struct compiler *c)
1839{
1840 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001841 static const char IN_FINALLY_ERROR_MSG[] =
1842 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001843 int i;
1844
1845 if (!c->u->u_nfblocks)
1846 return compiler_error(c, LOOP_ERROR_MSG);
1847 i = c->u->u_nfblocks - 1;
1848 switch (c->u->u_fblock[i].fb_type) {
1849 case LOOP:
1850 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1851 break;
1852 case EXCEPT:
1853 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001854 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1855 /* Prevent continue anywhere under a finally
1856 even if hidden in a sub-try or except. */
1857 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1858 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1859 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860 if (i == -1)
1861 return compiler_error(c, LOOP_ERROR_MSG);
1862 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1863 break;
1864 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001865 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866 }
1867
1868 return 1;
1869}
1870
1871/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1872
1873 SETUP_FINALLY L
1874 <code for body>
1875 POP_BLOCK
1876 LOAD_CONST <None>
1877 L: <code for finalbody>
1878 END_FINALLY
1879
1880 The special instructions use the block stack. Each block
1881 stack entry contains the instruction that created it (here
1882 SETUP_FINALLY), the level of the value stack at the time the
1883 block stack entry was created, and a label (here L).
1884
1885 SETUP_FINALLY:
1886 Pushes the current value stack level and the label
1887 onto the block stack.
1888 POP_BLOCK:
1889 Pops en entry from the block stack, and pops the value
1890 stack until its level is the same as indicated on the
1891 block stack. (The label is ignored.)
1892 END_FINALLY:
1893 Pops a variable number of entries from the *value* stack
1894 and re-raises the exception they specify. The number of
1895 entries popped depends on the (pseudo) exception type.
1896
1897 The block stack is unwound when an exception is raised:
1898 when a SETUP_FINALLY entry is found, the exception is pushed
1899 onto the value stack (and the exception condition is cleared),
1900 and the interpreter jumps to the label gotten from the block
1901 stack.
1902*/
1903
1904static int
1905compiler_try_finally(struct compiler *c, stmt_ty s)
1906{
1907 basicblock *body, *end;
1908 body = compiler_new_block(c);
1909 end = compiler_new_block(c);
1910 if (body == NULL || end == NULL)
1911 return 0;
1912
1913 ADDOP_JREL(c, SETUP_FINALLY, end);
1914 compiler_use_next_block(c, body);
1915 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1916 return 0;
1917 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1918 ADDOP(c, POP_BLOCK);
1919 compiler_pop_fblock(c, FINALLY_TRY, body);
1920
1921 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1922 compiler_use_next_block(c, end);
1923 if (!compiler_push_fblock(c, FINALLY_END, end))
1924 return 0;
1925 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1926 ADDOP(c, END_FINALLY);
1927 compiler_pop_fblock(c, FINALLY_END, end);
1928
1929 return 1;
1930}
1931
1932/*
1933 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1934 (The contents of the value stack is shown in [], with the top
1935 at the right; 'tb' is trace-back info, 'val' the exception's
1936 associated value, and 'exc' the exception.)
1937
1938 Value stack Label Instruction Argument
1939 [] SETUP_EXCEPT L1
1940 [] <code for S>
1941 [] POP_BLOCK
1942 [] JUMP_FORWARD L0
1943
1944 [tb, val, exc] L1: DUP )
1945 [tb, val, exc, exc] <evaluate E1> )
1946 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1947 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1948 [tb, val, exc, 1] POP )
1949 [tb, val, exc] POP
1950 [tb, val] <assign to V1> (or POP if no V1)
1951 [tb] POP
1952 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001953 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954
1955 [tb, val, exc, 0] L2: POP
1956 [tb, val, exc] DUP
1957 .............................etc.......................
1958
1959 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001960 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
1962 [] L0: <next statement>
1963
1964 Of course, parts are not generated if Vi or Ei is not present.
1965*/
1966static int
1967compiler_try_except(struct compiler *c, stmt_ty s)
1968{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001969 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970 int i, n;
1971
1972 body = compiler_new_block(c);
1973 except = compiler_new_block(c);
1974 orelse = compiler_new_block(c);
1975 end = compiler_new_block(c);
1976 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1977 return 0;
1978 ADDOP_JREL(c, SETUP_EXCEPT, except);
1979 compiler_use_next_block(c, body);
1980 if (!compiler_push_fblock(c, EXCEPT, body))
1981 return 0;
1982 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1983 ADDOP(c, POP_BLOCK);
1984 compiler_pop_fblock(c, EXCEPT, body);
1985 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1986 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1987 compiler_use_next_block(c, except);
1988 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001989 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001991 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001993 c->u->u_lineno_set = 0;
1994 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995 except = compiler_new_block(c);
1996 if (except == NULL)
1997 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001998 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002000 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2002 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2003 ADDOP(c, POP_TOP);
2004 }
2005 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002006 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00002007 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002008
2009 cleanup_end = compiler_new_block(c);
2010 cleanup_body = compiler_new_block(c);
2011 if(!(cleanup_end || cleanup_body))
2012 return 0;
2013
Neal Norwitzad74aa82008-03-31 05:14:30 +00002014 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002015 ADDOP(c, POP_TOP);
2016
2017 /*
2018 try:
2019 # body
2020 except type as name:
2021 try:
2022 # body
2023 finally:
2024 name = None
2025 del name
2026 */
2027
2028 /* second try: */
2029 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2030 compiler_use_next_block(c, cleanup_body);
2031 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2032 return 0;
2033
2034 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002035 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002036 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002037 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002038 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2039
2040 /* finally: */
2041 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2042 compiler_use_next_block(c, cleanup_end);
2043 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2044 return 0;
2045
2046 /* name = None */
2047 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002048 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002049
Guido van Rossum16be03e2007-01-10 18:51:35 +00002050 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002051 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002052
2053 ADDOP(c, END_FINALLY);
2054 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 }
2056 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002057 basicblock *cleanup_body;
2058
2059 cleanup_body = compiler_new_block(c);
2060 if(!cleanup_body)
2061 return 0;
2062
2063 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002064 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002065 compiler_use_next_block(c, cleanup_body);
2066 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2067 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002068 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002069 ADDOP(c, POP_EXCEPT);
2070 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 ADDOP_JREL(c, JUMP_FORWARD, end);
2073 compiler_use_next_block(c, except);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002074 if (handler->v.ExceptHandler.type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 ADDOP(c, POP_TOP);
2076 }
2077 ADDOP(c, END_FINALLY);
2078 compiler_use_next_block(c, orelse);
2079 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2080 compiler_use_next_block(c, end);
2081 return 1;
2082}
2083
2084static int
2085compiler_import_as(struct compiler *c, identifier name, identifier asname)
2086{
2087 /* The IMPORT_NAME opcode was already generated. This function
2088 merely needs to bind the result to a name.
2089
2090 If there is a dot in name, we need to split it and emit a
2091 LOAD_ATTR for each name.
2092 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002093 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2094 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 if (dot) {
2096 /* Consume the base module name to get the first attribute */
2097 src = dot + 1;
2098 while (dot) {
2099 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002100 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002101 dot = Py_UNICODE_strchr(src, '.');
2102 attr = PyUnicode_FromUnicode(src,
2103 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002104 if (!attr)
2105 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002107 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 src = dot + 1;
2109 }
2110 }
2111 return compiler_nameop(c, asname, Store);
2112}
2113
2114static int
2115compiler_import(struct compiler *c, stmt_ty s)
2116{
2117 /* The Import node stores a module name like a.b.c as a single
2118 string. This is convenient for all cases except
2119 import a.b.c as d
2120 where we need to parse that string to extract the individual
2121 module names.
2122 XXX Perhaps change the representation to make this case simpler?
2123 */
2124 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002125
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002127 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002129 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130
Christian Heimes217cfd12007-12-02 14:31:20 +00002131 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002132 if (level == NULL)
2133 return 0;
2134
2135 ADDOP_O(c, LOAD_CONST, level, consts);
2136 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2138 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2139
2140 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002141 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002142 if (!r)
2143 return r;
2144 }
2145 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002147 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2148 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002150 tmp = PyUnicode_FromUnicode(base,
2151 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 r = compiler_nameop(c, tmp, Store);
2153 if (dot) {
2154 Py_DECREF(tmp);
2155 }
2156 if (!r)
2157 return r;
2158 }
2159 }
2160 return 1;
2161}
2162
2163static int
2164compiler_from_import(struct compiler *c, stmt_ty s)
2165{
2166 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167
2168 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002169 PyObject *level;
2170
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002171 if (!names)
2172 return 0;
2173
Christian Heimes217cfd12007-12-02 14:31:20 +00002174 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002175 if (!level) {
2176 Py_DECREF(names);
2177 return 0;
2178 }
2179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 /* build up the names */
2181 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002182 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183 Py_INCREF(alias->name);
2184 PyTuple_SET_ITEM(names, i, alias->name);
2185 }
2186
2187 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002188 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2189 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002190 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191 Py_DECREF(names);
2192 return compiler_error(c,
2193 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002194 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195
2196 }
2197 }
2198
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002199 ADDOP_O(c, LOAD_CONST, level, consts);
2200 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002202 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2204 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002205 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002206 identifier store_name;
2207
Martin v. Löwis5b222132007-06-10 09:51:05 +00002208 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209 assert(n == 1);
2210 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002211 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212 }
2213
2214 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2215 store_name = alias->name;
2216 if (alias->asname)
2217 store_name = alias->asname;
2218
2219 if (!compiler_nameop(c, store_name, Store)) {
2220 Py_DECREF(names);
2221 return 0;
2222 }
2223 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002224 /* remove imported module */
2225 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226 return 1;
2227}
2228
2229static int
2230compiler_assert(struct compiler *c, stmt_ty s)
2231{
2232 static PyObject *assertion_error = NULL;
2233 basicblock *end;
2234
2235 if (Py_OptimizeFlag)
2236 return 1;
2237 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002238 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239 if (assertion_error == NULL)
2240 return 0;
2241 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002242 if (s->v.Assert.test->kind == Tuple_kind &&
2243 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2244 const char* msg =
2245 "assertion is always true, perhaps remove parentheses?";
2246 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2247 c->u->u_lineno, NULL, NULL) == -1)
2248 return 0;
2249 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250 VISIT(c, expr, s->v.Assert.test);
2251 end = compiler_new_block(c);
2252 if (end == NULL)
2253 return 0;
2254 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2255 ADDOP(c, POP_TOP);
2256 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2257 if (s->v.Assert.msg) {
2258 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002259 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 }
Collin Winter828f04a2007-08-31 00:04:24 +00002261 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002262 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 ADDOP(c, POP_TOP);
2264 return 1;
2265}
2266
2267static int
2268compiler_visit_stmt(struct compiler *c, stmt_ty s)
2269{
2270 int i, n;
2271
Thomas Wouters89f507f2006-12-13 04:49:30 +00002272 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002274 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002277 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002279 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002281 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 if (c->u->u_ste->ste_type != FunctionBlock)
2283 return compiler_error(c, "'return' outside function");
2284 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285 VISIT(c, expr, s->v.Return.value);
2286 }
2287 else
2288 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2289 ADDOP(c, RETURN_VALUE);
2290 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 VISIT_SEQ(c, expr, s->v.Delete.targets)
2293 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002294 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002295 n = asdl_seq_LEN(s->v.Assign.targets);
2296 VISIT(c, expr, s->v.Assign.value);
2297 for (i = 0; i < n; i++) {
2298 if (i < n - 1)
2299 ADDOP(c, DUP_TOP);
2300 VISIT(c, expr,
2301 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2302 }
2303 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002304 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002306 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002308 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002310 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002312 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002314 if (s->v.Raise.exc) {
2315 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002317 if (s->v.Raise.cause) {
2318 VISIT(c, expr, s->v.Raise.cause);
2319 n++;
2320 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 }
2322 ADDOP_I(c, RAISE_VARARGS, n);
2323 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002324 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002326 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002328 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002330 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002332 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002334 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002335 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002337 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002339 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340 ADDOP(c, PRINT_EXPR);
2341 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002342 else if (s->v.Expr.value->kind != Str_kind &&
2343 s->v.Expr.value->kind != Num_kind) {
2344 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 ADDOP(c, POP_TOP);
2346 }
2347 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002348 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002350 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002351 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352 return compiler_error(c, "'break' outside loop");
2353 ADDOP(c, BREAK_LOOP);
2354 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002355 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002357 case With_kind:
2358 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359 }
2360 return 1;
2361}
2362
2363static int
2364unaryop(unaryop_ty op)
2365{
2366 switch (op) {
2367 case Invert:
2368 return UNARY_INVERT;
2369 case Not:
2370 return UNARY_NOT;
2371 case UAdd:
2372 return UNARY_POSITIVE;
2373 case USub:
2374 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002375 default:
2376 PyErr_Format(PyExc_SystemError,
2377 "unary op %d should not be possible", op);
2378 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380}
2381
2382static int
2383binop(struct compiler *c, operator_ty op)
2384{
2385 switch (op) {
2386 case Add:
2387 return BINARY_ADD;
2388 case Sub:
2389 return BINARY_SUBTRACT;
2390 case Mult:
2391 return BINARY_MULTIPLY;
2392 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002393 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394 case Mod:
2395 return BINARY_MODULO;
2396 case Pow:
2397 return BINARY_POWER;
2398 case LShift:
2399 return BINARY_LSHIFT;
2400 case RShift:
2401 return BINARY_RSHIFT;
2402 case BitOr:
2403 return BINARY_OR;
2404 case BitXor:
2405 return BINARY_XOR;
2406 case BitAnd:
2407 return BINARY_AND;
2408 case FloorDiv:
2409 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002410 default:
2411 PyErr_Format(PyExc_SystemError,
2412 "binary op %d should not be possible", op);
2413 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002414 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415}
2416
2417static int
2418cmpop(cmpop_ty op)
2419{
2420 switch (op) {
2421 case Eq:
2422 return PyCmp_EQ;
2423 case NotEq:
2424 return PyCmp_NE;
2425 case Lt:
2426 return PyCmp_LT;
2427 case LtE:
2428 return PyCmp_LE;
2429 case Gt:
2430 return PyCmp_GT;
2431 case GtE:
2432 return PyCmp_GE;
2433 case Is:
2434 return PyCmp_IS;
2435 case IsNot:
2436 return PyCmp_IS_NOT;
2437 case In:
2438 return PyCmp_IN;
2439 case NotIn:
2440 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002441 default:
2442 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444}
2445
2446static int
2447inplace_binop(struct compiler *c, operator_ty op)
2448{
2449 switch (op) {
2450 case Add:
2451 return INPLACE_ADD;
2452 case Sub:
2453 return INPLACE_SUBTRACT;
2454 case Mult:
2455 return INPLACE_MULTIPLY;
2456 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002457 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 case Mod:
2459 return INPLACE_MODULO;
2460 case Pow:
2461 return INPLACE_POWER;
2462 case LShift:
2463 return INPLACE_LSHIFT;
2464 case RShift:
2465 return INPLACE_RSHIFT;
2466 case BitOr:
2467 return INPLACE_OR;
2468 case BitXor:
2469 return INPLACE_XOR;
2470 case BitAnd:
2471 return INPLACE_AND;
2472 case FloorDiv:
2473 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002474 default:
2475 PyErr_Format(PyExc_SystemError,
2476 "inplace binary op %d should not be possible", op);
2477 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479}
2480
2481static int
2482compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2483{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002484 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2486
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002487 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002488 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 /* XXX AugStore isn't used anywhere! */
2490
2491 /* First check for assignment to __debug__. Param? */
2492 if ((ctx == Store || ctx == AugStore || ctx == Del)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002493 && !PyUnicode_CompareWithASCIIString(name, "__debug__")) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494 return compiler_error(c, "can not assign to __debug__");
2495 }
2496
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002497 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002498 if (!mangled)
2499 return 0;
2500
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 op = 0;
2502 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002503 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504 switch (scope) {
2505 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002506 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 optype = OP_DEREF;
2508 break;
2509 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002510 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 optype = OP_DEREF;
2512 break;
2513 case LOCAL:
2514 if (c->u->u_ste->ste_type == FunctionBlock)
2515 optype = OP_FAST;
2516 break;
2517 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002518 if (c->u->u_ste->ste_type == FunctionBlock &&
2519 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520 optype = OP_GLOBAL;
2521 break;
2522 case GLOBAL_EXPLICIT:
2523 optype = OP_GLOBAL;
2524 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002525 default:
2526 /* scope can be 0 */
2527 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002528 }
2529
2530 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002531 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532
2533 switch (optype) {
2534 case OP_DEREF:
2535 switch (ctx) {
2536 case Load: op = LOAD_DEREF; break;
2537 case Store: op = STORE_DEREF; break;
2538 case AugLoad:
2539 case AugStore:
2540 break;
2541 case Del:
2542 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002543 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002545 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002546 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002549 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002550 PyErr_SetString(PyExc_SystemError,
2551 "param invalid for deref variable");
2552 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553 }
2554 break;
2555 case OP_FAST:
2556 switch (ctx) {
2557 case Load: op = LOAD_FAST; break;
2558 case Store: op = STORE_FAST; break;
2559 case Del: op = DELETE_FAST; break;
2560 case AugLoad:
2561 case AugStore:
2562 break;
2563 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002564 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002565 PyErr_SetString(PyExc_SystemError,
2566 "param invalid for local variable");
2567 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002569 ADDOP_O(c, op, mangled, varnames);
2570 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 return 1;
2572 case OP_GLOBAL:
2573 switch (ctx) {
2574 case Load: op = LOAD_GLOBAL; break;
2575 case Store: op = STORE_GLOBAL; break;
2576 case Del: op = DELETE_GLOBAL; break;
2577 case AugLoad:
2578 case AugStore:
2579 break;
2580 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002581 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002582 PyErr_SetString(PyExc_SystemError,
2583 "param invalid for global variable");
2584 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 }
2586 break;
2587 case OP_NAME:
2588 switch (ctx) {
2589 case Load: op = LOAD_NAME; break;
2590 case Store: op = STORE_NAME; break;
2591 case Del: op = DELETE_NAME; break;
2592 case AugLoad:
2593 case AugStore:
2594 break;
2595 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002596 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002597 PyErr_SetString(PyExc_SystemError,
2598 "param invalid for name variable");
2599 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 }
2601 break;
2602 }
2603
2604 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002605 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002606 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002607 if (arg < 0)
2608 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002609 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610}
2611
2612static int
2613compiler_boolop(struct compiler *c, expr_ty e)
2614{
2615 basicblock *end;
2616 int jumpi, i, n;
2617 asdl_seq *s;
2618
2619 assert(e->kind == BoolOp_kind);
2620 if (e->v.BoolOp.op == And)
2621 jumpi = JUMP_IF_FALSE;
2622 else
2623 jumpi = JUMP_IF_TRUE;
2624 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002625 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 return 0;
2627 s = e->v.BoolOp.values;
2628 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002629 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002631 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632 ADDOP_JREL(c, jumpi, end);
2633 ADDOP(c, POP_TOP)
2634 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002635 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 compiler_use_next_block(c, end);
2637 return 1;
2638}
2639
2640static int
2641compiler_list(struct compiler *c, expr_ty e)
2642{
2643 int n = asdl_seq_LEN(e->v.List.elts);
2644 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002645 int i, seen_star = 0;
2646 for (i = 0; i < n; i++) {
2647 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2648 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002649 if ((i >= (1 << 8)) ||
2650 (n-i-1 >= (INT_MAX >> 8)))
2651 return compiler_error(c,
2652 "too many expressions in "
2653 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002654 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2655 seen_star = 1;
2656 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2657 } else if (elt->kind == Starred_kind) {
2658 return compiler_error(c,
2659 "two starred expressions in assignment");
2660 }
2661 }
2662 if (!seen_star) {
2663 ADDOP_I(c, UNPACK_SEQUENCE, n);
2664 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665 }
2666 VISIT_SEQ(c, expr, e->v.List.elts);
2667 if (e->v.List.ctx == Load) {
2668 ADDOP_I(c, BUILD_LIST, n);
2669 }
2670 return 1;
2671}
2672
2673static int
2674compiler_tuple(struct compiler *c, expr_ty e)
2675{
2676 int n = asdl_seq_LEN(e->v.Tuple.elts);
2677 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002678 int i, seen_star = 0;
2679 for (i = 0; i < n; i++) {
2680 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2681 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002682 if ((i >= (1 << 8)) ||
2683 (n-i-1 >= (INT_MAX >> 8)))
2684 return compiler_error(c,
2685 "too many expressions in "
2686 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002687 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2688 seen_star = 1;
2689 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2690 } else if (elt->kind == Starred_kind) {
2691 return compiler_error(c,
2692 "two starred expressions in assignment");
2693 }
2694 }
2695 if (!seen_star) {
2696 ADDOP_I(c, UNPACK_SEQUENCE, n);
2697 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 }
2699 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2700 if (e->v.Tuple.ctx == Load) {
2701 ADDOP_I(c, BUILD_TUPLE, n);
2702 }
2703 return 1;
2704}
2705
2706static int
2707compiler_compare(struct compiler *c, expr_ty e)
2708{
2709 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711
2712 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2713 VISIT(c, expr, e->v.Compare.left);
2714 n = asdl_seq_LEN(e->v.Compare.ops);
2715 assert(n > 0);
2716 if (n > 1) {
2717 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002718 if (cleanup == NULL)
2719 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002720 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002721 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 }
2723 for (i = 1; i < n; i++) {
2724 ADDOP(c, DUP_TOP);
2725 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002727 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002728 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2730 NEXT_BLOCK(c);
2731 ADDOP(c, POP_TOP);
2732 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002733 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002734 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002736 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002738 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739 if (n > 1) {
2740 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002741 if (end == NULL)
2742 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 ADDOP_JREL(c, JUMP_FORWARD, end);
2744 compiler_use_next_block(c, cleanup);
2745 ADDOP(c, ROT_TWO);
2746 ADDOP(c, POP_TOP);
2747 compiler_use_next_block(c, end);
2748 }
2749 return 1;
2750}
2751
2752static int
2753compiler_call(struct compiler *c, expr_ty e)
2754{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002756 return compiler_call_helper(c, 0,
2757 e->v.Call.args,
2758 e->v.Call.keywords,
2759 e->v.Call.starargs,
2760 e->v.Call.kwargs);
2761}
2762
2763/* shared code between compiler_call and compiler_class */
2764static int
2765compiler_call_helper(struct compiler *c,
2766 int n, /* Args already pushed */
2767 asdl_seq *args,
2768 asdl_seq *keywords,
2769 expr_ty starargs,
2770 expr_ty kwargs)
2771{
2772 int code = 0;
2773
2774 n += asdl_seq_LEN(args);
2775 VISIT_SEQ(c, expr, args);
2776 if (keywords) {
2777 VISIT_SEQ(c, keyword, keywords);
2778 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002780 if (starargs) {
2781 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782 code |= 1;
2783 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002784 if (kwargs) {
2785 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786 code |= 2;
2787 }
2788 switch (code) {
2789 case 0:
2790 ADDOP_I(c, CALL_FUNCTION, n);
2791 break;
2792 case 1:
2793 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2794 break;
2795 case 2:
2796 ADDOP_I(c, CALL_FUNCTION_KW, n);
2797 break;
2798 case 3:
2799 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2800 break;
2801 }
2802 return 1;
2803}
2804
Nick Coghlan650f0d02007-04-15 12:05:43 +00002805
2806/* List and set comprehensions and generator expressions work by creating a
2807 nested function to perform the actual iteration. This means that the
2808 iteration variables don't leak into the current scope.
2809 The defined function is called immediately following its definition, with the
2810 result of that call being the result of the expression.
2811 The LC/SC version returns the populated container, while the GE version is
2812 flagged in symtable.c as a generator, so it returns the generator object
2813 when the function is called.
2814 This code *knows* that the loop cannot contain break, continue, or return,
2815 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2816
2817 Possible cleanups:
2818 - iterate over the generator sequence instead of using recursion
2819*/
2820
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002822compiler_comprehension_generator(struct compiler *c, PyObject *tmpname,
2823 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002824 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825{
2826 /* generate code for the iterator, then each of the ifs,
2827 and then write to the element */
2828
Nick Coghlan650f0d02007-04-15 12:05:43 +00002829 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002831 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
2833 start = compiler_new_block(c);
2834 skip = compiler_new_block(c);
2835 if_cleanup = compiler_new_block(c);
2836 anchor = compiler_new_block(c);
2837
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002838 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002839 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841
Nick Coghlan650f0d02007-04-15 12:05:43 +00002842 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844 if (gen_index == 0) {
2845 /* Receive outermost iter as an implicit argument */
2846 c->u->u_argcount = 1;
2847 ADDOP_I(c, LOAD_FAST, 0);
2848 }
2849 else {
2850 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002851 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852 ADDOP(c, GET_ITER);
2853 }
2854 compiler_use_next_block(c, start);
2855 ADDOP_JREL(c, FOR_ITER, anchor);
2856 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002857 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002859 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002860 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002862 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863 VISIT(c, expr, e);
2864 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2865 NEXT_BLOCK(c);
2866 ADDOP(c, POP_TOP);
2867 }
2868
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002869 if (++gen_index < asdl_seq_LEN(generators))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002870 if (!compiler_comprehension_generator(c, tmpname,
2871 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002872 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002873 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002876 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002877 /* comprehension specific code */
2878 switch (type) {
2879 case COMP_GENEXP:
2880 VISIT(c, expr, elt);
2881 ADDOP(c, YIELD_VALUE);
2882 ADDOP(c, POP_TOP);
2883 break;
2884 case COMP_LISTCOMP:
2885 if (!compiler_nameop(c, tmpname, Load))
2886 return 0;
2887 VISIT(c, expr, elt);
2888 ADDOP(c, LIST_APPEND);
2889 break;
2890 case COMP_SETCOMP:
2891 if (!compiler_nameop(c, tmpname, Load))
2892 return 0;
2893 VISIT(c, expr, elt);
2894 ADDOP(c, SET_ADD);
2895 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002896 case COMP_DICTCOMP:
2897 if (!compiler_nameop(c, tmpname, Load))
2898 return 0;
2899 /* With 'd[k] = v', v is evaluated before k, so we do
2900 the same. STORE_SUBSCR requires (item, map, key),
2901 so we still end up ROTing once. */
2902 VISIT(c, expr, val);
2903 ADDOP(c, ROT_TWO);
2904 VISIT(c, expr, elt);
2905 ADDOP(c, STORE_SUBSCR);
2906 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002907 default:
2908 return 0;
2909 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910
2911 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002912 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002913 for (i = 0; i < n; i++) {
2914 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002915 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 ADDOP(c, POP_TOP);
2919 }
2920 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2921 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922
2923 return 1;
2924}
2925
2926static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002927compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002928 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002929{
2930 PyCodeObject *co = NULL;
2931 identifier tmp = NULL;
2932 expr_ty outermost_iter;
2933
2934 outermost_iter = ((comprehension_ty)
2935 asdl_seq_GET(generators, 0))->iter;
2936
2937 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2938 goto error;
2939
2940 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002941 int op;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002942 tmp = compiler_new_tmpname(c);
2943 if (!tmp)
2944 goto error_in_scope;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002945 switch (type) {
2946 case COMP_LISTCOMP:
2947 op = BUILD_LIST;
2948 break;
2949 case COMP_SETCOMP:
2950 op = BUILD_SET;
2951 break;
2952 case COMP_DICTCOMP:
2953 op = BUILD_MAP;
2954 break;
2955 default:
2956 PyErr_Format(PyExc_SystemError,
2957 "unknown comprehension type %d", type);
2958 goto error_in_scope;
2959 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002960
Guido van Rossum992d4a32007-07-11 13:09:30 +00002961 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002962 ADDOP(c, DUP_TOP);
2963 if (!compiler_nameop(c, tmp, Store))
2964 goto error_in_scope;
2965 }
2966
Guido van Rossum992d4a32007-07-11 13:09:30 +00002967 if (!compiler_comprehension_generator(c, tmp, generators, 0, elt,
2968 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002969 goto error_in_scope;
2970
2971 if (type != COMP_GENEXP) {
2972 ADDOP(c, RETURN_VALUE);
2973 }
2974
2975 co = assemble(c, 1);
2976 compiler_exit_scope(c);
2977 if (co == NULL)
2978 goto error;
2979
2980 if (!compiler_make_closure(c, co, 0))
2981 goto error;
2982 Py_DECREF(co);
2983 Py_XDECREF(tmp);
2984
2985 VISIT(c, expr, outermost_iter);
2986 ADDOP(c, GET_ITER);
2987 ADDOP_I(c, CALL_FUNCTION, 1);
2988 return 1;
2989error_in_scope:
2990 compiler_exit_scope(c);
2991error:
2992 Py_XDECREF(co);
2993 Py_XDECREF(tmp);
2994 return 0;
2995}
2996
2997static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998compiler_genexp(struct compiler *c, expr_ty e)
2999{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003000 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003001 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00003002 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003003 if (!name)
3004 return 0;
3005 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003006 assert(e->kind == GeneratorExp_kind);
3007 return compiler_comprehension(c, e, COMP_GENEXP, name,
3008 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003009 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010}
3011
3012static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003013compiler_listcomp(struct compiler *c, expr_ty e)
3014{
3015 static identifier name;
3016 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003017 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00003018 if (!name)
3019 return 0;
3020 }
3021 assert(e->kind == ListComp_kind);
3022 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3023 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003024 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003025}
3026
3027static int
3028compiler_setcomp(struct compiler *c, expr_ty e)
3029{
3030 static identifier name;
3031 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003032 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00003033 if (!name)
3034 return 0;
3035 }
3036 assert(e->kind == SetComp_kind);
3037 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3038 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003039 e->v.SetComp.elt, NULL);
3040}
3041
3042
3043static int
3044compiler_dictcomp(struct compiler *c, expr_ty e)
3045{
3046 static identifier name;
3047 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003048 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003049 if (!name)
3050 return 0;
3051 }
3052 assert(e->kind == DictComp_kind);
3053 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3054 e->v.DictComp.generators,
3055 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003056}
3057
3058
3059static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003060compiler_visit_keyword(struct compiler *c, keyword_ty k)
3061{
3062 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3063 VISIT(c, expr, k->value);
3064 return 1;
3065}
3066
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003067/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003068 whether they are true or false.
3069
3070 Return values: 1 for true, 0 for false, -1 for non-constant.
3071 */
3072
3073static int
3074expr_constant(expr_ty e)
3075{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003076 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003078 case Ellipsis_kind:
3079 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080 case Num_kind:
3081 return PyObject_IsTrue(e->v.Num.n);
3082 case Str_kind:
3083 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003084 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003085 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003086 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003087 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003088 if (strcmp(id, "True") == 0) return 1;
3089 if (strcmp(id, "False") == 0) return 0;
3090 if (strcmp(id, "None") == 0) return 0;
3091 if (strcmp(id, "__debug__") == 0)
3092 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003093 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094 default:
3095 return -1;
3096 }
3097}
3098
Guido van Rossumc2e20742006-02-27 22:32:47 +00003099/*
3100 Implements the with statement from PEP 343.
3101
3102 The semantics outlined in that PEP are as follows:
3103
3104 with EXPR as VAR:
3105 BLOCK
3106
3107 It is implemented roughly as:
3108
Thomas Wouters477c8d52006-05-27 19:21:47 +00003109 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003110 exit = context.__exit__ # not calling it
3111 value = context.__enter__()
3112 try:
3113 VAR = value # if VAR present in the syntax
3114 BLOCK
3115 finally:
3116 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003117 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003118 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003119 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003120 exit(*exc)
3121 */
3122static int
3123compiler_with(struct compiler *c, stmt_ty s)
3124{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003125 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003126 basicblock *block, *finally;
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003127 identifier tmpvalue = NULL, tmpexit = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003128
3129 assert(s->kind == With_kind);
3130
Guido van Rossumc2e20742006-02-27 22:32:47 +00003131 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003132 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003133 if (!enter_attr)
3134 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003135 }
3136 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003137 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 if (!exit_attr)
3139 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003140 }
3141
3142 block = compiler_new_block(c);
3143 finally = compiler_new_block(c);
3144 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003145 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003146
Guido van Rossumc2e20742006-02-27 22:32:47 +00003147 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003149 We need to do this rather than preserving it on the stack
3150 because SETUP_FINALLY remembers the stack level.
3151 We need to do the assignment *inside* the try/finally
3152 so that context.__exit__() is called when the assignment
3153 fails. But we need to call context.__enter__() *before*
3154 the try/finally so that if it fails we won't call
3155 context.__exit__().
3156 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003157 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003158 if (tmpvalue == NULL)
3159 return 0;
3160 PyArena_AddPyObject(c->c_arena, tmpvalue);
3161 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003162 tmpexit = compiler_new_tmpname(c);
3163 if (tmpexit == NULL)
3164 return 0;
3165 PyArena_AddPyObject(c->c_arena, tmpexit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003166
Thomas Wouters477c8d52006-05-27 19:21:47 +00003167 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003168 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003169
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003170 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003171 ADDOP(c, DUP_TOP);
3172 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003173 if (!compiler_nameop(c, tmpexit, Store))
3174 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003175
3176 /* Call context.__enter__() */
3177 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3178 ADDOP_I(c, CALL_FUNCTION, 0);
3179
3180 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 /* Store it in tmpvalue */
3182 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003183 return 0;
3184 }
3185 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003186 /* Discard result from context.__enter__() */
3187 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003188 }
3189
3190 /* Start the try block */
3191 ADDOP_JREL(c, SETUP_FINALLY, finally);
3192
3193 compiler_use_next_block(c, block);
3194 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003196 }
3197
3198 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003199 /* Bind saved result of context.__enter__() to VAR */
3200 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003201 !compiler_nameop(c, tmpvalue, Del))
3202 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003204 }
3205
3206 /* BLOCK code */
3207 VISIT_SEQ(c, stmt, s->v.With.body);
3208
3209 /* End of try block; start the finally block */
3210 ADDOP(c, POP_BLOCK);
3211 compiler_pop_fblock(c, FINALLY_TRY, block);
3212
3213 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3214 compiler_use_next_block(c, finally);
3215 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003216 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003217
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003218 /* Finally block starts; context.__exit__ is on the stack under
3219 the exception or return information. Just issue our magic
3220 opcode. */
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003221 if (!compiler_nameop(c, tmpexit, Load) ||
3222 !compiler_nameop(c, tmpexit, Del))
3223 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003224 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003225
3226 /* Finally block ends. */
3227 ADDOP(c, END_FINALLY);
3228 compiler_pop_fblock(c, FINALLY_END, finally);
3229 return 1;
3230}
3231
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232static int
3233compiler_visit_expr(struct compiler *c, expr_ty e)
3234{
3235 int i, n;
3236
Thomas Wouters89f507f2006-12-13 04:49:30 +00003237 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003238 set a new line number for the next instruction.
3239 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240 if (e->lineno > c->u->u_lineno) {
3241 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003242 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003243 }
3244 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003245 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003247 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248 VISIT(c, expr, e->v.BinOp.left);
3249 VISIT(c, expr, e->v.BinOp.right);
3250 ADDOP(c, binop(c, e->v.BinOp.op));
3251 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003252 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253 VISIT(c, expr, e->v.UnaryOp.operand);
3254 ADDOP(c, unaryop(e->v.UnaryOp.op));
3255 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003256 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003258 case IfExp_kind:
3259 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003260 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003262 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003264 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003265 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003266 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003267 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003268 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269 }
3270 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003271 case Set_kind:
3272 n = asdl_seq_LEN(e->v.Set.elts);
3273 VISIT_SEQ(c, expr, e->v.Set.elts);
3274 ADDOP_I(c, BUILD_SET, n);
3275 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003276 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003278 case ListComp_kind:
3279 return compiler_listcomp(c, e);
3280 case SetComp_kind:
3281 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003282 case DictComp_kind:
3283 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 case Yield_kind:
3285 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003286 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 if (e->v.Yield.value) {
3288 VISIT(c, expr, e->v.Yield.value);
3289 }
3290 else {
3291 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3292 }
3293 ADDOP(c, YIELD_VALUE);
3294 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003295 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003297 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003299 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3301 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003302 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3304 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003305 case Bytes_kind:
3306 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003307 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003308 case Ellipsis_kind:
3309 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3310 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003312 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313 if (e->v.Attribute.ctx != AugStore)
3314 VISIT(c, expr, e->v.Attribute.value);
3315 switch (e->v.Attribute.ctx) {
3316 case AugLoad:
3317 ADDOP(c, DUP_TOP);
3318 /* Fall through to load */
3319 case Load:
3320 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3321 break;
3322 case AugStore:
3323 ADDOP(c, ROT_TWO);
3324 /* Fall through to save */
3325 case Store:
3326 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3327 break;
3328 case Del:
3329 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3330 break;
3331 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003332 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003333 PyErr_SetString(PyExc_SystemError,
3334 "param invalid in attribute expression");
3335 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336 }
3337 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003338 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339 switch (e->v.Subscript.ctx) {
3340 case AugLoad:
3341 VISIT(c, expr, e->v.Subscript.value);
3342 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3343 break;
3344 case Load:
3345 VISIT(c, expr, e->v.Subscript.value);
3346 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3347 break;
3348 case AugStore:
3349 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3350 break;
3351 case Store:
3352 VISIT(c, expr, e->v.Subscript.value);
3353 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3354 break;
3355 case Del:
3356 VISIT(c, expr, e->v.Subscript.value);
3357 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3358 break;
3359 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003360 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003361 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003362 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364 }
3365 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003366 case Starred_kind:
3367 switch (e->v.Starred.ctx) {
3368 case Store:
3369 /* In all legitimate cases, the Starred node was already replaced
3370 * by compiler_list/compiler_tuple. XXX: is that okay? */
3371 return compiler_error(c,
3372 "starred assignment target must be in a list or tuple");
3373 default:
3374 return compiler_error(c,
3375 "can use starred expression only as assignment target");
3376 }
3377 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003378 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003379 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3380 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003381 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003383 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 return compiler_tuple(c, e);
3385 }
3386 return 1;
3387}
3388
3389static int
3390compiler_augassign(struct compiler *c, stmt_ty s)
3391{
3392 expr_ty e = s->v.AugAssign.target;
3393 expr_ty auge;
3394
3395 assert(s->kind == AugAssign_kind);
3396
3397 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003398 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003400 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003401 if (auge == NULL)
3402 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403 VISIT(c, expr, auge);
3404 VISIT(c, expr, s->v.AugAssign.value);
3405 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3406 auge->v.Attribute.ctx = AugStore;
3407 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408 break;
3409 case Subscript_kind:
3410 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003411 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003412 if (auge == NULL)
3413 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414 VISIT(c, expr, auge);
3415 VISIT(c, expr, s->v.AugAssign.value);
3416 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003417 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003418 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003419 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003421 if (!compiler_nameop(c, e->v.Name.id, Load))
3422 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423 VISIT(c, expr, s->v.AugAssign.value);
3424 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3425 return compiler_nameop(c, e->v.Name.id, Store);
3426 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003427 PyErr_Format(PyExc_SystemError,
3428 "invalid node type (%d) for augmented assignment",
3429 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003430 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431 }
3432 return 1;
3433}
3434
3435static int
3436compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3437{
3438 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003439 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3440 PyErr_SetString(PyExc_SystemError,
3441 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003443 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444 f = &c->u->u_fblock[c->u->u_nfblocks++];
3445 f->fb_type = t;
3446 f->fb_block = b;
3447 return 1;
3448}
3449
3450static void
3451compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3452{
3453 struct compiler_unit *u = c->u;
3454 assert(u->u_nfblocks > 0);
3455 u->u_nfblocks--;
3456 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3457 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3458}
3459
Thomas Wouters89f507f2006-12-13 04:49:30 +00003460static int
3461compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003462 int i;
3463 struct compiler_unit *u = c->u;
3464 for (i = 0; i < u->u_nfblocks; ++i) {
3465 if (u->u_fblock[i].fb_type == LOOP)
3466 return 1;
3467 }
3468 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003469}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003470/* Raises a SyntaxError and returns 0.
3471 If something goes wrong, a different exception may be raised.
3472*/
3473
3474static int
3475compiler_error(struct compiler *c, const char *errstr)
3476{
3477 PyObject *loc;
3478 PyObject *u = NULL, *v = NULL;
3479
3480 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3481 if (!loc) {
3482 Py_INCREF(Py_None);
3483 loc = Py_None;
3484 }
3485 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3486 Py_None, loc);
3487 if (!u)
3488 goto exit;
3489 v = Py_BuildValue("(zO)", errstr, u);
3490 if (!v)
3491 goto exit;
3492 PyErr_SetObject(PyExc_SyntaxError, v);
3493 exit:
3494 Py_DECREF(loc);
3495 Py_XDECREF(u);
3496 Py_XDECREF(v);
3497 return 0;
3498}
3499
3500static int
3501compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003502 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003504 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506 /* XXX this code is duplicated */
3507 switch (ctx) {
3508 case AugLoad: /* fall through to Load */
3509 case Load: op = BINARY_SUBSCR; break;
3510 case AugStore:/* fall through to Store */
3511 case Store: op = STORE_SUBSCR; break;
3512 case Del: op = DELETE_SUBSCR; break;
3513 case Param:
3514 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003515 "invalid %s kind %d in subscript\n",
3516 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003517 return 0;
3518 }
3519 if (ctx == AugLoad) {
3520 ADDOP_I(c, DUP_TOPX, 2);
3521 }
3522 else if (ctx == AugStore) {
3523 ADDOP(c, ROT_THREE);
3524 }
3525 ADDOP(c, op);
3526 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527}
3528
3529static int
3530compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3531{
3532 int n = 2;
3533 assert(s->kind == Slice_kind);
3534
3535 /* only handles the cases where BUILD_SLICE is emitted */
3536 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003537 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 }
3539 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003540 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003542
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003544 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 }
3546 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003547 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548 }
3549
3550 if (s->v.Slice.step) {
3551 n++;
3552 VISIT(c, expr, s->v.Slice.step);
3553 }
3554 ADDOP_I(c, BUILD_SLICE, n);
3555 return 1;
3556}
3557
3558static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3560 expr_context_ty ctx)
3561{
3562 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 case Slice_kind:
3564 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 case Index_kind:
3566 VISIT(c, expr, s->v.Index.value);
3567 break;
3568 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003569 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003570 PyErr_SetString(PyExc_SystemError,
3571 "extended slice invalid in nested slice");
3572 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 }
3574 return 1;
3575}
3576
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577static int
3578compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3579{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003580 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003582 case Index_kind:
3583 kindname = "index";
3584 if (ctx != AugStore) {
3585 VISIT(c, expr, s->v.Index.value);
3586 }
3587 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003589 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003590 if (ctx != AugStore) {
3591 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 return 0;
3593 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003594 break;
3595 case ExtSlice_kind:
3596 kindname = "extended slice";
3597 if (ctx != AugStore) {
3598 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3599 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003600 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003601 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003602 if (!compiler_visit_nested_slice(c, sub, ctx))
3603 return 0;
3604 }
3605 ADDOP_I(c, BUILD_TUPLE, n);
3606 }
3607 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003608 default:
3609 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003610 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003611 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003613 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614}
3615
Thomas Wouters89f507f2006-12-13 04:49:30 +00003616/* End of the compiler section, beginning of the assembler section */
3617
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618/* do depth-first search of basic block graph, starting with block.
3619 post records the block indices in post-order.
3620
3621 XXX must handle implicit jumps from one block to next
3622*/
3623
Thomas Wouters89f507f2006-12-13 04:49:30 +00003624struct assembler {
3625 PyObject *a_bytecode; /* string containing bytecode */
3626 int a_offset; /* offset into bytecode */
3627 int a_nblocks; /* number of reachable blocks */
3628 basicblock **a_postorder; /* list of blocks in dfs postorder */
3629 PyObject *a_lnotab; /* string containing lnotab */
3630 int a_lnotab_off; /* offset into lnotab */
3631 int a_lineno; /* last lineno of emitted instruction */
3632 int a_lineno_off; /* bytecode offset of last lineno */
3633};
3634
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635static void
3636dfs(struct compiler *c, basicblock *b, struct assembler *a)
3637{
3638 int i;
3639 struct instr *instr = NULL;
3640
3641 if (b->b_seen)
3642 return;
3643 b->b_seen = 1;
3644 if (b->b_next != NULL)
3645 dfs(c, b->b_next, a);
3646 for (i = 0; i < b->b_iused; i++) {
3647 instr = &b->b_instr[i];
3648 if (instr->i_jrel || instr->i_jabs)
3649 dfs(c, instr->i_target, a);
3650 }
3651 a->a_postorder[a->a_nblocks++] = b;
3652}
3653
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003654static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3656{
3657 int i;
3658 struct instr *instr;
3659 if (b->b_seen || b->b_startdepth >= depth)
3660 return maxdepth;
3661 b->b_seen = 1;
3662 b->b_startdepth = depth;
3663 for (i = 0; i < b->b_iused; i++) {
3664 instr = &b->b_instr[i];
3665 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3666 if (depth > maxdepth)
3667 maxdepth = depth;
3668 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3669 if (instr->i_jrel || instr->i_jabs) {
3670 maxdepth = stackdepth_walk(c, instr->i_target,
3671 depth, maxdepth);
3672 if (instr->i_opcode == JUMP_ABSOLUTE ||
3673 instr->i_opcode == JUMP_FORWARD) {
3674 goto out; /* remaining code is dead */
3675 }
3676 }
3677 }
3678 if (b->b_next)
3679 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3680out:
3681 b->b_seen = 0;
3682 return maxdepth;
3683}
3684
3685/* Find the flow path that needs the largest stack. We assume that
3686 * cycles in the flow graph have no net effect on the stack depth.
3687 */
3688static int
3689stackdepth(struct compiler *c)
3690{
3691 basicblock *b, *entryblock;
3692 entryblock = NULL;
3693 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3694 b->b_seen = 0;
3695 b->b_startdepth = INT_MIN;
3696 entryblock = b;
3697 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003698 if (!entryblock)
3699 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700 return stackdepth_walk(c, entryblock, 0, 0);
3701}
3702
3703static int
3704assemble_init(struct assembler *a, int nblocks, int firstlineno)
3705{
3706 memset(a, 0, sizeof(struct assembler));
3707 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003708 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709 if (!a->a_bytecode)
3710 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003711 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003712 if (!a->a_lnotab)
3713 return 0;
3714 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003715 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003716 if (!a->a_postorder) {
3717 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003719 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720 return 1;
3721}
3722
3723static void
3724assemble_free(struct assembler *a)
3725{
3726 Py_XDECREF(a->a_bytecode);
3727 Py_XDECREF(a->a_lnotab);
3728 if (a->a_postorder)
3729 PyObject_Free(a->a_postorder);
3730}
3731
3732/* Return the size of a basic block in bytes. */
3733
3734static int
3735instrsize(struct instr *instr)
3736{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003737 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003738 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003739 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003740 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3741 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742}
3743
3744static int
3745blocksize(basicblock *b)
3746{
3747 int i;
3748 int size = 0;
3749
3750 for (i = 0; i < b->b_iused; i++)
3751 size += instrsize(&b->b_instr[i]);
3752 return size;
3753}
3754
3755/* All about a_lnotab.
3756
3757c_lnotab is an array of unsigned bytes disguised as a Python string.
3758It is used to map bytecode offsets to source code line #s (when needed
3759for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003760
Tim Peters2a7f3842001-06-09 09:26:21 +00003761The array is conceptually a list of
3762 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003763pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003764
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003765 byte code offset source code line number
3766 0 1
3767 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003768 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003769 350 307
3770 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003771
3772The first trick is that these numbers aren't stored, only the increments
3773from one row to the next (this doesn't really work, but it's a start):
3774
3775 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3776
3777The second trick is that an unsigned byte can't hold negative values, or
3778values larger than 255, so (a) there's a deep assumption that byte code
3779offsets and their corresponding line #s both increase monotonically, and (b)
3780if at least one column jumps by more than 255 from one row to the next, more
3781than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003782from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003783part. A user of c_lnotab desiring to find the source line number
3784corresponding to a bytecode address A should do something like this
3785
3786 lineno = addr = 0
3787 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003788 addr += addr_incr
3789 if addr > A:
3790 return lineno
3791 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003792
3793In order for this to work, when the addr field increments by more than 255,
3794the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003795increment is < 256. So, in the example above, assemble_lnotab (it used
3796to be called com_set_lineno) should not (as was actually done until 2.2)
3797expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003798 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003799*/
3800
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003801static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003803{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 int d_bytecode, d_lineno;
3805 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003806 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807
3808 d_bytecode = a->a_offset - a->a_lineno_off;
3809 d_lineno = i->i_lineno - a->a_lineno;
3810
3811 assert(d_bytecode >= 0);
3812 assert(d_lineno >= 0);
3813
Christian Heimes2202f872008-02-06 14:31:34 +00003814 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003815 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003816
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003818 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003820 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003821 if (nbytes >= len) {
3822 if (len * 2 < nbytes)
3823 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003824 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 len *= 2;
Christian Heimes72b710a2008-05-26 13:28:38 +00003826 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003828 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003829 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003830 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003831 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832 *lnotab++ = 255;
3833 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003834 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 d_bytecode -= ncodes * 255;
3836 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838 assert(d_bytecode <= 255);
3839 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003840 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003842 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 if (nbytes >= len) {
3844 if (len * 2 < nbytes)
3845 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003846 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847 len *= 2;
Christian Heimes72b710a2008-05-26 13:28:38 +00003848 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003850 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003851 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003852 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003854 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003856 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003858 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003859 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003860 d_lineno -= ncodes * 255;
3861 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003862 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003863
Christian Heimes72b710a2008-05-26 13:28:38 +00003864 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003866 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003867 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003868 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003869 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003870 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003871
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872 a->a_lnotab_off += 2;
3873 if (d_bytecode) {
3874 *lnotab++ = d_bytecode;
3875 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003876 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003877 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 *lnotab++ = 0;
3879 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003880 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 a->a_lineno = i->i_lineno;
3882 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003883 return 1;
3884}
3885
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886/* assemble_emit()
3887 Extend the bytecode with a new instruction.
3888 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003889*/
3890
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003891static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003892assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003893{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003894 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003895 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003896 char *code;
3897
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003898 size = instrsize(i);
3899 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003901 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003902 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003904 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 if (a->a_offset + size >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003906 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003907 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003908 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003909 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003911 if (size == 6) {
3912 assert(i->i_hasarg);
3913 *code++ = (char)EXTENDED_ARG;
3914 *code++ = ext & 0xff;
3915 *code++ = ext >> 8;
3916 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003917 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003919 if (i->i_hasarg) {
3920 assert(size == 3 || size == 6);
3921 *code++ = arg & 0xff;
3922 *code++ = arg >> 8;
3923 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003924 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003925}
3926
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003927static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003928assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003929{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003931 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003932 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934 /* Compute the size of each block and fixup jump args.
3935 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003936start:
3937 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003939 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940 bsize = blocksize(b);
3941 b->b_offset = totsize;
3942 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003943 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003944 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3946 bsize = b->b_offset;
3947 for (i = 0; i < b->b_iused; i++) {
3948 struct instr *instr = &b->b_instr[i];
3949 /* Relative jumps are computed relative to
3950 the instruction pointer after fetching
3951 the jump instruction.
3952 */
3953 bsize += instrsize(instr);
3954 if (instr->i_jabs)
3955 instr->i_oparg = instr->i_target->b_offset;
3956 else if (instr->i_jrel) {
3957 int delta = instr->i_target->b_offset - bsize;
3958 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003959 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003960 else
3961 continue;
3962 if (instr->i_oparg > 0xffff)
3963 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003964 }
3965 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003966
3967 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003968 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003969 with a better solution.
3970
3971 In the meantime, should the goto be dropped in favor
3972 of a loop?
3973
3974 The issue is that in the first loop blocksize() is called
3975 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003976 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003977 i_oparg is calculated in the second loop above.
3978
3979 So we loop until we stop seeing new EXTENDED_ARGs.
3980 The only EXTENDED_ARGs that could be popping up are
3981 ones in jump instructions. So this should converge
3982 fairly quickly.
3983 */
3984 if (last_extended_arg_count != extended_arg_count) {
3985 last_extended_arg_count = extended_arg_count;
3986 goto start;
3987 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003988}
3989
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003990static PyObject *
3991dict_keys_inorder(PyObject *dict, int offset)
3992{
3993 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003994 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003995
3996 tuple = PyTuple_New(size);
3997 if (tuple == NULL)
3998 return NULL;
3999 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00004000 i = PyLong_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004001 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004002 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004003 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004004 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004005 PyTuple_SET_ITEM(tuple, i - offset, k);
4006 }
4007 return tuple;
4008}
4009
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004010static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004011compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004012{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004013 PySTEntryObject *ste = c->u->u_ste;
4014 int flags = 0, n;
4015 if (ste->ste_type != ModuleBlock)
4016 flags |= CO_NEWLOCALS;
4017 if (ste->ste_type == FunctionBlock) {
4018 if (!ste->ste_unoptimized)
4019 flags |= CO_OPTIMIZED;
4020 if (ste->ste_nested)
4021 flags |= CO_NESTED;
4022 if (ste->ste_generator)
4023 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004024 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025 if (ste->ste_varargs)
4026 flags |= CO_VARARGS;
4027 if (ste->ste_varkeywords)
4028 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004029 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004031
4032 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004033 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004035 n = PyDict_Size(c->u->u_freevars);
4036 if (n < 0)
4037 return -1;
4038 if (n == 0) {
4039 n = PyDict_Size(c->u->u_cellvars);
4040 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004041 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004042 if (n == 0) {
4043 flags |= CO_NOFREE;
4044 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004045 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004046
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004047 return flags;
4048}
4049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004050static PyCodeObject *
4051makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004052{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004053 PyObject *tmp;
4054 PyCodeObject *co = NULL;
4055 PyObject *consts = NULL;
4056 PyObject *names = NULL;
4057 PyObject *varnames = NULL;
4058 PyObject *filename = NULL;
4059 PyObject *name = NULL;
4060 PyObject *freevars = NULL;
4061 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004062 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065 tmp = dict_keys_inorder(c->u->u_consts, 0);
4066 if (!tmp)
4067 goto error;
4068 consts = PySequence_List(tmp); /* optimize_code requires a list */
4069 Py_DECREF(tmp);
4070
4071 names = dict_keys_inorder(c->u->u_names, 0);
4072 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4073 if (!consts || !names || !varnames)
4074 goto error;
4075
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004076 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4077 if (!cellvars)
4078 goto error;
4079 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4080 if (!freevars)
4081 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004082 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083 if (!filename)
4084 goto error;
4085
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004086 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004087 flags = compute_code_flags(c);
4088 if (flags < 0)
4089 goto error;
4090
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004091 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004092 if (!bytecode)
4093 goto error;
4094
4095 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4096 if (!tmp)
4097 goto error;
4098 Py_DECREF(consts);
4099 consts = tmp;
4100
Guido van Rossum4f72a782006-10-27 23:31:49 +00004101 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4102 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103 bytecode, consts, names, varnames,
4104 freevars, cellvars,
4105 filename, c->u->u_name,
4106 c->u->u_firstlineno,
4107 a->a_lnotab);
4108 error:
4109 Py_XDECREF(consts);
4110 Py_XDECREF(names);
4111 Py_XDECREF(varnames);
4112 Py_XDECREF(filename);
4113 Py_XDECREF(name);
4114 Py_XDECREF(freevars);
4115 Py_XDECREF(cellvars);
4116 Py_XDECREF(bytecode);
4117 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004118}
4119
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004120
4121/* For debugging purposes only */
4122#if 0
4123static void
4124dump_instr(const struct instr *i)
4125{
4126 const char *jrel = i->i_jrel ? "jrel " : "";
4127 const char *jabs = i->i_jabs ? "jabs " : "";
4128 char arg[128];
4129
4130 *arg = '\0';
4131 if (i->i_hasarg)
4132 sprintf(arg, "arg: %d ", i->i_oparg);
4133
4134 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4135 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4136}
4137
4138static void
4139dump_basicblock(const basicblock *b)
4140{
4141 const char *seen = b->b_seen ? "seen " : "";
4142 const char *b_return = b->b_return ? "return " : "";
4143 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4144 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4145 if (b->b_instr) {
4146 int i;
4147 for (i = 0; i < b->b_iused; i++) {
4148 fprintf(stderr, " [%02d] ", i);
4149 dump_instr(b->b_instr + i);
4150 }
4151 }
4152}
4153#endif
4154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004155static PyCodeObject *
4156assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004157{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158 basicblock *b, *entryblock;
4159 struct assembler a;
4160 int i, j, nblocks;
4161 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004162
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004163 /* Make sure every block that falls off the end returns None.
4164 XXX NEXT_BLOCK() isn't quite right, because if the last
4165 block ends with a jump or return b_next shouldn't set.
4166 */
4167 if (!c->u->u_curblock->b_return) {
4168 NEXT_BLOCK(c);
4169 if (addNone)
4170 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4171 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004172 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004173
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004174 nblocks = 0;
4175 entryblock = NULL;
4176 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4177 nblocks++;
4178 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004179 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004180
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004181 /* Set firstlineno if it wasn't explicitly set. */
4182 if (!c->u->u_firstlineno) {
4183 if (entryblock && entryblock->b_instr)
4184 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4185 else
4186 c->u->u_firstlineno = 1;
4187 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004188 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4189 goto error;
4190 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004192 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004193 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195 /* Emit code in reverse postorder from dfs. */
4196 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004197 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198 for (j = 0; j < b->b_iused; j++)
4199 if (!assemble_emit(&a, &b->b_instr[j]))
4200 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004201 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004202
Christian Heimes72b710a2008-05-26 13:28:38 +00004203 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004205 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004207
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208 co = makecode(c, &a);
4209 error:
4210 assemble_free(&a);
4211 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004212}