blob: 36f8c13d527fc2076a39e254bb9f7c4f0ee12847 [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);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000230
231 assert(1 <= PY_SSIZE_T_MAX - nlen);
232 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
233
Martin v. Löwis5b222132007-06-10 09:51:05 +0000234 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 if (!ident)
236 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000238 buffer = PyUnicode_AS_UNICODE(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000239 buffer[0] = '_';
Martin v. Löwis5b222132007-06-10 09:51:05 +0000240 Py_UNICODE_strncpy(buffer+1, p, plen);
241 Py_UNICODE_strcpy(buffer+1+plen, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000243}
244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245static int
246compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000247{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000248 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250 c->c_stack = PyList_New(0);
251 if (!c->c_stack)
252 return 0;
253
254 return 1;
255}
256
257PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000258PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000259 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260{
261 struct compiler c;
262 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000263 PyCompilerFlags local_flags;
264 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000266 if (!__doc__) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000267 __doc__ = PyUnicode_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000268 if (!__doc__)
269 return NULL;
270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271
272 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000273 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000274 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000275 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000276 c.c_future = PyFuture_FromAST(mod, filename);
277 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000278 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000280 local_flags.cf_flags = 0;
281 flags = &local_flags;
282 }
283 merged = c.c_future->ff_features | flags->cf_flags;
284 c.c_future->ff_features = merged;
285 flags->cf_flags = merged;
286 c.c_flags = flags;
287 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288
289 c.c_st = PySymtable_Build(mod, filename, c.c_future);
290 if (c.c_st == NULL) {
291 if (!PyErr_Occurred())
292 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 }
295
296 /* XXX initialize to NULL for now, need to handle */
297 c.c_encoding = NULL;
298
299 co = compiler_mod(&c, mod);
300
Thomas Wouters1175c432006-02-27 22:49:54 +0000301 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000303 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304 return co;
305}
306
307PyCodeObject *
308PyNode_Compile(struct _node *n, const char *filename)
309{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000310 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000311 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000312 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000313 if (!arena)
314 return NULL;
315 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000316 if (mod)
317 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000318 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000319 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000320}
321
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000324{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 if (c->c_st)
326 PySymtable_Free(c->c_st);
327 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000330}
331
Guido van Rossum79f25d91997-04-29 20:08:16 +0000332static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000334{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000335 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000336 PyObject *v, *k;
337 PyObject *dict = PyDict_New();
338 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340 n = PyList_Size(list);
341 for (i = 0; i < n; i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000342 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 if (!v) {
344 Py_DECREF(dict);
345 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000347 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000348 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
350 Py_XDECREF(k);
351 Py_DECREF(v);
352 Py_DECREF(dict);
353 return NULL;
354 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000355 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000357 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 return dict;
359}
360
361/* Return new dict containing names from src that match scope(s).
362
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000363src is a symbol table dictionary. If the scope of a name matches
364either scope_type or flag is set, insert it into the new dict. The
365values are integers, starting at offset and increasing by one for
366each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367*/
368
369static PyObject *
370dictbytype(PyObject *src, int scope_type, int flag, int offset)
371{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000372 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000373 PyObject *k, *v, *dest = PyDict_New();
374
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000375 assert(offset >= 0);
376 if (dest == NULL)
377 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378
379 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000380 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000381 long vi;
Christian Heimes217cfd12007-12-02 14:31:20 +0000382 assert(PyLong_Check(v));
383 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000384 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000386 if (scope == scope_type || vi & flag) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000387 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 if (item == NULL) {
389 Py_DECREF(dest);
390 return NULL;
391 }
392 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000393 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000394 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
395 Py_DECREF(item);
396 Py_DECREF(dest);
397 Py_XDECREF(tuple);
398 return NULL;
399 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000401 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403 }
404 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000405}
406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407static void
408compiler_unit_check(struct compiler_unit *u)
409{
410 basicblock *block;
411 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Christian Heimes77c02eb2008-02-09 02:18:51 +0000412 assert((void *)block != (void *)0xcbcbcbcb);
413 assert((void *)block != (void *)0xfbfbfbfb);
414 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415 if (block->b_instr != NULL) {
416 assert(block->b_ialloc > 0);
417 assert(block->b_iused > 0);
418 assert(block->b_ialloc >= block->b_iused);
419 }
420 else {
421 assert (block->b_iused == 0);
422 assert (block->b_ialloc == 0);
423 }
424 }
425}
426
427static void
428compiler_unit_free(struct compiler_unit *u)
429{
430 basicblock *b, *next;
431
432 compiler_unit_check(u);
433 b = u->u_blocks;
434 while (b != NULL) {
435 if (b->b_instr)
436 PyObject_Free((void *)b->b_instr);
437 next = b->b_list;
438 PyObject_Free((void *)b);
439 b = next;
440 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000441 Py_CLEAR(u->u_ste);
442 Py_CLEAR(u->u_name);
443 Py_CLEAR(u->u_consts);
444 Py_CLEAR(u->u_names);
445 Py_CLEAR(u->u_varnames);
446 Py_CLEAR(u->u_freevars);
447 Py_CLEAR(u->u_cellvars);
448 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449 PyObject_Free(u);
450}
451
452static int
453compiler_enter_scope(struct compiler *c, identifier name, void *key,
454 int lineno)
455{
456 struct compiler_unit *u;
457
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000459 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000460 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 PyErr_NoMemory();
462 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000463 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000465 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000466 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 u->u_ste = PySymtable_Lookup(c->c_st, key);
468 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000469 compiler_unit_free(u);
470 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471 }
472 Py_INCREF(name);
473 u->u_name = name;
474 u->u_varnames = list2dict(u->u_ste->ste_varnames);
475 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000476 if (!u->u_varnames || !u->u_cellvars) {
477 compiler_unit_free(u);
478 return 0;
479 }
480
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000482 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000483 if (!u->u_freevars) {
484 compiler_unit_free(u);
485 return 0;
486 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487
488 u->u_blocks = NULL;
489 u->u_tmpname = 0;
490 u->u_nfblocks = 0;
491 u->u_firstlineno = lineno;
492 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000493 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000494 u->u_consts = PyDict_New();
495 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000496 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497 return 0;
498 }
499 u->u_names = PyDict_New();
500 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000501 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502 return 0;
503 }
504
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000505 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000506
507 /* Push the old compiler_unit on the stack. */
508 if (c->u) {
509 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000510 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
511 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513 return 0;
514 }
515 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000516 u->u_private = c->u->u_private;
517 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518 }
519 c->u = u;
520
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000521 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000522 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523 return 0;
524
525 return 1;
526}
527
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000528static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529compiler_exit_scope(struct compiler *c)
530{
531 int n;
532 PyObject *wrapper;
533
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000534 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535 compiler_unit_free(c->u);
536 /* Restore c->u to the parent unit. */
537 n = PyList_GET_SIZE(c->c_stack) - 1;
538 if (n >= 0) {
539 wrapper = PyList_GET_ITEM(c->c_stack, n);
540 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000541 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000542 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000544 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545 compiler_unit_check(c->u);
546 }
547 else
548 c->u = NULL;
549
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550}
551
Guido van Rossumc2e20742006-02-27 22:32:47 +0000552/* Allocate a new "anonymous" local variable.
553 Used by list comprehensions and with statements.
554*/
555
556static PyObject *
557compiler_new_tmpname(struct compiler *c)
558{
559 char tmpname[256];
560 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000561 return PyUnicode_FromString(tmpname);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000562}
563
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564/* Allocate a new block and return a pointer to it.
565 Returns NULL on error.
566*/
567
568static basicblock *
569compiler_new_block(struct compiler *c)
570{
571 basicblock *b;
572 struct compiler_unit *u;
573
574 u = c->u;
575 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000576 if (b == NULL) {
577 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582 b->b_list = u->u_blocks;
583 u->u_blocks = b;
584 return b;
585}
586
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587static basicblock *
588compiler_use_new_block(struct compiler *c)
589{
590 basicblock *block = compiler_new_block(c);
591 if (block == NULL)
592 return NULL;
593 c->u->u_curblock = block;
594 return block;
595}
596
597static basicblock *
598compiler_next_block(struct compiler *c)
599{
600 basicblock *block = compiler_new_block(c);
601 if (block == NULL)
602 return NULL;
603 c->u->u_curblock->b_next = block;
604 c->u->u_curblock = block;
605 return block;
606}
607
608static basicblock *
609compiler_use_next_block(struct compiler *c, basicblock *block)
610{
611 assert(block != NULL);
612 c->u->u_curblock->b_next = block;
613 c->u->u_curblock = block;
614 return block;
615}
616
617/* Returns the offset of the next instruction in the current block's
618 b_instr array. Resizes the b_instr as necessary.
619 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000620*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
622static int
623compiler_next_instr(struct compiler *c, basicblock *b)
624{
625 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000626 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000628 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629 if (b->b_instr == NULL) {
630 PyErr_NoMemory();
631 return -1;
632 }
633 b->b_ialloc = DEFAULT_BLOCK_SIZE;
634 memset((char *)b->b_instr, 0,
635 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000636 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639 size_t oldsize, newsize;
640 oldsize = b->b_ialloc * sizeof(struct instr);
641 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000642
643 if (oldsize > (PY_SIZE_MAX >> 1)) {
644 PyErr_NoMemory();
645 return -1;
646 }
647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648 if (newsize == 0) {
649 PyErr_NoMemory();
650 return -1;
651 }
652 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655 if (tmp == NULL) {
656 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658 }
659 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
661 }
662 return b->b_iused++;
663}
664
Christian Heimes2202f872008-02-06 14:31:34 +0000665/* Set the i_lineno member of the instruction at offset off if the
666 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000667 already been set. If it has been set, the call has no effect.
668
Christian Heimes2202f872008-02-06 14:31:34 +0000669 The line number is reset in the following cases:
670 - when entering a new scope
671 - on each statement
672 - on each expression that start a new line
673 - before the "except" clause
674 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677static void
678compiler_set_lineno(struct compiler *c, int off)
679{
680 basicblock *b;
681 if (c->u->u_lineno_set)
682 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000683 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000685 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686}
687
688static int
689opcode_stack_effect(int opcode, int oparg)
690{
691 switch (opcode) {
692 case POP_TOP:
693 return -1;
694 case ROT_TWO:
695 case ROT_THREE:
696 return 0;
697 case DUP_TOP:
698 return 1;
699 case ROT_FOUR:
700 return 0;
701
702 case UNARY_POSITIVE:
703 case UNARY_NEGATIVE:
704 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705 case UNARY_INVERT:
706 return 0;
707
Nick Coghlan650f0d02007-04-15 12:05:43 +0000708 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000709 case LIST_APPEND:
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000710 return -1;
711 case MAP_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000712 return -2;
713
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714 case BINARY_POWER:
715 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716 case BINARY_MODULO:
717 case BINARY_ADD:
718 case BINARY_SUBTRACT:
719 case BINARY_SUBSCR:
720 case BINARY_FLOOR_DIVIDE:
721 case BINARY_TRUE_DIVIDE:
722 return -1;
723 case INPLACE_FLOOR_DIVIDE:
724 case INPLACE_TRUE_DIVIDE:
725 return -1;
726
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000727 case INPLACE_ADD:
728 case INPLACE_SUBTRACT:
729 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 case INPLACE_MODULO:
731 return -1;
732 case STORE_SUBSCR:
733 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000734 case STORE_MAP:
735 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736 case DELETE_SUBSCR:
737 return -2;
738
739 case BINARY_LSHIFT:
740 case BINARY_RSHIFT:
741 case BINARY_AND:
742 case BINARY_XOR:
743 case BINARY_OR:
744 return -1;
745 case INPLACE_POWER:
746 return -1;
747 case GET_ITER:
748 return 0;
749
750 case PRINT_EXPR:
751 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000752 case LOAD_BUILD_CLASS:
753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754 case INPLACE_LSHIFT:
755 case INPLACE_RSHIFT:
756 case INPLACE_AND:
757 case INPLACE_XOR:
758 case INPLACE_OR:
759 return -1;
760 case BREAK_LOOP:
761 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000762 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000763 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000764 case STORE_LOCALS:
765 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766 case RETURN_VALUE:
767 return -1;
768 case IMPORT_STAR:
769 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770 case YIELD_VALUE:
771 return 0;
772
773 case POP_BLOCK:
774 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000775 case POP_EXCEPT:
776 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777 case END_FINALLY:
778 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779
780 case STORE_NAME:
781 return -1;
782 case DELETE_NAME:
783 return 0;
784 case UNPACK_SEQUENCE:
785 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000786 case UNPACK_EX:
787 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788 case FOR_ITER:
789 return 1;
790
791 case STORE_ATTR:
792 return -2;
793 case DELETE_ATTR:
794 return -1;
795 case STORE_GLOBAL:
796 return -1;
797 case DELETE_GLOBAL:
798 return 0;
799 case DUP_TOPX:
800 return oparg;
801 case LOAD_CONST:
802 return 1;
803 case LOAD_NAME:
804 return 1;
805 case BUILD_TUPLE:
806 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000807 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808 return 1-oparg;
809 case BUILD_MAP:
810 return 1;
811 case LOAD_ATTR:
812 return 0;
813 case COMPARE_OP:
814 return -1;
815 case IMPORT_NAME:
816 return 0;
817 case IMPORT_FROM:
818 return 1;
819
820 case JUMP_FORWARD:
821 case JUMP_IF_FALSE:
822 case JUMP_IF_TRUE:
823 case JUMP_ABSOLUTE:
824 return 0;
825
826 case LOAD_GLOBAL:
827 return 1;
828
829 case CONTINUE_LOOP:
830 return 0;
831 case SETUP_LOOP:
832 return 0;
833 case SETUP_EXCEPT:
834 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000835 return 6; /* can push 3 values for the new exception
836 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837
838 case LOAD_FAST:
839 return 1;
840 case STORE_FAST:
841 return -1;
842 case DELETE_FAST:
843 return 0;
844
845 case RAISE_VARARGS:
846 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000847#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848 case CALL_FUNCTION:
849 return -NARGS(oparg);
850 case CALL_FUNCTION_VAR:
851 case CALL_FUNCTION_KW:
852 return -NARGS(oparg)-1;
853 case CALL_FUNCTION_VAR_KW:
854 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000856 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000857 case MAKE_CLOSURE:
858 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000859#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860 case BUILD_SLICE:
861 if (oparg == 3)
862 return -2;
863 else
864 return -1;
865
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000866 case LOAD_CLOSURE:
867 return 1;
868 case LOAD_DEREF:
869 return 1;
870 case STORE_DEREF:
871 return -1;
872 default:
873 fprintf(stderr, "opcode = %d\n", opcode);
874 Py_FatalError("opcode_stack_effect()");
875
876 }
877 return 0; /* not reachable */
878}
879
880/* Add an opcode with no argument.
881 Returns 0 on failure, 1 on success.
882*/
883
884static int
885compiler_addop(struct compiler *c, int opcode)
886{
887 basicblock *b;
888 struct instr *i;
889 int off;
890 off = compiler_next_instr(c, c->u->u_curblock);
891 if (off < 0)
892 return 0;
893 b = c->u->u_curblock;
894 i = &b->b_instr[off];
895 i->i_opcode = opcode;
896 i->i_hasarg = 0;
897 if (opcode == RETURN_VALUE)
898 b->b_return = 1;
899 compiler_set_lineno(c, off);
900 return 1;
901}
902
903static int
904compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
905{
906 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000907 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000908 unsigned char *p, *q;
909 Py_complex z;
910 double d;
911 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000913 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000914 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
915 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000916 d = PyFloat_AS_DOUBLE(o);
917 p = (unsigned char*) &d;
918 /* all we need is to make the tuple different in either the 0.0
919 * or -0.0 case from all others, just to avoid the "coercion".
920 */
921 if (*p==0 && p[sizeof(double)-1]==0)
922 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
923 else
924 t = PyTuple_Pack(2, o, o->ob_type);
925 }
926 else if (PyComplex_Check(o)) {
927 /* complex case is even messier: we need to make complex(x,
928 0.) different from complex(x, -0.) and complex(0., y)
929 different from complex(-0., y), for any x and y. In
930 particular, all four complex zeros should be
931 distinguished.*/
932 z = PyComplex_AsCComplex(o);
933 p = (unsigned char*) &(z.real);
934 q = (unsigned char*) &(z.imag);
935 /* all that matters here is that on IEEE platforms
936 real_part_zero will be true if z.real == 0., and false if
937 z.real == -0. In fact, real_part_zero will also be true
938 for some other rarely occurring nonzero floats, but this
939 doesn't matter. Similar comments apply to
940 imag_part_zero. */
941 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
942 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
943 if (real_part_zero && imag_part_zero) {
944 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
945 }
946 else if (real_part_zero && !imag_part_zero) {
947 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
948 }
949 else if (!real_part_zero && imag_part_zero) {
950 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
951 }
952 else {
953 t = PyTuple_Pack(2, o, o->ob_type);
954 }
955 }
956 else {
957 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000958 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000959 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000960 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961
962 v = PyDict_GetItem(dict, t);
963 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000964 if (PyErr_Occurred())
965 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000966 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000967 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 if (!v) {
969 Py_DECREF(t);
970 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000971 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 if (PyDict_SetItem(dict, t, v) < 0) {
973 Py_DECREF(t);
974 Py_DECREF(v);
975 return -1;
976 }
977 Py_DECREF(v);
978 }
979 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000980 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983}
984
985static int
986compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
987 PyObject *o)
988{
989 int arg = compiler_add_o(c, dict, o);
990 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992 return compiler_addop_i(c, opcode, arg);
993}
994
995static int
996compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000997 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998{
999 int arg;
1000 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1001 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 arg = compiler_add_o(c, dict, mangled);
1004 Py_DECREF(mangled);
1005 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007 return compiler_addop_i(c, opcode, arg);
1008}
1009
1010/* Add an opcode with an integer argument.
1011 Returns 0 on failure, 1 on success.
1012*/
1013
1014static int
1015compiler_addop_i(struct compiler *c, int opcode, int oparg)
1016{
1017 struct instr *i;
1018 int off;
1019 off = compiler_next_instr(c, c->u->u_curblock);
1020 if (off < 0)
1021 return 0;
1022 i = &c->u->u_curblock->b_instr[off];
1023 i->i_opcode = opcode;
1024 i->i_oparg = oparg;
1025 i->i_hasarg = 1;
1026 compiler_set_lineno(c, off);
1027 return 1;
1028}
1029
1030static int
1031compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1032{
1033 struct instr *i;
1034 int off;
1035
1036 assert(b != NULL);
1037 off = compiler_next_instr(c, c->u->u_curblock);
1038 if (off < 0)
1039 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040 i = &c->u->u_curblock->b_instr[off];
1041 i->i_opcode = opcode;
1042 i->i_target = b;
1043 i->i_hasarg = 1;
1044 if (absolute)
1045 i->i_jabs = 1;
1046 else
1047 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001048 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049 return 1;
1050}
1051
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001052/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1053 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054 it as the current block. NEXT_BLOCK() also creates an implicit jump
1055 from the current block to the new block.
1056*/
1057
Thomas Wouters89f507f2006-12-13 04:49:30 +00001058/* The returns inside these macros make it impossible to decref objects
1059 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060*/
1061
1062
1063#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001064 if (compiler_use_new_block((C)) == NULL) \
1065 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066}
1067
1068#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001069 if (compiler_next_block((C)) == NULL) \
1070 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071}
1072
1073#define ADDOP(C, OP) { \
1074 if (!compiler_addop((C), (OP))) \
1075 return 0; \
1076}
1077
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001078#define ADDOP_IN_SCOPE(C, OP) { \
1079 if (!compiler_addop((C), (OP))) { \
1080 compiler_exit_scope(c); \
1081 return 0; \
1082 } \
1083}
1084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085#define ADDOP_O(C, OP, O, TYPE) { \
1086 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1087 return 0; \
1088}
1089
1090#define ADDOP_NAME(C, OP, O, TYPE) { \
1091 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1092 return 0; \
1093}
1094
1095#define ADDOP_I(C, OP, O) { \
1096 if (!compiler_addop_i((C), (OP), (O))) \
1097 return 0; \
1098}
1099
1100#define ADDOP_JABS(C, OP, O) { \
1101 if (!compiler_addop_j((C), (OP), (O), 1)) \
1102 return 0; \
1103}
1104
1105#define ADDOP_JREL(C, OP, O) { \
1106 if (!compiler_addop_j((C), (OP), (O), 0)) \
1107 return 0; \
1108}
1109
1110/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1111 the ASDL name to synthesize the name of the C type and the visit function.
1112*/
1113
1114#define VISIT(C, TYPE, V) {\
1115 if (!compiler_visit_ ## TYPE((C), (V))) \
1116 return 0; \
1117}
1118
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001119#define VISIT_IN_SCOPE(C, TYPE, V) {\
1120 if (!compiler_visit_ ## TYPE((C), (V))) { \
1121 compiler_exit_scope(c); \
1122 return 0; \
1123 } \
1124}
1125
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126#define VISIT_SLICE(C, V, CTX) {\
1127 if (!compiler_visit_slice((C), (V), (CTX))) \
1128 return 0; \
1129}
1130
1131#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001134 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001135 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136 if (!compiler_visit_ ## TYPE((C), elt)) \
1137 return 0; \
1138 } \
1139}
1140
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001141#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001143 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001144 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001145 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001146 if (!compiler_visit_ ## TYPE((C), elt)) { \
1147 compiler_exit_scope(c); \
1148 return 0; \
1149 } \
1150 } \
1151}
1152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153static int
1154compiler_isdocstring(stmt_ty s)
1155{
1156 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001157 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 return s->v.Expr.value->kind == Str_kind;
1159}
1160
1161/* Compile a sequence of statements, checking for a docstring. */
1162
1163static int
1164compiler_body(struct compiler *c, asdl_seq *stmts)
1165{
1166 int i = 0;
1167 stmt_ty st;
1168
1169 if (!asdl_seq_LEN(stmts))
1170 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001171 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001172 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1173 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 i = 1;
1175 VISIT(c, expr, st->v.Expr.value);
1176 if (!compiler_nameop(c, __doc__, Store))
1177 return 0;
1178 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001179 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181 return 1;
1182}
1183
1184static PyCodeObject *
1185compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001186{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001187 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001188 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 static PyObject *module;
1190 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001191 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192 if (!module)
1193 return NULL;
1194 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001195 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1196 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001197 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 switch (mod->kind) {
1199 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001200 if (!compiler_body(c, mod->v.Module.body)) {
1201 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 break;
1205 case Interactive_kind:
1206 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001207 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001208 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 break;
1210 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001211 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001212 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 break;
1214 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001215 PyErr_SetString(PyExc_SystemError,
1216 "suite should not be possible");
1217 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001218 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001219 PyErr_Format(PyExc_SystemError,
1220 "module kind %d should not be possible",
1221 mod->kind);
1222 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224 co = assemble(c, addNone);
1225 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001226 return co;
1227}
1228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229/* The test for LOCAL must come before the test for FREE in order to
1230 handle classes where name is both local and free. The local var is
1231 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001232*/
1233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234static int
1235get_ref_type(struct compiler *c, PyObject *name)
1236{
1237 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001238 if (scope == 0) {
1239 char buf[350];
1240 PyOS_snprintf(buf, sizeof(buf),
1241 "unknown scope for %.100s in %.100s(%s) in %s\n"
1242 "symbols: %s\nlocals: %s\nglobals: %s\n",
Christian Heimes72b710a2008-05-26 13:28:38 +00001243 PyBytes_AS_STRING(name),
1244 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 PyObject_REPR(c->u->u_ste->ste_id),
1246 c->c_filename,
1247 PyObject_REPR(c->u->u_ste->ste_symbols),
1248 PyObject_REPR(c->u->u_varnames),
1249 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 Py_FatalError(buf);
1252 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001253
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001254 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255}
1256
1257static int
1258compiler_lookup_arg(PyObject *dict, PyObject *name)
1259{
1260 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001263 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001265 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001267 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001268 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269}
1270
1271static int
1272compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1273{
1274 int i, free = PyCode_GetNumFree(co);
1275 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001276 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1277 ADDOP_I(c, MAKE_FUNCTION, args);
1278 return 1;
1279 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001280 for (i = 0; i < free; ++i) {
1281 /* Bypass com_addop_varname because it will generate
1282 LOAD_DEREF but LOAD_CLOSURE is needed.
1283 */
1284 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1285 int arg, reftype;
1286
1287 /* Special case: If a class contains a method with a
1288 free variable that has the same name as a method,
1289 the name will be considered free *and* local in the
1290 class. It should be handled by the closure, as
1291 well as by the normal name loookup logic.
1292 */
1293 reftype = get_ref_type(c, name);
1294 if (reftype == CELL)
1295 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1296 else /* (reftype == FREE) */
1297 arg = compiler_lookup_arg(c->u->u_freevars, name);
1298 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001299 fprintf(stderr,
1300 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301 "freevars of %s: %s\n",
1302 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001303 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001304 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001305 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306 PyObject_REPR(co->co_freevars));
1307 Py_FatalError("compiler_make_closure()");
1308 }
1309 ADDOP_I(c, LOAD_CLOSURE, arg);
1310 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001311 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001313 ADDOP_I(c, MAKE_CLOSURE, args);
1314 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315}
1316
1317static int
1318compiler_decorators(struct compiler *c, asdl_seq* decos)
1319{
1320 int i;
1321
1322 if (!decos)
1323 return 1;
1324
1325 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001326 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327 }
1328 return 1;
1329}
1330
1331static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001332compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1333 asdl_seq *kw_defaults)
1334{
1335 int i, default_count = 0;
1336 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001337 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001338 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1339 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001340 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001341 if (!compiler_visit_expr(c, default_)) {
1342 return -1;
1343 }
1344 default_count++;
1345 }
1346 }
1347 return default_count;
1348}
1349
1350static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001351compiler_visit_argannotation(struct compiler *c, identifier id,
1352 expr_ty annotation, PyObject *names)
1353{
1354 if (annotation) {
1355 VISIT(c, expr, annotation);
1356 if (PyList_Append(names, id))
1357 return -1;
1358 }
1359 return 0;
1360}
1361
1362static int
1363compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1364 PyObject *names)
1365{
1366 int i, error;
1367 for (i = 0; i < asdl_seq_LEN(args); i++) {
1368 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001369 error = compiler_visit_argannotation(
1370 c,
1371 arg->arg,
1372 arg->annotation,
1373 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001374 if (error)
1375 return error;
1376 }
1377 return 0;
1378}
1379
1380static int
1381compiler_visit_annotations(struct compiler *c, arguments_ty args,
1382 expr_ty returns)
1383{
Guido van Rossum0240b922007-02-26 21:23:50 +00001384 /* Push arg annotations and a list of the argument names. Return the #
1385 of items pushed. The expressions are evaluated out-of-order wrt the
1386 source code.
1387
1388 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1389 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001390 static identifier return_str;
1391 PyObject *names;
1392 int len;
1393 names = PyList_New(0);
1394 if (!names)
1395 return -1;
1396
1397 if (compiler_visit_argannotations(c, args->args, names))
1398 goto error;
1399 if (args->varargannotation &&
1400 compiler_visit_argannotation(c, args->vararg,
1401 args->varargannotation, names))
1402 goto error;
1403 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1404 goto error;
1405 if (args->kwargannotation &&
1406 compiler_visit_argannotation(c, args->kwarg,
1407 args->kwargannotation, names))
1408 goto error;
1409
1410 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001411 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001412 if (!return_str)
1413 goto error;
1414 }
1415 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1416 goto error;
1417 }
1418
1419 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001420 if (len > 65534) {
1421 /* len must fit in 16 bits, and len is incremented below */
1422 PyErr_SetString(PyExc_SyntaxError,
1423 "too many annotations");
1424 goto error;
1425 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001426 if (len) {
1427 /* convert names to a tuple and place on stack */
1428 PyObject *elt;
1429 int i;
1430 PyObject *s = PyTuple_New(len);
1431 if (!s)
1432 goto error;
1433 for (i = 0; i < len; i++) {
1434 elt = PyList_GET_ITEM(names, i);
1435 Py_INCREF(elt);
1436 PyTuple_SET_ITEM(s, i, elt);
1437 }
1438 ADDOP_O(c, LOAD_CONST, s, consts);
1439 Py_DECREF(s);
1440 len++; /* include the just-pushed tuple */
1441 }
1442 Py_DECREF(names);
1443 return len;
1444
1445error:
1446 Py_DECREF(names);
1447 return -1;
1448}
1449
1450static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451compiler_function(struct compiler *c, stmt_ty s)
1452{
1453 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001454 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001456 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001457 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001458 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001459 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001460 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461
1462 assert(s->kind == FunctionDef_kind);
1463
1464 if (!compiler_decorators(c, decos))
1465 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001466 if (args->kwonlyargs) {
1467 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1468 args->kw_defaults);
1469 if (res < 0)
1470 return 0;
1471 kw_default_count = res;
1472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473 if (args->defaults)
1474 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001475 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001476 if (num_annotations < 0)
1477 return 0;
1478 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001479
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1481 s->lineno))
1482 return 0;
1483
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001484 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001485 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001486 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001487 first_const = st->v.Expr.value->v.Str.s;
1488 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001489 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001490 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001494 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001496 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001498 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1499 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500 }
1501 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001502 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503 if (co == NULL)
1504 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505
Guido van Rossum4f72a782006-10-27 23:31:49 +00001506 arglength = asdl_seq_LEN(args->defaults);
1507 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001508 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001509 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001510 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511
Neal Norwitzc1505362006-12-28 06:47:50 +00001512 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1514 ADDOP_I(c, CALL_FUNCTION, 1);
1515 }
1516
1517 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1518}
1519
1520static int
1521compiler_class(struct compiler *c, stmt_ty s)
1522{
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001523 static PyObject *locals = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001525 PyObject *str;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001526 PySTEntryObject *ste;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001527 int err, i;
1528 asdl_seq* decos = s->v.ClassDef.decorator_list;
1529
1530 if (!compiler_decorators(c, decos))
1531 return 0;
1532
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001533 /* initialize statics */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001534 if (locals == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001535 locals = PyUnicode_InternFromString("__locals__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001536 if (locals == NULL)
1537 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001538 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001540 /* ultimately generate code for:
1541 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1542 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001543 <func> is a function/closure created from the class body;
1544 it has a single argument (__locals__) where the dict
1545 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001546 <name> is the class name
1547 <bases> is the positional arguments and *varargs argument
1548 <keywords> is the keyword arguments and **kwds argument
1549 This borrows from compiler_call.
1550 */
1551
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001552 /* 0. Create a fake argument named __locals__ */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001553 ste = PySymtable_Lookup(c->c_st, s);
1554 if (ste == NULL)
1555 return 0;
1556 assert(PyList_Check(ste->ste_varnames));
Guido van Rossum3a383622007-03-21 21:26:58 +00001557 err = PyList_Append(ste->ste_varnames, locals);
1558 Py_DECREF(ste);
1559 if (err < 0)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001560 return 0;
1561
1562 /* 1. compile the class body into a code object */
1563 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1564 return 0;
1565 /* this block represents what we do in the new scope */
1566 {
1567 /* use the class name for name mangling */
1568 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001569 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001570 c->u->u_private = s->v.ClassDef.name;
1571 /* force it to have one mandatory argument */
1572 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001573 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001574 ADDOP_I(c, LOAD_FAST, 0);
1575 /* ... and store it into f_locals */
1576 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001577 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001578 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001579 if (!str || !compiler_nameop(c, str, Load)) {
1580 Py_XDECREF(str);
1581 compiler_exit_scope(c);
1582 return 0;
1583 }
1584 Py_DECREF(str);
1585 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001586 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001587 if (!str || !compiler_nameop(c, str, Store)) {
1588 Py_XDECREF(str);
1589 compiler_exit_scope(c);
1590 return 0;
1591 }
1592 Py_DECREF(str);
1593 /* compile the body proper */
1594 if (!compiler_body(c, s->v.ClassDef.body)) {
1595 compiler_exit_scope(c);
1596 return 0;
1597 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001598 /* return the (empty) __class__ cell */
1599 str = PyUnicode_InternFromString("__class__");
1600 if (str == NULL) {
1601 compiler_exit_scope(c);
1602 return 0;
1603 }
1604 i = compiler_lookup_arg(c->u->u_cellvars, str);
1605 Py_DECREF(str);
1606 if (i == -1) {
1607 /* This happens when nobody references the cell */
1608 PyErr_Clear();
1609 /* Return None */
1610 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1611 }
1612 else {
1613 /* Return the cell where to store __class__ */
1614 ADDOP_I(c, LOAD_CLOSURE, i);
1615 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001616 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1617 /* create the code object */
1618 co = assemble(c, 1);
1619 }
1620 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001621 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622 if (co == NULL)
1623 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001625 /* 2. load the 'build_class' function */
1626 ADDOP(c, LOAD_BUILD_CLASS);
1627
1628 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001629 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001630 Py_DECREF(co);
1631
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001632 /* 4. load class name */
1633 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1634
1635 /* 5. generate the rest of the code for the call */
1636 if (!compiler_call_helper(c, 2,
1637 s->v.ClassDef.bases,
1638 s->v.ClassDef.keywords,
1639 s->v.ClassDef.starargs,
1640 s->v.ClassDef.kwargs))
1641 return 0;
1642
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001643 /* 6. apply decorators */
1644 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1645 ADDOP_I(c, CALL_FUNCTION, 1);
1646 }
1647
1648 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1650 return 0;
1651 return 1;
1652}
1653
1654static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001655compiler_ifexp(struct compiler *c, expr_ty e)
1656{
1657 basicblock *end, *next;
1658
1659 assert(e->kind == IfExp_kind);
1660 end = compiler_new_block(c);
1661 if (end == NULL)
1662 return 0;
1663 next = compiler_new_block(c);
1664 if (next == NULL)
1665 return 0;
1666 VISIT(c, expr, e->v.IfExp.test);
1667 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1668 ADDOP(c, POP_TOP);
1669 VISIT(c, expr, e->v.IfExp.body);
1670 ADDOP_JREL(c, JUMP_FORWARD, end);
1671 compiler_use_next_block(c, next);
1672 ADDOP(c, POP_TOP);
1673 VISIT(c, expr, e->v.IfExp.orelse);
1674 compiler_use_next_block(c, end);
1675 return 1;
1676}
1677
1678static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679compiler_lambda(struct compiler *c, expr_ty e)
1680{
1681 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001682 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001683 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001684 arguments_ty args = e->v.Lambda.args;
1685 assert(e->kind == Lambda_kind);
1686
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001687 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001688 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001689 if (!name)
1690 return 0;
1691 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
Guido van Rossum4f72a782006-10-27 23:31:49 +00001693 if (args->kwonlyargs) {
1694 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1695 args->kw_defaults);
1696 if (res < 0) return 0;
1697 kw_default_count = res;
1698 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699 if (args->defaults)
1700 VISIT_SEQ(c, expr, args->defaults);
1701 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1702 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001703
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001705 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001706 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1707 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001709 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710 if (co == NULL)
1711 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001712
Guido van Rossum4f72a782006-10-27 23:31:49 +00001713 arglength = asdl_seq_LEN(args->defaults);
1714 arglength |= kw_default_count << 8;
1715 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001716 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717
1718 return 1;
1719}
1720
1721static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722compiler_if(struct compiler *c, stmt_ty s)
1723{
1724 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001725 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726 assert(s->kind == If_kind);
1727 end = compiler_new_block(c);
1728 if (end == NULL)
1729 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001730 next = compiler_new_block(c);
1731 if (next == NULL)
1732 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001733
1734 constant = expr_constant(s->v.If.test);
1735 /* constant = 0: "if 0"
1736 * constant = 1: "if 1", "if 2", ...
1737 * constant = -1: rest */
1738 if (constant == 0) {
1739 if (s->v.If.orelse)
1740 VISIT_SEQ(c, stmt, s->v.If.orelse);
1741 } else if (constant == 1) {
1742 VISIT_SEQ(c, stmt, s->v.If.body);
1743 } else {
1744 VISIT(c, expr, s->v.If.test);
1745 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1746 ADDOP(c, POP_TOP);
1747 VISIT_SEQ(c, stmt, s->v.If.body);
1748 ADDOP_JREL(c, JUMP_FORWARD, end);
1749 compiler_use_next_block(c, next);
1750 ADDOP(c, POP_TOP);
1751 if (s->v.If.orelse)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001752 VISIT_SEQ(c, stmt, s->v.If.orelse);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001753 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001754 compiler_use_next_block(c, end);
1755 return 1;
1756}
1757
1758static int
1759compiler_for(struct compiler *c, stmt_ty s)
1760{
1761 basicblock *start, *cleanup, *end;
1762
1763 start = compiler_new_block(c);
1764 cleanup = compiler_new_block(c);
1765 end = compiler_new_block(c);
1766 if (start == NULL || end == NULL || cleanup == NULL)
1767 return 0;
1768 ADDOP_JREL(c, SETUP_LOOP, end);
1769 if (!compiler_push_fblock(c, LOOP, start))
1770 return 0;
1771 VISIT(c, expr, s->v.For.iter);
1772 ADDOP(c, GET_ITER);
1773 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001774 /* for expressions must be traced on each iteration,
1775 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001776 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777 ADDOP_JREL(c, FOR_ITER, cleanup);
1778 VISIT(c, expr, s->v.For.target);
1779 VISIT_SEQ(c, stmt, s->v.For.body);
1780 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1781 compiler_use_next_block(c, cleanup);
1782 ADDOP(c, POP_BLOCK);
1783 compiler_pop_fblock(c, LOOP, start);
1784 VISIT_SEQ(c, stmt, s->v.For.orelse);
1785 compiler_use_next_block(c, end);
1786 return 1;
1787}
1788
1789static int
1790compiler_while(struct compiler *c, stmt_ty s)
1791{
1792 basicblock *loop, *orelse, *end, *anchor = NULL;
1793 int constant = expr_constant(s->v.While.test);
1794
Christian Heimes969fe572008-01-25 11:23:10 +00001795 if (constant == 0) {
1796 if (s->v.While.orelse)
1797 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001799 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 loop = compiler_new_block(c);
1801 end = compiler_new_block(c);
1802 if (constant == -1) {
1803 anchor = compiler_new_block(c);
1804 if (anchor == NULL)
1805 return 0;
1806 }
1807 if (loop == NULL || end == NULL)
1808 return 0;
1809 if (s->v.While.orelse) {
1810 orelse = compiler_new_block(c);
1811 if (orelse == NULL)
1812 return 0;
1813 }
1814 else
1815 orelse = NULL;
1816
1817 ADDOP_JREL(c, SETUP_LOOP, end);
1818 compiler_use_next_block(c, loop);
1819 if (!compiler_push_fblock(c, LOOP, loop))
1820 return 0;
1821 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001822 /* while expressions must be traced on each iteration,
1823 so we need to set an extra line number. */
1824 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825 VISIT(c, expr, s->v.While.test);
1826 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1827 ADDOP(c, POP_TOP);
1828 }
1829 VISIT_SEQ(c, stmt, s->v.While.body);
1830 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1831
1832 /* XXX should the two POP instructions be in a separate block
1833 if there is no else clause ?
1834 */
1835
1836 if (constant == -1) {
1837 compiler_use_next_block(c, anchor);
1838 ADDOP(c, POP_TOP);
1839 ADDOP(c, POP_BLOCK);
1840 }
1841 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001842 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001843 VISIT_SEQ(c, stmt, s->v.While.orelse);
1844 compiler_use_next_block(c, end);
1845
1846 return 1;
1847}
1848
1849static int
1850compiler_continue(struct compiler *c)
1851{
1852 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001853 static const char IN_FINALLY_ERROR_MSG[] =
1854 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855 int i;
1856
1857 if (!c->u->u_nfblocks)
1858 return compiler_error(c, LOOP_ERROR_MSG);
1859 i = c->u->u_nfblocks - 1;
1860 switch (c->u->u_fblock[i].fb_type) {
1861 case LOOP:
1862 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1863 break;
1864 case EXCEPT:
1865 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001866 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1867 /* Prevent continue anywhere under a finally
1868 even if hidden in a sub-try or except. */
1869 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1870 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1871 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872 if (i == -1)
1873 return compiler_error(c, LOOP_ERROR_MSG);
1874 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1875 break;
1876 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001877 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 }
1879
1880 return 1;
1881}
1882
1883/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1884
1885 SETUP_FINALLY L
1886 <code for body>
1887 POP_BLOCK
1888 LOAD_CONST <None>
1889 L: <code for finalbody>
1890 END_FINALLY
1891
1892 The special instructions use the block stack. Each block
1893 stack entry contains the instruction that created it (here
1894 SETUP_FINALLY), the level of the value stack at the time the
1895 block stack entry was created, and a label (here L).
1896
1897 SETUP_FINALLY:
1898 Pushes the current value stack level and the label
1899 onto the block stack.
1900 POP_BLOCK:
1901 Pops en entry from the block stack, and pops the value
1902 stack until its level is the same as indicated on the
1903 block stack. (The label is ignored.)
1904 END_FINALLY:
1905 Pops a variable number of entries from the *value* stack
1906 and re-raises the exception they specify. The number of
1907 entries popped depends on the (pseudo) exception type.
1908
1909 The block stack is unwound when an exception is raised:
1910 when a SETUP_FINALLY entry is found, the exception is pushed
1911 onto the value stack (and the exception condition is cleared),
1912 and the interpreter jumps to the label gotten from the block
1913 stack.
1914*/
1915
1916static int
1917compiler_try_finally(struct compiler *c, stmt_ty s)
1918{
1919 basicblock *body, *end;
1920 body = compiler_new_block(c);
1921 end = compiler_new_block(c);
1922 if (body == NULL || end == NULL)
1923 return 0;
1924
1925 ADDOP_JREL(c, SETUP_FINALLY, end);
1926 compiler_use_next_block(c, body);
1927 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1928 return 0;
1929 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1930 ADDOP(c, POP_BLOCK);
1931 compiler_pop_fblock(c, FINALLY_TRY, body);
1932
1933 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1934 compiler_use_next_block(c, end);
1935 if (!compiler_push_fblock(c, FINALLY_END, end))
1936 return 0;
1937 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1938 ADDOP(c, END_FINALLY);
1939 compiler_pop_fblock(c, FINALLY_END, end);
1940
1941 return 1;
1942}
1943
1944/*
1945 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1946 (The contents of the value stack is shown in [], with the top
1947 at the right; 'tb' is trace-back info, 'val' the exception's
1948 associated value, and 'exc' the exception.)
1949
1950 Value stack Label Instruction Argument
1951 [] SETUP_EXCEPT L1
1952 [] <code for S>
1953 [] POP_BLOCK
1954 [] JUMP_FORWARD L0
1955
1956 [tb, val, exc] L1: DUP )
1957 [tb, val, exc, exc] <evaluate E1> )
1958 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1959 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1960 [tb, val, exc, 1] POP )
1961 [tb, val, exc] POP
1962 [tb, val] <assign to V1> (or POP if no V1)
1963 [tb] POP
1964 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001965 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966
1967 [tb, val, exc, 0] L2: POP
1968 [tb, val, exc] DUP
1969 .............................etc.......................
1970
1971 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001972 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973
1974 [] L0: <next statement>
1975
1976 Of course, parts are not generated if Vi or Ei is not present.
1977*/
1978static int
1979compiler_try_except(struct compiler *c, stmt_ty s)
1980{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001981 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 int i, n;
1983
1984 body = compiler_new_block(c);
1985 except = compiler_new_block(c);
1986 orelse = compiler_new_block(c);
1987 end = compiler_new_block(c);
1988 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1989 return 0;
1990 ADDOP_JREL(c, SETUP_EXCEPT, except);
1991 compiler_use_next_block(c, body);
1992 if (!compiler_push_fblock(c, EXCEPT, body))
1993 return 0;
1994 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1995 ADDOP(c, POP_BLOCK);
1996 compiler_pop_fblock(c, EXCEPT, body);
1997 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1998 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1999 compiler_use_next_block(c, except);
2000 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002001 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002003 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00002005 c->u->u_lineno_set = 0;
2006 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 except = compiler_new_block(c);
2008 if (except == NULL)
2009 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002010 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002012 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2014 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2015 ADDOP(c, POP_TOP);
2016 }
2017 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002018 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00002019 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002020
2021 cleanup_end = compiler_new_block(c);
2022 cleanup_body = compiler_new_block(c);
2023 if(!(cleanup_end || cleanup_body))
2024 return 0;
2025
Neal Norwitzad74aa82008-03-31 05:14:30 +00002026 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002027 ADDOP(c, POP_TOP);
2028
2029 /*
2030 try:
2031 # body
2032 except type as name:
2033 try:
2034 # body
2035 finally:
2036 name = None
2037 del name
2038 */
2039
2040 /* second try: */
2041 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2042 compiler_use_next_block(c, cleanup_body);
2043 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2044 return 0;
2045
2046 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002047 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002048 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002049 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002050 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2051
2052 /* finally: */
2053 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2054 compiler_use_next_block(c, cleanup_end);
2055 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2056 return 0;
2057
2058 /* name = None */
2059 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002060 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002061
Guido van Rossum16be03e2007-01-10 18:51:35 +00002062 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002063 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002064
2065 ADDOP(c, END_FINALLY);
2066 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 }
2068 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002069 basicblock *cleanup_body;
2070
2071 cleanup_body = compiler_new_block(c);
2072 if(!cleanup_body)
2073 return 0;
2074
2075 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002076 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002077 compiler_use_next_block(c, cleanup_body);
2078 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2079 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002080 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002081 ADDOP(c, POP_EXCEPT);
2082 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 ADDOP_JREL(c, JUMP_FORWARD, end);
2085 compiler_use_next_block(c, except);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002086 if (handler->v.ExceptHandler.type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087 ADDOP(c, POP_TOP);
2088 }
2089 ADDOP(c, END_FINALLY);
2090 compiler_use_next_block(c, orelse);
2091 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2092 compiler_use_next_block(c, end);
2093 return 1;
2094}
2095
2096static int
2097compiler_import_as(struct compiler *c, identifier name, identifier asname)
2098{
2099 /* The IMPORT_NAME opcode was already generated. This function
2100 merely needs to bind the result to a name.
2101
2102 If there is a dot in name, we need to split it and emit a
2103 LOAD_ATTR for each name.
2104 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002105 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2106 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 if (dot) {
2108 /* Consume the base module name to get the first attribute */
2109 src = dot + 1;
2110 while (dot) {
2111 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002112 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002113 dot = Py_UNICODE_strchr(src, '.');
2114 attr = PyUnicode_FromUnicode(src,
2115 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002116 if (!attr)
2117 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002119 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120 src = dot + 1;
2121 }
2122 }
2123 return compiler_nameop(c, asname, Store);
2124}
2125
2126static int
2127compiler_import(struct compiler *c, stmt_ty s)
2128{
2129 /* The Import node stores a module name like a.b.c as a single
2130 string. This is convenient for all cases except
2131 import a.b.c as d
2132 where we need to parse that string to extract the individual
2133 module names.
2134 XXX Perhaps change the representation to make this case simpler?
2135 */
2136 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002139 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002141 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002142
Christian Heimes217cfd12007-12-02 14:31:20 +00002143 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002144 if (level == NULL)
2145 return 0;
2146
2147 ADDOP_O(c, LOAD_CONST, level, consts);
2148 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2150 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2151
2152 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002153 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002154 if (!r)
2155 return r;
2156 }
2157 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002159 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2160 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002162 tmp = PyUnicode_FromUnicode(base,
2163 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164 r = compiler_nameop(c, tmp, Store);
2165 if (dot) {
2166 Py_DECREF(tmp);
2167 }
2168 if (!r)
2169 return r;
2170 }
2171 }
2172 return 1;
2173}
2174
2175static int
2176compiler_from_import(struct compiler *c, stmt_ty s)
2177{
2178 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179
2180 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002181 PyObject *level;
2182
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183 if (!names)
2184 return 0;
2185
Christian Heimes217cfd12007-12-02 14:31:20 +00002186 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002187 if (!level) {
2188 Py_DECREF(names);
2189 return 0;
2190 }
2191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192 /* build up the names */
2193 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002194 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195 Py_INCREF(alias->name);
2196 PyTuple_SET_ITEM(names, i, alias->name);
2197 }
2198
2199 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002200 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2201 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002202 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203 Py_DECREF(names);
2204 return compiler_error(c,
2205 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002206 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002207
2208 }
2209 }
2210
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002211 ADDOP_O(c, LOAD_CONST, level, consts);
2212 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002214 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002215 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2216 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002217 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002218 identifier store_name;
2219
Martin v. Löwis5b222132007-06-10 09:51:05 +00002220 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 assert(n == 1);
2222 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002223 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224 }
2225
2226 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2227 store_name = alias->name;
2228 if (alias->asname)
2229 store_name = alias->asname;
2230
2231 if (!compiler_nameop(c, store_name, Store)) {
2232 Py_DECREF(names);
2233 return 0;
2234 }
2235 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002236 /* remove imported module */
2237 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 return 1;
2239}
2240
2241static int
2242compiler_assert(struct compiler *c, stmt_ty s)
2243{
2244 static PyObject *assertion_error = NULL;
2245 basicblock *end;
2246
2247 if (Py_OptimizeFlag)
2248 return 1;
2249 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002250 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002251 if (assertion_error == NULL)
2252 return 0;
2253 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002254 if (s->v.Assert.test->kind == Tuple_kind &&
2255 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2256 const char* msg =
2257 "assertion is always true, perhaps remove parentheses?";
2258 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2259 c->u->u_lineno, NULL, NULL) == -1)
2260 return 0;
2261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 VISIT(c, expr, s->v.Assert.test);
2263 end = compiler_new_block(c);
2264 if (end == NULL)
2265 return 0;
2266 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2267 ADDOP(c, POP_TOP);
2268 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2269 if (s->v.Assert.msg) {
2270 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002271 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272 }
Collin Winter828f04a2007-08-31 00:04:24 +00002273 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002274 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275 ADDOP(c, POP_TOP);
2276 return 1;
2277}
2278
2279static int
2280compiler_visit_stmt(struct compiler *c, stmt_ty s)
2281{
2282 int i, n;
2283
Thomas Wouters89f507f2006-12-13 04:49:30 +00002284 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002286 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002289 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 if (c->u->u_ste->ste_type != FunctionBlock)
2295 return compiler_error(c, "'return' outside function");
2296 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 VISIT(c, expr, s->v.Return.value);
2298 }
2299 else
2300 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2301 ADDOP(c, RETURN_VALUE);
2302 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002303 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304 VISIT_SEQ(c, expr, s->v.Delete.targets)
2305 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002306 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 n = asdl_seq_LEN(s->v.Assign.targets);
2308 VISIT(c, expr, s->v.Assign.value);
2309 for (i = 0; i < n; i++) {
2310 if (i < n - 1)
2311 ADDOP(c, DUP_TOP);
2312 VISIT(c, expr,
2313 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2314 }
2315 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002316 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002318 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002320 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002322 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002324 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002326 if (s->v.Raise.exc) {
2327 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002329 if (s->v.Raise.cause) {
2330 VISIT(c, expr, s->v.Raise.cause);
2331 n++;
2332 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 }
2334 ADDOP_I(c, RAISE_VARARGS, n);
2335 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002336 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002338 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002340 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002342 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002344 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002346 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002347 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002349 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002351 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352 ADDOP(c, PRINT_EXPR);
2353 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002354 else if (s->v.Expr.value->kind != Str_kind &&
2355 s->v.Expr.value->kind != Num_kind) {
2356 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 ADDOP(c, POP_TOP);
2358 }
2359 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002360 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002362 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002363 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364 return compiler_error(c, "'break' outside loop");
2365 ADDOP(c, BREAK_LOOP);
2366 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002367 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002369 case With_kind:
2370 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371 }
2372 return 1;
2373}
2374
2375static int
2376unaryop(unaryop_ty op)
2377{
2378 switch (op) {
2379 case Invert:
2380 return UNARY_INVERT;
2381 case Not:
2382 return UNARY_NOT;
2383 case UAdd:
2384 return UNARY_POSITIVE;
2385 case USub:
2386 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002387 default:
2388 PyErr_Format(PyExc_SystemError,
2389 "unary op %d should not be possible", op);
2390 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392}
2393
2394static int
2395binop(struct compiler *c, operator_ty op)
2396{
2397 switch (op) {
2398 case Add:
2399 return BINARY_ADD;
2400 case Sub:
2401 return BINARY_SUBTRACT;
2402 case Mult:
2403 return BINARY_MULTIPLY;
2404 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002405 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406 case Mod:
2407 return BINARY_MODULO;
2408 case Pow:
2409 return BINARY_POWER;
2410 case LShift:
2411 return BINARY_LSHIFT;
2412 case RShift:
2413 return BINARY_RSHIFT;
2414 case BitOr:
2415 return BINARY_OR;
2416 case BitXor:
2417 return BINARY_XOR;
2418 case BitAnd:
2419 return BINARY_AND;
2420 case FloorDiv:
2421 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002422 default:
2423 PyErr_Format(PyExc_SystemError,
2424 "binary op %d should not be possible", op);
2425 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002426 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427}
2428
2429static int
2430cmpop(cmpop_ty op)
2431{
2432 switch (op) {
2433 case Eq:
2434 return PyCmp_EQ;
2435 case NotEq:
2436 return PyCmp_NE;
2437 case Lt:
2438 return PyCmp_LT;
2439 case LtE:
2440 return PyCmp_LE;
2441 case Gt:
2442 return PyCmp_GT;
2443 case GtE:
2444 return PyCmp_GE;
2445 case Is:
2446 return PyCmp_IS;
2447 case IsNot:
2448 return PyCmp_IS_NOT;
2449 case In:
2450 return PyCmp_IN;
2451 case NotIn:
2452 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002453 default:
2454 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456}
2457
2458static int
2459inplace_binop(struct compiler *c, operator_ty op)
2460{
2461 switch (op) {
2462 case Add:
2463 return INPLACE_ADD;
2464 case Sub:
2465 return INPLACE_SUBTRACT;
2466 case Mult:
2467 return INPLACE_MULTIPLY;
2468 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002469 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 case Mod:
2471 return INPLACE_MODULO;
2472 case Pow:
2473 return INPLACE_POWER;
2474 case LShift:
2475 return INPLACE_LSHIFT;
2476 case RShift:
2477 return INPLACE_RSHIFT;
2478 case BitOr:
2479 return INPLACE_OR;
2480 case BitXor:
2481 return INPLACE_XOR;
2482 case BitAnd:
2483 return INPLACE_AND;
2484 case FloorDiv:
2485 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002486 default:
2487 PyErr_Format(PyExc_SystemError,
2488 "inplace binary op %d should not be possible", op);
2489 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491}
2492
2493static int
2494compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2495{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002496 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2498
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002499 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002500 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 /* XXX AugStore isn't used anywhere! */
2502
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002503 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002504 if (!mangled)
2505 return 0;
2506
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 op = 0;
2508 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002509 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510 switch (scope) {
2511 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002512 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 optype = OP_DEREF;
2514 break;
2515 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002516 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517 optype = OP_DEREF;
2518 break;
2519 case LOCAL:
2520 if (c->u->u_ste->ste_type == FunctionBlock)
2521 optype = OP_FAST;
2522 break;
2523 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002524 if (c->u->u_ste->ste_type == FunctionBlock &&
2525 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526 optype = OP_GLOBAL;
2527 break;
2528 case GLOBAL_EXPLICIT:
2529 optype = OP_GLOBAL;
2530 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002531 default:
2532 /* scope can be 0 */
2533 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 }
2535
2536 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002537 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538
2539 switch (optype) {
2540 case OP_DEREF:
2541 switch (ctx) {
2542 case Load: op = LOAD_DEREF; break;
2543 case Store: op = STORE_DEREF; break;
2544 case AugLoad:
2545 case AugStore:
2546 break;
2547 case Del:
2548 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002549 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002551 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002552 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002554 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002555 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002556 PyErr_SetString(PyExc_SystemError,
2557 "param invalid for deref variable");
2558 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 }
2560 break;
2561 case OP_FAST:
2562 switch (ctx) {
2563 case Load: op = LOAD_FAST; break;
2564 case Store: op = STORE_FAST; break;
2565 case Del: op = DELETE_FAST; break;
2566 case AugLoad:
2567 case AugStore:
2568 break;
2569 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002570 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002571 PyErr_SetString(PyExc_SystemError,
2572 "param invalid for local variable");
2573 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002575 ADDOP_O(c, op, mangled, varnames);
2576 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002577 return 1;
2578 case OP_GLOBAL:
2579 switch (ctx) {
2580 case Load: op = LOAD_GLOBAL; break;
2581 case Store: op = STORE_GLOBAL; break;
2582 case Del: op = DELETE_GLOBAL; break;
2583 case AugLoad:
2584 case AugStore:
2585 break;
2586 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002587 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002588 PyErr_SetString(PyExc_SystemError,
2589 "param invalid for global variable");
2590 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591 }
2592 break;
2593 case OP_NAME:
2594 switch (ctx) {
2595 case Load: op = LOAD_NAME; break;
2596 case Store: op = STORE_NAME; break;
2597 case Del: op = DELETE_NAME; break;
2598 case AugLoad:
2599 case AugStore:
2600 break;
2601 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002602 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002603 PyErr_SetString(PyExc_SystemError,
2604 "param invalid for name variable");
2605 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 }
2607 break;
2608 }
2609
2610 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002611 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002612 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002613 if (arg < 0)
2614 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002615 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616}
2617
2618static int
2619compiler_boolop(struct compiler *c, expr_ty e)
2620{
2621 basicblock *end;
2622 int jumpi, i, n;
2623 asdl_seq *s;
2624
2625 assert(e->kind == BoolOp_kind);
2626 if (e->v.BoolOp.op == And)
2627 jumpi = JUMP_IF_FALSE;
2628 else
2629 jumpi = JUMP_IF_TRUE;
2630 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002631 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632 return 0;
2633 s = e->v.BoolOp.values;
2634 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002635 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002637 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 ADDOP_JREL(c, jumpi, end);
2639 ADDOP(c, POP_TOP)
2640 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002641 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 compiler_use_next_block(c, end);
2643 return 1;
2644}
2645
2646static int
2647compiler_list(struct compiler *c, expr_ty e)
2648{
2649 int n = asdl_seq_LEN(e->v.List.elts);
2650 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002651 int i, seen_star = 0;
2652 for (i = 0; i < n; i++) {
2653 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2654 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002655 if ((i >= (1 << 8)) ||
2656 (n-i-1 >= (INT_MAX >> 8)))
2657 return compiler_error(c,
2658 "too many expressions in "
2659 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002660 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2661 seen_star = 1;
2662 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2663 } else if (elt->kind == Starred_kind) {
2664 return compiler_error(c,
2665 "two starred expressions in assignment");
2666 }
2667 }
2668 if (!seen_star) {
2669 ADDOP_I(c, UNPACK_SEQUENCE, n);
2670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671 }
2672 VISIT_SEQ(c, expr, e->v.List.elts);
2673 if (e->v.List.ctx == Load) {
2674 ADDOP_I(c, BUILD_LIST, n);
2675 }
2676 return 1;
2677}
2678
2679static int
2680compiler_tuple(struct compiler *c, expr_ty e)
2681{
2682 int n = asdl_seq_LEN(e->v.Tuple.elts);
2683 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002684 int i, seen_star = 0;
2685 for (i = 0; i < n; i++) {
2686 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2687 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002688 if ((i >= (1 << 8)) ||
2689 (n-i-1 >= (INT_MAX >> 8)))
2690 return compiler_error(c,
2691 "too many expressions in "
2692 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002693 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2694 seen_star = 1;
2695 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2696 } else if (elt->kind == Starred_kind) {
2697 return compiler_error(c,
2698 "two starred expressions in assignment");
2699 }
2700 }
2701 if (!seen_star) {
2702 ADDOP_I(c, UNPACK_SEQUENCE, n);
2703 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704 }
2705 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2706 if (e->v.Tuple.ctx == Load) {
2707 ADDOP_I(c, BUILD_TUPLE, n);
2708 }
2709 return 1;
2710}
2711
2712static int
2713compiler_compare(struct compiler *c, expr_ty e)
2714{
2715 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002716 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717
2718 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2719 VISIT(c, expr, e->v.Compare.left);
2720 n = asdl_seq_LEN(e->v.Compare.ops);
2721 assert(n > 0);
2722 if (n > 1) {
2723 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002724 if (cleanup == NULL)
2725 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002726 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002727 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728 }
2729 for (i = 1; i < n; i++) {
2730 ADDOP(c, DUP_TOP);
2731 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002733 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002734 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2736 NEXT_BLOCK(c);
2737 ADDOP(c, POP_TOP);
2738 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002739 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002740 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002742 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002744 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745 if (n > 1) {
2746 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002747 if (end == NULL)
2748 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749 ADDOP_JREL(c, JUMP_FORWARD, end);
2750 compiler_use_next_block(c, cleanup);
2751 ADDOP(c, ROT_TWO);
2752 ADDOP(c, POP_TOP);
2753 compiler_use_next_block(c, end);
2754 }
2755 return 1;
2756}
2757
2758static int
2759compiler_call(struct compiler *c, expr_ty e)
2760{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002762 return compiler_call_helper(c, 0,
2763 e->v.Call.args,
2764 e->v.Call.keywords,
2765 e->v.Call.starargs,
2766 e->v.Call.kwargs);
2767}
2768
2769/* shared code between compiler_call and compiler_class */
2770static int
2771compiler_call_helper(struct compiler *c,
2772 int n, /* Args already pushed */
2773 asdl_seq *args,
2774 asdl_seq *keywords,
2775 expr_ty starargs,
2776 expr_ty kwargs)
2777{
2778 int code = 0;
2779
2780 n += asdl_seq_LEN(args);
2781 VISIT_SEQ(c, expr, args);
2782 if (keywords) {
2783 VISIT_SEQ(c, keyword, keywords);
2784 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002786 if (starargs) {
2787 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788 code |= 1;
2789 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002790 if (kwargs) {
2791 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792 code |= 2;
2793 }
2794 switch (code) {
2795 case 0:
2796 ADDOP_I(c, CALL_FUNCTION, n);
2797 break;
2798 case 1:
2799 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2800 break;
2801 case 2:
2802 ADDOP_I(c, CALL_FUNCTION_KW, n);
2803 break;
2804 case 3:
2805 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2806 break;
2807 }
2808 return 1;
2809}
2810
Nick Coghlan650f0d02007-04-15 12:05:43 +00002811
2812/* List and set comprehensions and generator expressions work by creating a
2813 nested function to perform the actual iteration. This means that the
2814 iteration variables don't leak into the current scope.
2815 The defined function is called immediately following its definition, with the
2816 result of that call being the result of the expression.
2817 The LC/SC version returns the populated container, while the GE version is
2818 flagged in symtable.c as a generator, so it returns the generator object
2819 when the function is called.
2820 This code *knows* that the loop cannot contain break, continue, or return,
2821 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2822
2823 Possible cleanups:
2824 - iterate over the generator sequence instead of using recursion
2825*/
2826
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002828compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002829 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002830 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831{
2832 /* generate code for the iterator, then each of the ifs,
2833 and then write to the element */
2834
Nick Coghlan650f0d02007-04-15 12:05:43 +00002835 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002837 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838
2839 start = compiler_new_block(c);
2840 skip = compiler_new_block(c);
2841 if_cleanup = compiler_new_block(c);
2842 anchor = compiler_new_block(c);
2843
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002844 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002845 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847
Nick Coghlan650f0d02007-04-15 12:05:43 +00002848 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002850 if (gen_index == 0) {
2851 /* Receive outermost iter as an implicit argument */
2852 c->u->u_argcount = 1;
2853 ADDOP_I(c, LOAD_FAST, 0);
2854 }
2855 else {
2856 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002857 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858 ADDOP(c, GET_ITER);
2859 }
2860 compiler_use_next_block(c, start);
2861 ADDOP_JREL(c, FOR_ITER, anchor);
2862 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002863 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002865 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002866 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002868 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002869 VISIT(c, expr, e);
2870 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2871 NEXT_BLOCK(c);
2872 ADDOP(c, POP_TOP);
2873 }
2874
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002875 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002876 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002877 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002878 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002879 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880
Nick Coghlan650f0d02007-04-15 12:05:43 +00002881 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002882 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002883 /* comprehension specific code */
2884 switch (type) {
2885 case COMP_GENEXP:
2886 VISIT(c, expr, elt);
2887 ADDOP(c, YIELD_VALUE);
2888 ADDOP(c, POP_TOP);
2889 break;
2890 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002891 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002892 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002893 break;
2894 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002895 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002896 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002897 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002898 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002899 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002900 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002901 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002902 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002903 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002904 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002905 default:
2906 return 0;
2907 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908
2909 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002910 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911 for (i = 0; i < n; i++) {
2912 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002913 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 compiler_use_next_block(c, if_cleanup);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002915
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916 ADDOP(c, POP_TOP);
2917 }
2918 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2919 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920
2921 return 1;
2922}
2923
2924static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002925compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002926 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002927{
2928 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002929 expr_ty outermost_iter;
2930
2931 outermost_iter = ((comprehension_ty)
2932 asdl_seq_GET(generators, 0))->iter;
2933
2934 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2935 goto error;
2936
2937 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002938 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002939 switch (type) {
2940 case COMP_LISTCOMP:
2941 op = BUILD_LIST;
2942 break;
2943 case COMP_SETCOMP:
2944 op = BUILD_SET;
2945 break;
2946 case COMP_DICTCOMP:
2947 op = BUILD_MAP;
2948 break;
2949 default:
2950 PyErr_Format(PyExc_SystemError,
2951 "unknown comprehension type %d", type);
2952 goto error_in_scope;
2953 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002954
Guido van Rossum992d4a32007-07-11 13:09:30 +00002955 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002956 }
2957
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002958 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002959 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002960 goto error_in_scope;
2961
2962 if (type != COMP_GENEXP) {
2963 ADDOP(c, RETURN_VALUE);
2964 }
2965
2966 co = assemble(c, 1);
2967 compiler_exit_scope(c);
2968 if (co == NULL)
2969 goto error;
2970
2971 if (!compiler_make_closure(c, co, 0))
2972 goto error;
2973 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002974
2975 VISIT(c, expr, outermost_iter);
2976 ADDOP(c, GET_ITER);
2977 ADDOP_I(c, CALL_FUNCTION, 1);
2978 return 1;
2979error_in_scope:
2980 compiler_exit_scope(c);
2981error:
2982 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002983 return 0;
2984}
2985
2986static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987compiler_genexp(struct compiler *c, expr_ty e)
2988{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002989 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002990 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002991 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002992 if (!name)
2993 return 0;
2994 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002995 assert(e->kind == GeneratorExp_kind);
2996 return compiler_comprehension(c, e, COMP_GENEXP, name,
2997 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002998 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999}
3000
3001static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003002compiler_listcomp(struct compiler *c, expr_ty e)
3003{
3004 static identifier name;
3005 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003006 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00003007 if (!name)
3008 return 0;
3009 }
3010 assert(e->kind == ListComp_kind);
3011 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3012 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003013 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003014}
3015
3016static int
3017compiler_setcomp(struct compiler *c, expr_ty e)
3018{
3019 static identifier name;
3020 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003021 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00003022 if (!name)
3023 return 0;
3024 }
3025 assert(e->kind == SetComp_kind);
3026 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3027 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003028 e->v.SetComp.elt, NULL);
3029}
3030
3031
3032static int
3033compiler_dictcomp(struct compiler *c, expr_ty e)
3034{
3035 static identifier name;
3036 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003037 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003038 if (!name)
3039 return 0;
3040 }
3041 assert(e->kind == DictComp_kind);
3042 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3043 e->v.DictComp.generators,
3044 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003045}
3046
3047
3048static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049compiler_visit_keyword(struct compiler *c, keyword_ty k)
3050{
3051 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3052 VISIT(c, expr, k->value);
3053 return 1;
3054}
3055
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003056/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057 whether they are true or false.
3058
3059 Return values: 1 for true, 0 for false, -1 for non-constant.
3060 */
3061
3062static int
3063expr_constant(expr_ty e)
3064{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003065 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003066 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003067 case Ellipsis_kind:
3068 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003069 case Num_kind:
3070 return PyObject_IsTrue(e->v.Num.n);
3071 case Str_kind:
3072 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003073 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003074 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003075 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003076 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003077 if (strcmp(id, "True") == 0) return 1;
3078 if (strcmp(id, "False") == 0) return 0;
3079 if (strcmp(id, "None") == 0) return 0;
3080 if (strcmp(id, "__debug__") == 0)
3081 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003082 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083 default:
3084 return -1;
3085 }
3086}
3087
Guido van Rossumc2e20742006-02-27 22:32:47 +00003088/*
3089 Implements the with statement from PEP 343.
3090
3091 The semantics outlined in that PEP are as follows:
3092
3093 with EXPR as VAR:
3094 BLOCK
3095
3096 It is implemented roughly as:
3097
Thomas Wouters477c8d52006-05-27 19:21:47 +00003098 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003099 exit = context.__exit__ # not calling it
3100 value = context.__enter__()
3101 try:
3102 VAR = value # if VAR present in the syntax
3103 BLOCK
3104 finally:
3105 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003106 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003107 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003108 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003109 exit(*exc)
3110 */
3111static int
3112compiler_with(struct compiler *c, stmt_ty s)
3113{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003114 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003115 basicblock *block, *finally;
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003116 identifier tmpvalue = NULL, tmpexit = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003117
3118 assert(s->kind == With_kind);
3119
Guido van Rossumc2e20742006-02-27 22:32:47 +00003120 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003121 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003122 if (!enter_attr)
3123 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003124 }
3125 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003126 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003127 if (!exit_attr)
3128 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003129 }
3130
3131 block = compiler_new_block(c);
3132 finally = compiler_new_block(c);
3133 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003135
Guido van Rossumc2e20742006-02-27 22:32:47 +00003136 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003137 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003138 We need to do this rather than preserving it on the stack
3139 because SETUP_FINALLY remembers the stack level.
3140 We need to do the assignment *inside* the try/finally
3141 so that context.__exit__() is called when the assignment
3142 fails. But we need to call context.__enter__() *before*
3143 the try/finally so that if it fails we won't call
3144 context.__exit__().
3145 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003146 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003147 if (tmpvalue == NULL)
3148 return 0;
3149 PyArena_AddPyObject(c->c_arena, tmpvalue);
3150 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003151 tmpexit = compiler_new_tmpname(c);
3152 if (tmpexit == NULL)
3153 return 0;
3154 PyArena_AddPyObject(c->c_arena, tmpexit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003155
Thomas Wouters477c8d52006-05-27 19:21:47 +00003156 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003157 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003158
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003159 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003160 ADDOP(c, DUP_TOP);
3161 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003162 if (!compiler_nameop(c, tmpexit, Store))
3163 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003164
3165 /* Call context.__enter__() */
3166 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3167 ADDOP_I(c, CALL_FUNCTION, 0);
3168
3169 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003170 /* Store it in tmpvalue */
3171 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003172 return 0;
3173 }
3174 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003175 /* Discard result from context.__enter__() */
3176 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003177 }
3178
3179 /* Start the try block */
3180 ADDOP_JREL(c, SETUP_FINALLY, finally);
3181
3182 compiler_use_next_block(c, block);
3183 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003184 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003185 }
3186
3187 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003188 /* Bind saved result of context.__enter__() to VAR */
3189 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003190 !compiler_nameop(c, tmpvalue, Del))
3191 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003193 }
3194
3195 /* BLOCK code */
3196 VISIT_SEQ(c, stmt, s->v.With.body);
3197
3198 /* End of try block; start the finally block */
3199 ADDOP(c, POP_BLOCK);
3200 compiler_pop_fblock(c, FINALLY_TRY, block);
3201
3202 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3203 compiler_use_next_block(c, finally);
3204 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003206
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003207 /* Finally block starts; context.__exit__ is on the stack under
3208 the exception or return information. Just issue our magic
3209 opcode. */
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003210 if (!compiler_nameop(c, tmpexit, Load) ||
3211 !compiler_nameop(c, tmpexit, Del))
3212 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003213 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003214
3215 /* Finally block ends. */
3216 ADDOP(c, END_FINALLY);
3217 compiler_pop_fblock(c, FINALLY_END, finally);
3218 return 1;
3219}
3220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221static int
3222compiler_visit_expr(struct compiler *c, expr_ty e)
3223{
3224 int i, n;
3225
Thomas Wouters89f507f2006-12-13 04:49:30 +00003226 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003227 set a new line number for the next instruction.
3228 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229 if (e->lineno > c->u->u_lineno) {
3230 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003231 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 }
3233 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003234 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003236 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237 VISIT(c, expr, e->v.BinOp.left);
3238 VISIT(c, expr, e->v.BinOp.right);
3239 ADDOP(c, binop(c, e->v.BinOp.op));
3240 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003241 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242 VISIT(c, expr, e->v.UnaryOp.operand);
3243 ADDOP(c, unaryop(e->v.UnaryOp.op));
3244 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003245 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003247 case IfExp_kind:
3248 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003249 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003251 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003253 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003254 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003255 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003256 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003257 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258 }
3259 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003260 case Set_kind:
3261 n = asdl_seq_LEN(e->v.Set.elts);
3262 VISIT_SEQ(c, expr, e->v.Set.elts);
3263 ADDOP_I(c, BUILD_SET, n);
3264 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003265 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003267 case ListComp_kind:
3268 return compiler_listcomp(c, e);
3269 case SetComp_kind:
3270 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003271 case DictComp_kind:
3272 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273 case Yield_kind:
3274 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003275 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276 if (e->v.Yield.value) {
3277 VISIT(c, expr, e->v.Yield.value);
3278 }
3279 else {
3280 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3281 }
3282 ADDOP(c, YIELD_VALUE);
3283 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003284 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003286 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003288 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3290 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003291 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3293 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003294 case Bytes_kind:
3295 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003296 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003297 case Ellipsis_kind:
3298 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3299 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003301 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 if (e->v.Attribute.ctx != AugStore)
3303 VISIT(c, expr, e->v.Attribute.value);
3304 switch (e->v.Attribute.ctx) {
3305 case AugLoad:
3306 ADDOP(c, DUP_TOP);
3307 /* Fall through to load */
3308 case Load:
3309 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3310 break;
3311 case AugStore:
3312 ADDOP(c, ROT_TWO);
3313 /* Fall through to save */
3314 case Store:
3315 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3316 break;
3317 case Del:
3318 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3319 break;
3320 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003321 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003322 PyErr_SetString(PyExc_SystemError,
3323 "param invalid in attribute expression");
3324 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 }
3326 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003327 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328 switch (e->v.Subscript.ctx) {
3329 case AugLoad:
3330 VISIT(c, expr, e->v.Subscript.value);
3331 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3332 break;
3333 case Load:
3334 VISIT(c, expr, e->v.Subscript.value);
3335 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3336 break;
3337 case AugStore:
3338 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3339 break;
3340 case Store:
3341 VISIT(c, expr, e->v.Subscript.value);
3342 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3343 break;
3344 case Del:
3345 VISIT(c, expr, e->v.Subscript.value);
3346 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3347 break;
3348 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003349 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003350 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003351 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003352 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353 }
3354 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003355 case Starred_kind:
3356 switch (e->v.Starred.ctx) {
3357 case Store:
3358 /* In all legitimate cases, the Starred node was already replaced
3359 * by compiler_list/compiler_tuple. XXX: is that okay? */
3360 return compiler_error(c,
3361 "starred assignment target must be in a list or tuple");
3362 default:
3363 return compiler_error(c,
3364 "can use starred expression only as assignment target");
3365 }
3366 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003367 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3369 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003370 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003372 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003373 return compiler_tuple(c, e);
3374 }
3375 return 1;
3376}
3377
3378static int
3379compiler_augassign(struct compiler *c, stmt_ty s)
3380{
3381 expr_ty e = s->v.AugAssign.target;
3382 expr_ty auge;
3383
3384 assert(s->kind == AugAssign_kind);
3385
3386 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003387 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003388 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003389 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003390 if (auge == NULL)
3391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392 VISIT(c, expr, auge);
3393 VISIT(c, expr, s->v.AugAssign.value);
3394 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3395 auge->v.Attribute.ctx = AugStore;
3396 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397 break;
3398 case Subscript_kind:
3399 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
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));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003406 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003408 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003409 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003410 if (!compiler_nameop(c, e->v.Name.id, Load))
3411 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003412 VISIT(c, expr, s->v.AugAssign.value);
3413 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3414 return compiler_nameop(c, e->v.Name.id, Store);
3415 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003416 PyErr_Format(PyExc_SystemError,
3417 "invalid node type (%d) for augmented assignment",
3418 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003419 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420 }
3421 return 1;
3422}
3423
3424static int
3425compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3426{
3427 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003428 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3429 PyErr_SetString(PyExc_SystemError,
3430 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003432 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003433 f = &c->u->u_fblock[c->u->u_nfblocks++];
3434 f->fb_type = t;
3435 f->fb_block = b;
3436 return 1;
3437}
3438
3439static void
3440compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3441{
3442 struct compiler_unit *u = c->u;
3443 assert(u->u_nfblocks > 0);
3444 u->u_nfblocks--;
3445 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3446 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3447}
3448
Thomas Wouters89f507f2006-12-13 04:49:30 +00003449static int
3450compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003451 int i;
3452 struct compiler_unit *u = c->u;
3453 for (i = 0; i < u->u_nfblocks; ++i) {
3454 if (u->u_fblock[i].fb_type == LOOP)
3455 return 1;
3456 }
3457 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003458}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459/* Raises a SyntaxError and returns 0.
3460 If something goes wrong, a different exception may be raised.
3461*/
3462
3463static int
3464compiler_error(struct compiler *c, const char *errstr)
3465{
3466 PyObject *loc;
3467 PyObject *u = NULL, *v = NULL;
3468
3469 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3470 if (!loc) {
3471 Py_INCREF(Py_None);
3472 loc = Py_None;
3473 }
3474 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3475 Py_None, loc);
3476 if (!u)
3477 goto exit;
3478 v = Py_BuildValue("(zO)", errstr, u);
3479 if (!v)
3480 goto exit;
3481 PyErr_SetObject(PyExc_SyntaxError, v);
3482 exit:
3483 Py_DECREF(loc);
3484 Py_XDECREF(u);
3485 Py_XDECREF(v);
3486 return 0;
3487}
3488
3489static int
3490compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003491 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 /* XXX this code is duplicated */
3496 switch (ctx) {
3497 case AugLoad: /* fall through to Load */
3498 case Load: op = BINARY_SUBSCR; break;
3499 case AugStore:/* fall through to Store */
3500 case Store: op = STORE_SUBSCR; break;
3501 case Del: op = DELETE_SUBSCR; break;
3502 case Param:
3503 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003504 "invalid %s kind %d in subscript\n",
3505 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506 return 0;
3507 }
3508 if (ctx == AugLoad) {
3509 ADDOP_I(c, DUP_TOPX, 2);
3510 }
3511 else if (ctx == AugStore) {
3512 ADDOP(c, ROT_THREE);
3513 }
3514 ADDOP(c, op);
3515 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516}
3517
3518static int
3519compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3520{
3521 int n = 2;
3522 assert(s->kind == Slice_kind);
3523
3524 /* only handles the cases where BUILD_SLICE is emitted */
3525 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003526 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 }
3528 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003529 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003533 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 }
3535 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003536 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537 }
3538
3539 if (s->v.Slice.step) {
3540 n++;
3541 VISIT(c, expr, s->v.Slice.step);
3542 }
3543 ADDOP_I(c, BUILD_SLICE, n);
3544 return 1;
3545}
3546
3547static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3549 expr_context_ty ctx)
3550{
3551 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 case Slice_kind:
3553 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 case Index_kind:
3555 VISIT(c, expr, s->v.Index.value);
3556 break;
3557 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003558 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003559 PyErr_SetString(PyExc_SystemError,
3560 "extended slice invalid in nested slice");
3561 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 }
3563 return 1;
3564}
3565
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566static int
3567compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3568{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003569 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003571 case Index_kind:
3572 kindname = "index";
3573 if (ctx != AugStore) {
3574 VISIT(c, expr, s->v.Index.value);
3575 }
3576 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003578 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003579 if (ctx != AugStore) {
3580 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581 return 0;
3582 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003583 break;
3584 case ExtSlice_kind:
3585 kindname = "extended slice";
3586 if (ctx != AugStore) {
3587 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3588 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003589 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003590 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003591 if (!compiler_visit_nested_slice(c, sub, ctx))
3592 return 0;
3593 }
3594 ADDOP_I(c, BUILD_TUPLE, n);
3595 }
3596 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003597 default:
3598 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003599 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003600 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003602 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003603}
3604
Thomas Wouters89f507f2006-12-13 04:49:30 +00003605/* End of the compiler section, beginning of the assembler section */
3606
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607/* do depth-first search of basic block graph, starting with block.
3608 post records the block indices in post-order.
3609
3610 XXX must handle implicit jumps from one block to next
3611*/
3612
Thomas Wouters89f507f2006-12-13 04:49:30 +00003613struct assembler {
3614 PyObject *a_bytecode; /* string containing bytecode */
3615 int a_offset; /* offset into bytecode */
3616 int a_nblocks; /* number of reachable blocks */
3617 basicblock **a_postorder; /* list of blocks in dfs postorder */
3618 PyObject *a_lnotab; /* string containing lnotab */
3619 int a_lnotab_off; /* offset into lnotab */
3620 int a_lineno; /* last lineno of emitted instruction */
3621 int a_lineno_off; /* bytecode offset of last lineno */
3622};
3623
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624static void
3625dfs(struct compiler *c, basicblock *b, struct assembler *a)
3626{
3627 int i;
3628 struct instr *instr = NULL;
3629
3630 if (b->b_seen)
3631 return;
3632 b->b_seen = 1;
3633 if (b->b_next != NULL)
3634 dfs(c, b->b_next, a);
3635 for (i = 0; i < b->b_iused; i++) {
3636 instr = &b->b_instr[i];
3637 if (instr->i_jrel || instr->i_jabs)
3638 dfs(c, instr->i_target, a);
3639 }
3640 a->a_postorder[a->a_nblocks++] = b;
3641}
3642
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003643static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3645{
3646 int i;
3647 struct instr *instr;
3648 if (b->b_seen || b->b_startdepth >= depth)
3649 return maxdepth;
3650 b->b_seen = 1;
3651 b->b_startdepth = depth;
3652 for (i = 0; i < b->b_iused; i++) {
3653 instr = &b->b_instr[i];
3654 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3655 if (depth > maxdepth)
3656 maxdepth = depth;
3657 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3658 if (instr->i_jrel || instr->i_jabs) {
3659 maxdepth = stackdepth_walk(c, instr->i_target,
3660 depth, maxdepth);
3661 if (instr->i_opcode == JUMP_ABSOLUTE ||
3662 instr->i_opcode == JUMP_FORWARD) {
3663 goto out; /* remaining code is dead */
3664 }
3665 }
3666 }
3667 if (b->b_next)
3668 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3669out:
3670 b->b_seen = 0;
3671 return maxdepth;
3672}
3673
3674/* Find the flow path that needs the largest stack. We assume that
3675 * cycles in the flow graph have no net effect on the stack depth.
3676 */
3677static int
3678stackdepth(struct compiler *c)
3679{
3680 basicblock *b, *entryblock;
3681 entryblock = NULL;
3682 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3683 b->b_seen = 0;
3684 b->b_startdepth = INT_MIN;
3685 entryblock = b;
3686 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003687 if (!entryblock)
3688 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689 return stackdepth_walk(c, entryblock, 0, 0);
3690}
3691
3692static int
3693assemble_init(struct assembler *a, int nblocks, int firstlineno)
3694{
3695 memset(a, 0, sizeof(struct assembler));
3696 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003697 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698 if (!a->a_bytecode)
3699 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003700 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003701 if (!a->a_lnotab)
3702 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003703 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3704 PyErr_NoMemory();
3705 return 0;
3706 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003707 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003708 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003709 if (!a->a_postorder) {
3710 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003711 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003712 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713 return 1;
3714}
3715
3716static void
3717assemble_free(struct assembler *a)
3718{
3719 Py_XDECREF(a->a_bytecode);
3720 Py_XDECREF(a->a_lnotab);
3721 if (a->a_postorder)
3722 PyObject_Free(a->a_postorder);
3723}
3724
3725/* Return the size of a basic block in bytes. */
3726
3727static int
3728instrsize(struct instr *instr)
3729{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003730 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003731 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003732 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003733 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3734 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735}
3736
3737static int
3738blocksize(basicblock *b)
3739{
3740 int i;
3741 int size = 0;
3742
3743 for (i = 0; i < b->b_iused; i++)
3744 size += instrsize(&b->b_instr[i]);
3745 return size;
3746}
3747
3748/* All about a_lnotab.
3749
3750c_lnotab is an array of unsigned bytes disguised as a Python string.
3751It is used to map bytecode offsets to source code line #s (when needed
3752for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003753
Tim Peters2a7f3842001-06-09 09:26:21 +00003754The array is conceptually a list of
3755 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003756pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003757
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003758 byte code offset source code line number
3759 0 1
3760 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003761 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003762 350 307
3763 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003764
3765The first trick is that these numbers aren't stored, only the increments
3766from one row to the next (this doesn't really work, but it's a start):
3767
3768 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3769
3770The second trick is that an unsigned byte can't hold negative values, or
3771values larger than 255, so (a) there's a deep assumption that byte code
3772offsets and their corresponding line #s both increase monotonically, and (b)
3773if at least one column jumps by more than 255 from one row to the next, more
3774than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003775from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003776part. A user of c_lnotab desiring to find the source line number
3777corresponding to a bytecode address A should do something like this
3778
3779 lineno = addr = 0
3780 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003781 addr += addr_incr
3782 if addr > A:
3783 return lineno
3784 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003785
3786In order for this to work, when the addr field increments by more than 255,
3787the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003788increment is < 256. So, in the example above, assemble_lnotab (it used
3789to be called com_set_lineno) should not (as was actually done until 2.2)
3790expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003791 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003792*/
3793
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003794static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003796{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797 int d_bytecode, d_lineno;
3798 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003799 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800
3801 d_bytecode = a->a_offset - a->a_lineno_off;
3802 d_lineno = i->i_lineno - a->a_lineno;
3803
3804 assert(d_bytecode >= 0);
3805 assert(d_lineno >= 0);
3806
Christian Heimes2202f872008-02-06 14:31:34 +00003807 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003808 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003811 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003813 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003815 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003816 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003817 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003819 else {
3820 PyErr_NoMemory();
3821 return 0;
3822 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003823 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003825 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003826 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003827 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003828 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829 *lnotab++ = 255;
3830 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003831 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832 d_bytecode -= ncodes * 255;
3833 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003834 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 assert(d_bytecode <= 255);
3836 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003837 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003839 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003841 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003843 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003845 else {
3846 PyErr_NoMemory();
3847 return 0;
3848 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003849 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003851 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003852 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003853 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003855 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003856 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003857 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003858 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003859 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003860 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 d_lineno -= ncodes * 255;
3862 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003863 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003864
Christian Heimes72b710a2008-05-26 13:28:38 +00003865 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003866 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003867 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003868 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003869 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003870 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003871 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003872
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 a->a_lnotab_off += 2;
3874 if (d_bytecode) {
3875 *lnotab++ = d_bytecode;
3876 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003877 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003878 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003879 *lnotab++ = 0;
3880 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003881 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882 a->a_lineno = i->i_lineno;
3883 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003884 return 1;
3885}
3886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887/* assemble_emit()
3888 Extend the bytecode with a new instruction.
3889 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003890*/
3891
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003892static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003894{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003895 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003896 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897 char *code;
3898
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003899 size = instrsize(i);
3900 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003902 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003903 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003905 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003907 if (len > PY_SSIZE_T_MAX / 2)
3908 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003909 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003910 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003911 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003912 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003914 if (size == 6) {
3915 assert(i->i_hasarg);
3916 *code++ = (char)EXTENDED_ARG;
3917 *code++ = ext & 0xff;
3918 *code++ = ext >> 8;
3919 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003920 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003922 if (i->i_hasarg) {
3923 assert(size == 3 || size == 6);
3924 *code++ = arg & 0xff;
3925 *code++ = arg >> 8;
3926 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003928}
3929
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003930static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003931assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003932{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003934 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003935 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003937 /* Compute the size of each block and fixup jump args.
3938 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003939start:
3940 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003941 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003942 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003943 bsize = blocksize(b);
3944 b->b_offset = totsize;
3945 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003946 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003947 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003948 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3949 bsize = b->b_offset;
3950 for (i = 0; i < b->b_iused; i++) {
3951 struct instr *instr = &b->b_instr[i];
3952 /* Relative jumps are computed relative to
3953 the instruction pointer after fetching
3954 the jump instruction.
3955 */
3956 bsize += instrsize(instr);
3957 if (instr->i_jabs)
3958 instr->i_oparg = instr->i_target->b_offset;
3959 else if (instr->i_jrel) {
3960 int delta = instr->i_target->b_offset - bsize;
3961 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003962 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003963 else
3964 continue;
3965 if (instr->i_oparg > 0xffff)
3966 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003967 }
3968 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003969
3970 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003971 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003972 with a better solution.
3973
3974 In the meantime, should the goto be dropped in favor
3975 of a loop?
3976
3977 The issue is that in the first loop blocksize() is called
3978 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003979 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003980 i_oparg is calculated in the second loop above.
3981
3982 So we loop until we stop seeing new EXTENDED_ARGs.
3983 The only EXTENDED_ARGs that could be popping up are
3984 ones in jump instructions. So this should converge
3985 fairly quickly.
3986 */
3987 if (last_extended_arg_count != extended_arg_count) {
3988 last_extended_arg_count = extended_arg_count;
3989 goto start;
3990 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003991}
3992
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003993static PyObject *
3994dict_keys_inorder(PyObject *dict, int offset)
3995{
3996 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003997 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003998
3999 tuple = PyTuple_New(size);
4000 if (tuple == NULL)
4001 return NULL;
4002 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00004003 i = PyLong_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004004 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004005 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004006 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004007 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004008 PyTuple_SET_ITEM(tuple, i - offset, k);
4009 }
4010 return tuple;
4011}
4012
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004013static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004014compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004015{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004016 PySTEntryObject *ste = c->u->u_ste;
4017 int flags = 0, n;
4018 if (ste->ste_type != ModuleBlock)
4019 flags |= CO_NEWLOCALS;
4020 if (ste->ste_type == FunctionBlock) {
4021 if (!ste->ste_unoptimized)
4022 flags |= CO_OPTIMIZED;
4023 if (ste->ste_nested)
4024 flags |= CO_NESTED;
4025 if (ste->ste_generator)
4026 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004027 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028 if (ste->ste_varargs)
4029 flags |= CO_VARARGS;
4030 if (ste->ste_varkeywords)
4031 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004032 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004033 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004034
4035 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004036 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004037
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004038 n = PyDict_Size(c->u->u_freevars);
4039 if (n < 0)
4040 return -1;
4041 if (n == 0) {
4042 n = PyDict_Size(c->u->u_cellvars);
4043 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004044 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004045 if (n == 0) {
4046 flags |= CO_NOFREE;
4047 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004048 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004049
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004050 return flags;
4051}
4052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004053static PyCodeObject *
4054makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004055{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004056 PyObject *tmp;
4057 PyCodeObject *co = NULL;
4058 PyObject *consts = NULL;
4059 PyObject *names = NULL;
4060 PyObject *varnames = NULL;
4061 PyObject *filename = NULL;
4062 PyObject *name = NULL;
4063 PyObject *freevars = NULL;
4064 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004065 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004067
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068 tmp = dict_keys_inorder(c->u->u_consts, 0);
4069 if (!tmp)
4070 goto error;
4071 consts = PySequence_List(tmp); /* optimize_code requires a list */
4072 Py_DECREF(tmp);
4073
4074 names = dict_keys_inorder(c->u->u_names, 0);
4075 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4076 if (!consts || !names || !varnames)
4077 goto error;
4078
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004079 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4080 if (!cellvars)
4081 goto error;
4082 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4083 if (!freevars)
4084 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004085 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004086 if (!filename)
4087 goto error;
4088
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004089 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090 flags = compute_code_flags(c);
4091 if (flags < 0)
4092 goto error;
4093
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004094 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004095 if (!bytecode)
4096 goto error;
4097
4098 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4099 if (!tmp)
4100 goto error;
4101 Py_DECREF(consts);
4102 consts = tmp;
4103
Guido van Rossum4f72a782006-10-27 23:31:49 +00004104 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4105 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004106 bytecode, consts, names, varnames,
4107 freevars, cellvars,
4108 filename, c->u->u_name,
4109 c->u->u_firstlineno,
4110 a->a_lnotab);
4111 error:
4112 Py_XDECREF(consts);
4113 Py_XDECREF(names);
4114 Py_XDECREF(varnames);
4115 Py_XDECREF(filename);
4116 Py_XDECREF(name);
4117 Py_XDECREF(freevars);
4118 Py_XDECREF(cellvars);
4119 Py_XDECREF(bytecode);
4120 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004121}
4122
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004123
4124/* For debugging purposes only */
4125#if 0
4126static void
4127dump_instr(const struct instr *i)
4128{
4129 const char *jrel = i->i_jrel ? "jrel " : "";
4130 const char *jabs = i->i_jabs ? "jabs " : "";
4131 char arg[128];
4132
4133 *arg = '\0';
4134 if (i->i_hasarg)
4135 sprintf(arg, "arg: %d ", i->i_oparg);
4136
4137 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4138 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4139}
4140
4141static void
4142dump_basicblock(const basicblock *b)
4143{
4144 const char *seen = b->b_seen ? "seen " : "";
4145 const char *b_return = b->b_return ? "return " : "";
4146 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4147 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4148 if (b->b_instr) {
4149 int i;
4150 for (i = 0; i < b->b_iused; i++) {
4151 fprintf(stderr, " [%02d] ", i);
4152 dump_instr(b->b_instr + i);
4153 }
4154 }
4155}
4156#endif
4157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158static PyCodeObject *
4159assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004160{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161 basicblock *b, *entryblock;
4162 struct assembler a;
4163 int i, j, nblocks;
4164 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004165
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166 /* Make sure every block that falls off the end returns None.
4167 XXX NEXT_BLOCK() isn't quite right, because if the last
4168 block ends with a jump or return b_next shouldn't set.
4169 */
4170 if (!c->u->u_curblock->b_return) {
4171 NEXT_BLOCK(c);
4172 if (addNone)
4173 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4174 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004175 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004176
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177 nblocks = 0;
4178 entryblock = NULL;
4179 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4180 nblocks++;
4181 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004182 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004183
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004184 /* Set firstlineno if it wasn't explicitly set. */
4185 if (!c->u->u_firstlineno) {
4186 if (entryblock && entryblock->b_instr)
4187 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4188 else
4189 c->u->u_firstlineno = 1;
4190 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4192 goto error;
4193 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004196 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198 /* Emit code in reverse postorder from dfs. */
4199 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004200 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201 for (j = 0; j < b->b_iused; j++)
4202 if (!assemble_emit(&a, &b->b_instr[j]))
4203 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004204 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004205
Christian Heimes72b710a2008-05-26 13:28:38 +00004206 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004207 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004208 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004209 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 co = makecode(c, &a);
4212 error:
4213 assemble_free(&a);
4214 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004215}