blob: 2c58d449b5e24cbeeff8c14aecaa1918f849e65e [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 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
121 int u_nfblocks;
122 struct fblockinfo u_fblock[CO_MAXBLOCKS];
123
124 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000125 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000126 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127 has been generated with current lineno */
128};
129
130/* This struct captures the global state of a compilation.
131
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000132The u pointer points to the current compilation unit, while units
133for enclosing blocks are stored in c_stack. The u and c_stack are
134managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135*/
136
137struct compiler {
138 const char *c_filename;
139 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141 PyCompilerFlags *c_flags;
142
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146 struct compiler_unit *u; /* compiler state for current block */
147 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000148 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149};
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151static int compiler_enter_scope(struct compiler *, identifier, void *, int);
152static void compiler_free(struct compiler *);
153static basicblock *compiler_new_block(struct compiler *);
154static int compiler_next_instr(struct compiler *, basicblock *);
155static int compiler_addop(struct compiler *, int);
156static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
157static int compiler_addop_i(struct compiler *, int, int);
158static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159static basicblock *compiler_use_new_block(struct compiler *);
160static int compiler_error(struct compiler *, const char *);
161static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
162
163static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
164static int compiler_visit_stmt(struct compiler *, stmt_ty);
165static int compiler_visit_keyword(struct compiler *, keyword_ty);
166static int compiler_visit_expr(struct compiler *, expr_ty);
167static int compiler_augassign(struct compiler *, stmt_ty);
168static int compiler_visit_slice(struct compiler *, slice_ty,
169 expr_context_ty);
170
171static int compiler_push_fblock(struct compiler *, enum fblocktype,
172 basicblock *);
173static void compiler_pop_fblock(struct compiler *, enum fblocktype,
174 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175/* Returns true if there is a loop on the fblock stack. */
176static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177
178static int inplace_binop(struct compiler *, operator_ty);
179static int expr_constant(expr_ty e);
180
Guido van Rossumc2e20742006-02-27 22:32:47 +0000181static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000182static int compiler_call_helper(struct compiler *c, int n,
183 asdl_seq *args,
184 asdl_seq *keywords,
185 expr_ty starargs,
186 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static PyCodeObject *assemble(struct compiler *, int addNone);
189static PyObject *__doc__;
190
Benjamin Petersonb173f782009-05-05 22:31:58 +0000191#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193PyObject *
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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 co = compiler_mod(&c, mod);
297
Thomas Wouters1175c432006-02-27 22:49:54 +0000298 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000300 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301 return co;
302}
303
304PyCodeObject *
305PyNode_Compile(struct _node *n, const char *filename)
306{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000307 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000308 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000309 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000310 if (!arena)
311 return NULL;
312 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000313 if (mod)
314 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000315 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000316 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000317}
318
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000319static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000321{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322 if (c->c_st)
323 PySymtable_Free(c->c_st);
324 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000325 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000327}
328
Guido van Rossum79f25d91997-04-29 20:08:16 +0000329static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000330list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000331{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000332 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000333 PyObject *v, *k;
334 PyObject *dict = PyDict_New();
335 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000336
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337 n = PyList_Size(list);
338 for (i = 0; i < n; i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000339 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340 if (!v) {
341 Py_DECREF(dict);
342 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000343 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000344 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000345 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000346 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
347 Py_XDECREF(k);
348 Py_DECREF(v);
349 Py_DECREF(dict);
350 return NULL;
351 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000352 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000354 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355 return dict;
356}
357
358/* Return new dict containing names from src that match scope(s).
359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360src is a symbol table dictionary. If the scope of a name matches
361either scope_type or flag is set, insert it into the new dict. The
362values are integers, starting at offset and increasing by one for
363each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000364*/
365
366static PyObject *
367dictbytype(PyObject *src, int scope_type, int flag, int offset)
368{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000369 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370 PyObject *k, *v, *dest = PyDict_New();
371
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000372 assert(offset >= 0);
373 if (dest == NULL)
374 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375
376 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000378 long vi;
Christian Heimes217cfd12007-12-02 14:31:20 +0000379 assert(PyLong_Check(v));
380 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000381 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000383 if (scope == scope_type || vi & flag) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000384 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000385 if (item == NULL) {
386 Py_DECREF(dest);
387 return NULL;
388 }
389 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000390 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000391 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
392 Py_DECREF(item);
393 Py_DECREF(dest);
394 Py_XDECREF(tuple);
395 return NULL;
396 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000397 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000398 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400 }
401 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000402}
403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404static void
405compiler_unit_check(struct compiler_unit *u)
406{
407 basicblock *block;
408 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Christian Heimes77c02eb2008-02-09 02:18:51 +0000409 assert((void *)block != (void *)0xcbcbcbcb);
410 assert((void *)block != (void *)0xfbfbfbfb);
411 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412 if (block->b_instr != NULL) {
413 assert(block->b_ialloc > 0);
414 assert(block->b_iused > 0);
415 assert(block->b_ialloc >= block->b_iused);
416 }
417 else {
418 assert (block->b_iused == 0);
419 assert (block->b_ialloc == 0);
420 }
421 }
422}
423
424static void
425compiler_unit_free(struct compiler_unit *u)
426{
427 basicblock *b, *next;
428
429 compiler_unit_check(u);
430 b = u->u_blocks;
431 while (b != NULL) {
432 if (b->b_instr)
433 PyObject_Free((void *)b->b_instr);
434 next = b->b_list;
435 PyObject_Free((void *)b);
436 b = next;
437 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000438 Py_CLEAR(u->u_ste);
439 Py_CLEAR(u->u_name);
440 Py_CLEAR(u->u_consts);
441 Py_CLEAR(u->u_names);
442 Py_CLEAR(u->u_varnames);
443 Py_CLEAR(u->u_freevars);
444 Py_CLEAR(u->u_cellvars);
445 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000446 PyObject_Free(u);
447}
448
449static int
450compiler_enter_scope(struct compiler *c, identifier name, void *key,
451 int lineno)
452{
453 struct compiler_unit *u;
454
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000455 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000456 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000457 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000458 PyErr_NoMemory();
459 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000460 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000462 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000463 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464 u->u_ste = PySymtable_Lookup(c->c_st, key);
465 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000466 compiler_unit_free(u);
467 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468 }
469 Py_INCREF(name);
470 u->u_name = name;
471 u->u_varnames = list2dict(u->u_ste->ste_varnames);
472 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000473 if (!u->u_varnames || !u->u_cellvars) {
474 compiler_unit_free(u);
475 return 0;
476 }
477
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000479 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000480 if (!u->u_freevars) {
481 compiler_unit_free(u);
482 return 0;
483 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484
485 u->u_blocks = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000486 u->u_nfblocks = 0;
487 u->u_firstlineno = lineno;
488 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000489 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490 u->u_consts = PyDict_New();
491 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000492 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493 return 0;
494 }
495 u->u_names = PyDict_New();
496 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000497 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498 return 0;
499 }
500
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000501 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502
503 /* Push the old compiler_unit on the stack. */
504 if (c->u) {
Benjamin Petersonb173f782009-05-05 22:31:58 +0000505 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
506 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
507 Py_XDECREF(capsule);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000508 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 return 0;
510 }
Benjamin Petersonb173f782009-05-05 22:31:58 +0000511 Py_DECREF(capsule);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 u->u_private = c->u->u_private;
513 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000514 }
515 c->u = u;
516
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000517 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000518 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519 return 0;
520
521 return 1;
522}
523
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525compiler_exit_scope(struct compiler *c)
526{
527 int n;
Benjamin Petersonb173f782009-05-05 22:31:58 +0000528 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000530 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531 compiler_unit_free(c->u);
532 /* Restore c->u to the parent unit. */
533 n = PyList_GET_SIZE(c->c_stack) - 1;
534 if (n >= 0) {
Benjamin Petersonb173f782009-05-05 22:31:58 +0000535 capsule = PyList_GET_ITEM(c->c_stack, n);
536 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000537 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000538 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000539 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000540 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541 compiler_unit_check(c->u);
542 }
543 else
544 c->u = NULL;
545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546}
547
548/* Allocate a new block and return a pointer to it.
549 Returns NULL on error.
550*/
551
552static basicblock *
553compiler_new_block(struct compiler *c)
554{
555 basicblock *b;
556 struct compiler_unit *u;
557
558 u = c->u;
559 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000560 if (b == NULL) {
561 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000563 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000565 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566 b->b_list = u->u_blocks;
567 u->u_blocks = b;
568 return b;
569}
570
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000571static basicblock *
572compiler_use_new_block(struct compiler *c)
573{
574 basicblock *block = compiler_new_block(c);
575 if (block == NULL)
576 return NULL;
577 c->u->u_curblock = block;
578 return block;
579}
580
581static basicblock *
582compiler_next_block(struct compiler *c)
583{
584 basicblock *block = compiler_new_block(c);
585 if (block == NULL)
586 return NULL;
587 c->u->u_curblock->b_next = block;
588 c->u->u_curblock = block;
589 return block;
590}
591
592static basicblock *
593compiler_use_next_block(struct compiler *c, basicblock *block)
594{
595 assert(block != NULL);
596 c->u->u_curblock->b_next = block;
597 c->u->u_curblock = block;
598 return block;
599}
600
601/* Returns the offset of the next instruction in the current block's
602 b_instr array. Resizes the b_instr as necessary.
603 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
606static int
607compiler_next_instr(struct compiler *c, basicblock *b)
608{
609 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000610 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000612 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613 if (b->b_instr == NULL) {
614 PyErr_NoMemory();
615 return -1;
616 }
617 b->b_ialloc = DEFAULT_BLOCK_SIZE;
618 memset((char *)b->b_instr, 0,
619 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000622 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623 size_t oldsize, newsize;
624 oldsize = b->b_ialloc * sizeof(struct instr);
625 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000626
627 if (oldsize > (PY_SIZE_MAX >> 1)) {
628 PyErr_NoMemory();
629 return -1;
630 }
631
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632 if (newsize == 0) {
633 PyErr_NoMemory();
634 return -1;
635 }
636 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000637 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639 if (tmp == NULL) {
640 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000641 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000642 }
643 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
645 }
646 return b->b_iused++;
647}
648
Christian Heimes2202f872008-02-06 14:31:34 +0000649/* Set the i_lineno member of the instruction at offset off if the
650 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000651 already been set. If it has been set, the call has no effect.
652
Christian Heimes2202f872008-02-06 14:31:34 +0000653 The line number is reset in the following cases:
654 - when entering a new scope
655 - on each statement
656 - on each expression that start a new line
657 - before the "except" clause
658 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000660
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000661static void
662compiler_set_lineno(struct compiler *c, int off)
663{
664 basicblock *b;
665 if (c->u->u_lineno_set)
666 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000667 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000669 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
672static int
673opcode_stack_effect(int opcode, int oparg)
674{
675 switch (opcode) {
676 case POP_TOP:
677 return -1;
678 case ROT_TWO:
679 case ROT_THREE:
680 return 0;
681 case DUP_TOP:
682 return 1;
683 case ROT_FOUR:
684 return 0;
685
686 case UNARY_POSITIVE:
687 case UNARY_NEGATIVE:
688 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000689 case UNARY_INVERT:
690 return 0;
691
Nick Coghlan650f0d02007-04-15 12:05:43 +0000692 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000693 case LIST_APPEND:
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000694 return -1;
695 case MAP_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000696 return -2;
697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000698 case BINARY_POWER:
699 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000700 case BINARY_MODULO:
701 case BINARY_ADD:
702 case BINARY_SUBTRACT:
703 case BINARY_SUBSCR:
704 case BINARY_FLOOR_DIVIDE:
705 case BINARY_TRUE_DIVIDE:
706 return -1;
707 case INPLACE_FLOOR_DIVIDE:
708 case INPLACE_TRUE_DIVIDE:
709 return -1;
710
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000711 case INPLACE_ADD:
712 case INPLACE_SUBTRACT:
713 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714 case INPLACE_MODULO:
715 return -1;
716 case STORE_SUBSCR:
717 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000718 case STORE_MAP:
719 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000720 case DELETE_SUBSCR:
721 return -2;
722
723 case BINARY_LSHIFT:
724 case BINARY_RSHIFT:
725 case BINARY_AND:
726 case BINARY_XOR:
727 case BINARY_OR:
728 return -1;
729 case INPLACE_POWER:
730 return -1;
731 case GET_ITER:
732 return 0;
733
734 case PRINT_EXPR:
735 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000736 case LOAD_BUILD_CLASS:
737 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000738 case INPLACE_LSHIFT:
739 case INPLACE_RSHIFT:
740 case INPLACE_AND:
741 case INPLACE_XOR:
742 case INPLACE_OR:
743 return -1;
744 case BREAK_LOOP:
745 return 0;
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000746 case SETUP_WITH:
747 return 7;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000748 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000749 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000750 case STORE_LOCALS:
751 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752 case RETURN_VALUE:
753 return -1;
754 case IMPORT_STAR:
755 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756 case YIELD_VALUE:
757 return 0;
758
759 case POP_BLOCK:
760 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000761 case POP_EXCEPT:
762 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763 case END_FINALLY:
764 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765
766 case STORE_NAME:
767 return -1;
768 case DELETE_NAME:
769 return 0;
770 case UNPACK_SEQUENCE:
771 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000772 case UNPACK_EX:
773 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774 case FOR_ITER:
Neil Schemenauere441cb72009-10-14 19:14:38 +0000775 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776
777 case STORE_ATTR:
778 return -2;
779 case DELETE_ATTR:
780 return -1;
781 case STORE_GLOBAL:
782 return -1;
783 case DELETE_GLOBAL:
784 return 0;
785 case DUP_TOPX:
786 return oparg;
787 case LOAD_CONST:
788 return 1;
789 case LOAD_NAME:
790 return 1;
791 case BUILD_TUPLE:
792 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000793 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794 return 1-oparg;
795 case BUILD_MAP:
796 return 1;
797 case LOAD_ATTR:
798 return 0;
799 case COMPARE_OP:
800 return -1;
801 case IMPORT_NAME:
Neil Schemenauere441cb72009-10-14 19:14:38 +0000802 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000803 case IMPORT_FROM:
804 return 1;
805
806 case JUMP_FORWARD:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000807 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
808 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000809 case JUMP_ABSOLUTE:
810 return 0;
811
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000812 case POP_JUMP_IF_FALSE:
813 case POP_JUMP_IF_TRUE:
814 return -1;
815
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816 case LOAD_GLOBAL:
817 return 1;
818
819 case CONTINUE_LOOP:
820 return 0;
821 case SETUP_LOOP:
822 return 0;
823 case SETUP_EXCEPT:
824 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000825 return 6; /* can push 3 values for the new exception
826 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827
828 case LOAD_FAST:
829 return 1;
830 case STORE_FAST:
831 return -1;
832 case DELETE_FAST:
833 return 0;
834
835 case RAISE_VARARGS:
836 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000837#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838 case CALL_FUNCTION:
839 return -NARGS(oparg);
840 case CALL_FUNCTION_VAR:
841 case CALL_FUNCTION_KW:
842 return -NARGS(oparg)-1;
843 case CALL_FUNCTION_VAR_KW:
844 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000846 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000847 case MAKE_CLOSURE:
848 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000849#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000850 case BUILD_SLICE:
851 if (oparg == 3)
852 return -2;
853 else
854 return -1;
855
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856 case LOAD_CLOSURE:
857 return 1;
858 case LOAD_DEREF:
859 return 1;
860 case STORE_DEREF:
861 return -1;
862 default:
863 fprintf(stderr, "opcode = %d\n", opcode);
864 Py_FatalError("opcode_stack_effect()");
865
866 }
867 return 0; /* not reachable */
868}
869
870/* Add an opcode with no argument.
871 Returns 0 on failure, 1 on success.
872*/
873
874static int
875compiler_addop(struct compiler *c, int opcode)
876{
877 basicblock *b;
878 struct instr *i;
879 int off;
880 off = compiler_next_instr(c, c->u->u_curblock);
881 if (off < 0)
882 return 0;
883 b = c->u->u_curblock;
884 i = &b->b_instr[off];
885 i->i_opcode = opcode;
886 i->i_hasarg = 0;
887 if (opcode == RETURN_VALUE)
888 b->b_return = 1;
889 compiler_set_lineno(c, off);
890 return 1;
891}
892
893static int
894compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
895{
896 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000897 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000898 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000900 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000901 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
902 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000903 d = PyFloat_AS_DOUBLE(o);
Christian Heimes400adb02008-02-01 08:12:03 +0000904 /* all we need is to make the tuple different in either the 0.0
905 * or -0.0 case from all others, just to avoid the "coercion".
906 */
Mark Dickinsona73ef2f2009-11-28 16:38:16 +0000907 if (d == 0.0 && copysign(1.0, d) < 0.0)
Christian Heimes400adb02008-02-01 08:12:03 +0000908 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
909 else
910 t = PyTuple_Pack(2, o, o->ob_type);
911 }
912 else if (PyComplex_Check(o)) {
Mark Dickinson42e30552009-10-15 19:55:18 +0000913 Py_complex z;
Mark Dickinsona73ef2f2009-11-28 16:38:16 +0000914 int real_negzero, imag_negzero;
915 /* For the complex case we must make complex(x, 0.)
916 different from complex(x, -0.) and complex(0., y)
917 different from complex(-0., y), for any x and y.
918 All four complex zeros must be distinguished.*/
Christian Heimes400adb02008-02-01 08:12:03 +0000919 z = PyComplex_AsCComplex(o);
Mark Dickinsona73ef2f2009-11-28 16:38:16 +0000920 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
921 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
922 if (real_negzero && imag_negzero) {
923 t = PyTuple_Pack(5, o, o->ob_type,
924 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000925 }
Mark Dickinsona73ef2f2009-11-28 16:38:16 +0000926 else if (imag_negzero) {
927 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000928 }
Mark Dickinsona73ef2f2009-11-28 16:38:16 +0000929 else if (real_negzero) {
930 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000931 }
932 else {
933 t = PyTuple_Pack(2, o, o->ob_type);
934 }
935 }
936 else {
937 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000938 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000939 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000940 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941
942 v = PyDict_GetItem(dict, t);
943 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000944 if (PyErr_Occurred())
945 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000947 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948 if (!v) {
949 Py_DECREF(t);
950 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000951 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952 if (PyDict_SetItem(dict, t, v) < 0) {
953 Py_DECREF(t);
954 Py_DECREF(v);
955 return -1;
956 }
957 Py_DECREF(v);
958 }
959 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000960 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000962 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963}
964
965static int
966compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
967 PyObject *o)
968{
969 int arg = compiler_add_o(c, dict, o);
970 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000971 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 return compiler_addop_i(c, opcode, arg);
973}
974
975static int
976compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000977 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978{
979 int arg;
980 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
981 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983 arg = compiler_add_o(c, dict, mangled);
984 Py_DECREF(mangled);
985 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987 return compiler_addop_i(c, opcode, arg);
988}
989
990/* Add an opcode with an integer argument.
991 Returns 0 on failure, 1 on success.
992*/
993
994static int
995compiler_addop_i(struct compiler *c, int opcode, int oparg)
996{
997 struct instr *i;
998 int off;
999 off = compiler_next_instr(c, c->u->u_curblock);
1000 if (off < 0)
1001 return 0;
1002 i = &c->u->u_curblock->b_instr[off];
1003 i->i_opcode = opcode;
1004 i->i_oparg = oparg;
1005 i->i_hasarg = 1;
1006 compiler_set_lineno(c, off);
1007 return 1;
1008}
1009
1010static int
1011compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1012{
1013 struct instr *i;
1014 int off;
1015
1016 assert(b != NULL);
1017 off = compiler_next_instr(c, c->u->u_curblock);
1018 if (off < 0)
1019 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020 i = &c->u->u_curblock->b_instr[off];
1021 i->i_opcode = opcode;
1022 i->i_target = b;
1023 i->i_hasarg = 1;
1024 if (absolute)
1025 i->i_jabs = 1;
1026 else
1027 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001028 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029 return 1;
1030}
1031
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001032/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1033 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034 it as the current block. NEXT_BLOCK() also creates an implicit jump
1035 from the current block to the new block.
1036*/
1037
Thomas Wouters89f507f2006-12-13 04:49:30 +00001038/* The returns inside these macros make it impossible to decref objects
1039 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040*/
1041
1042
1043#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001044 if (compiler_use_new_block((C)) == NULL) \
1045 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046}
1047
1048#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001049 if (compiler_next_block((C)) == NULL) \
1050 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051}
1052
1053#define ADDOP(C, OP) { \
1054 if (!compiler_addop((C), (OP))) \
1055 return 0; \
1056}
1057
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001058#define ADDOP_IN_SCOPE(C, OP) { \
1059 if (!compiler_addop((C), (OP))) { \
1060 compiler_exit_scope(c); \
1061 return 0; \
1062 } \
1063}
1064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065#define ADDOP_O(C, OP, O, TYPE) { \
1066 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1067 return 0; \
1068}
1069
1070#define ADDOP_NAME(C, OP, O, TYPE) { \
1071 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1072 return 0; \
1073}
1074
1075#define ADDOP_I(C, OP, O) { \
1076 if (!compiler_addop_i((C), (OP), (O))) \
1077 return 0; \
1078}
1079
1080#define ADDOP_JABS(C, OP, O) { \
1081 if (!compiler_addop_j((C), (OP), (O), 1)) \
1082 return 0; \
1083}
1084
1085#define ADDOP_JREL(C, OP, O) { \
1086 if (!compiler_addop_j((C), (OP), (O), 0)) \
1087 return 0; \
1088}
1089
1090/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1091 the ASDL name to synthesize the name of the C type and the visit function.
1092*/
1093
1094#define VISIT(C, TYPE, V) {\
1095 if (!compiler_visit_ ## TYPE((C), (V))) \
1096 return 0; \
1097}
1098
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001099#define VISIT_IN_SCOPE(C, TYPE, V) {\
1100 if (!compiler_visit_ ## TYPE((C), (V))) { \
1101 compiler_exit_scope(c); \
1102 return 0; \
1103 } \
1104}
1105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106#define VISIT_SLICE(C, V, CTX) {\
1107 if (!compiler_visit_slice((C), (V), (CTX))) \
1108 return 0; \
1109}
1110
1111#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001112 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001114 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001115 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116 if (!compiler_visit_ ## TYPE((C), elt)) \
1117 return 0; \
1118 } \
1119}
1120
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001121#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001122 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001123 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001124 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001126 if (!compiler_visit_ ## TYPE((C), elt)) { \
1127 compiler_exit_scope(c); \
1128 return 0; \
1129 } \
1130 } \
1131}
1132
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133static int
1134compiler_isdocstring(stmt_ty s)
1135{
1136 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001137 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 return s->v.Expr.value->kind == Str_kind;
1139}
1140
1141/* Compile a sequence of statements, checking for a docstring. */
1142
1143static int
1144compiler_body(struct compiler *c, asdl_seq *stmts)
1145{
1146 int i = 0;
1147 stmt_ty st;
1148
1149 if (!asdl_seq_LEN(stmts))
1150 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001151 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001152 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1153 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 i = 1;
1155 VISIT(c, expr, st->v.Expr.value);
1156 if (!compiler_nameop(c, __doc__, Store))
1157 return 0;
1158 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001159 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001160 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 return 1;
1162}
1163
1164static PyCodeObject *
1165compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001166{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001168 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 static PyObject *module;
1170 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001171 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 if (!module)
1173 return NULL;
1174 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001175 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1176 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001177 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 switch (mod->kind) {
1179 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001180 if (!compiler_body(c, mod->v.Module.body)) {
1181 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001183 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 break;
1185 case Interactive_kind:
1186 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001187 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 break;
1190 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001191 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001192 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 break;
1194 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001195 PyErr_SetString(PyExc_SystemError,
1196 "suite should not be possible");
1197 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001198 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001199 PyErr_Format(PyExc_SystemError,
1200 "module kind %d should not be possible",
1201 mod->kind);
1202 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 co = assemble(c, addNone);
1205 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001206 return co;
1207}
1208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209/* The test for LOCAL must come before the test for FREE in order to
1210 handle classes where name is both local and free. The local var is
1211 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001212*/
1213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214static int
1215get_ref_type(struct compiler *c, PyObject *name)
1216{
1217 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001218 if (scope == 0) {
1219 char buf[350];
1220 PyOS_snprintf(buf, sizeof(buf),
1221 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001222 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001223 PyBytes_AS_STRING(name),
1224 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001225 PyObject_REPR(c->u->u_ste->ste_id),
1226 c->c_filename,
1227 PyObject_REPR(c->u->u_ste->ste_symbols),
1228 PyObject_REPR(c->u->u_varnames),
1229 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001231 Py_FatalError(buf);
1232 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001233
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001234 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
1237static int
1238compiler_lookup_arg(PyObject *dict, PyObject *name)
1239{
1240 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001243 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001245 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001248 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
1251static int
1252compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1253{
1254 int i, free = PyCode_GetNumFree(co);
1255 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001256 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1257 ADDOP_I(c, MAKE_FUNCTION, args);
1258 return 1;
1259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 for (i = 0; i < free; ++i) {
1261 /* Bypass com_addop_varname because it will generate
1262 LOAD_DEREF but LOAD_CLOSURE is needed.
1263 */
1264 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1265 int arg, reftype;
1266
1267 /* Special case: If a class contains a method with a
1268 free variable that has the same name as a method,
1269 the name will be considered free *and* local in the
1270 class. It should be handled by the closure, as
1271 well as by the normal name loookup logic.
1272 */
1273 reftype = get_ref_type(c, name);
1274 if (reftype == CELL)
1275 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1276 else /* (reftype == FREE) */
1277 arg = compiler_lookup_arg(c->u->u_freevars, name);
1278 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001279 fprintf(stderr,
1280 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281 "freevars of %s: %s\n",
1282 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001283 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001285 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286 PyObject_REPR(co->co_freevars));
1287 Py_FatalError("compiler_make_closure()");
1288 }
1289 ADDOP_I(c, LOAD_CLOSURE, arg);
1290 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001291 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001293 ADDOP_I(c, MAKE_CLOSURE, args);
1294 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295}
1296
1297static int
1298compiler_decorators(struct compiler *c, asdl_seq* decos)
1299{
1300 int i;
1301
1302 if (!decos)
1303 return 1;
1304
1305 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001306 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307 }
1308 return 1;
1309}
1310
1311static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001312compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1313 asdl_seq *kw_defaults)
1314{
1315 int i, default_count = 0;
1316 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001317 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001318 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1319 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001320 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001321 if (!compiler_visit_expr(c, default_)) {
1322 return -1;
1323 }
1324 default_count++;
1325 }
1326 }
1327 return default_count;
1328}
1329
1330static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001331compiler_visit_argannotation(struct compiler *c, identifier id,
1332 expr_ty annotation, PyObject *names)
1333{
1334 if (annotation) {
1335 VISIT(c, expr, annotation);
1336 if (PyList_Append(names, id))
1337 return -1;
1338 }
1339 return 0;
1340}
1341
1342static int
1343compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1344 PyObject *names)
1345{
1346 int i, error;
1347 for (i = 0; i < asdl_seq_LEN(args); i++) {
1348 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001349 error = compiler_visit_argannotation(
1350 c,
1351 arg->arg,
1352 arg->annotation,
1353 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001354 if (error)
1355 return error;
1356 }
1357 return 0;
1358}
1359
1360static int
1361compiler_visit_annotations(struct compiler *c, arguments_ty args,
1362 expr_ty returns)
1363{
Guido van Rossum0240b922007-02-26 21:23:50 +00001364 /* Push arg annotations and a list of the argument names. Return the #
1365 of items pushed. The expressions are evaluated out-of-order wrt the
1366 source code.
1367
1368 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1369 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001370 static identifier return_str;
1371 PyObject *names;
1372 int len;
1373 names = PyList_New(0);
1374 if (!names)
1375 return -1;
1376
1377 if (compiler_visit_argannotations(c, args->args, names))
1378 goto error;
1379 if (args->varargannotation &&
1380 compiler_visit_argannotation(c, args->vararg,
1381 args->varargannotation, names))
1382 goto error;
1383 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1384 goto error;
1385 if (args->kwargannotation &&
1386 compiler_visit_argannotation(c, args->kwarg,
1387 args->kwargannotation, names))
1388 goto error;
1389
1390 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001391 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001392 if (!return_str)
1393 goto error;
1394 }
1395 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1396 goto error;
1397 }
1398
1399 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001400 if (len > 65534) {
1401 /* len must fit in 16 bits, and len is incremented below */
1402 PyErr_SetString(PyExc_SyntaxError,
1403 "too many annotations");
1404 goto error;
1405 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001406 if (len) {
1407 /* convert names to a tuple and place on stack */
1408 PyObject *elt;
1409 int i;
1410 PyObject *s = PyTuple_New(len);
1411 if (!s)
1412 goto error;
1413 for (i = 0; i < len; i++) {
1414 elt = PyList_GET_ITEM(names, i);
1415 Py_INCREF(elt);
1416 PyTuple_SET_ITEM(s, i, elt);
1417 }
1418 ADDOP_O(c, LOAD_CONST, s, consts);
1419 Py_DECREF(s);
1420 len++; /* include the just-pushed tuple */
1421 }
1422 Py_DECREF(names);
1423 return len;
1424
1425error:
1426 Py_DECREF(names);
1427 return -1;
1428}
1429
1430static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431compiler_function(struct compiler *c, stmt_ty s)
1432{
1433 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001434 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001436 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001437 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001438 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001439 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001440 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
1442 assert(s->kind == FunctionDef_kind);
1443
1444 if (!compiler_decorators(c, decos))
1445 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001446 if (args->kwonlyargs) {
1447 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1448 args->kw_defaults);
1449 if (res < 0)
1450 return 0;
1451 kw_default_count = res;
1452 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 if (args->defaults)
1454 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001455 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001456 if (num_annotations < 0)
1457 return 0;
1458 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001459
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1461 s->lineno))
1462 return 0;
1463
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001464 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001465 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001466 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001467 first_const = st->v.Expr.value->v.Str.s;
1468 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001469 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001470 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001474 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001476 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001478 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1479 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480 }
1481 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001482 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483 if (co == NULL)
1484 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485
Guido van Rossum4f72a782006-10-27 23:31:49 +00001486 arglength = asdl_seq_LEN(args->defaults);
1487 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001488 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001489 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001490 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491
Neal Norwitzc1505362006-12-28 06:47:50 +00001492 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1494 ADDOP_I(c, CALL_FUNCTION, 1);
1495 }
1496
1497 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1498}
1499
1500static int
1501compiler_class(struct compiler *c, stmt_ty s)
1502{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001504 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001505 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001506 asdl_seq* decos = s->v.ClassDef.decorator_list;
1507
1508 if (!compiler_decorators(c, decos))
1509 return 0;
1510
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001511 /* ultimately generate code for:
1512 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1513 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001514 <func> is a function/closure created from the class body;
1515 it has a single argument (__locals__) where the dict
1516 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001517 <name> is the class name
1518 <bases> is the positional arguments and *varargs argument
1519 <keywords> is the keyword arguments and **kwds argument
1520 This borrows from compiler_call.
1521 */
1522
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001523 /* 1. compile the class body into a code object */
1524 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1525 return 0;
1526 /* this block represents what we do in the new scope */
1527 {
1528 /* use the class name for name mangling */
1529 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001530 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001531 c->u->u_private = s->v.ClassDef.name;
1532 /* force it to have one mandatory argument */
1533 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001534 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001535 ADDOP_I(c, LOAD_FAST, 0);
1536 /* ... and store it into f_locals */
1537 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001538 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001539 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001540 if (!str || !compiler_nameop(c, str, Load)) {
1541 Py_XDECREF(str);
1542 compiler_exit_scope(c);
1543 return 0;
1544 }
1545 Py_DECREF(str);
1546 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001547 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001548 if (!str || !compiler_nameop(c, str, Store)) {
1549 Py_XDECREF(str);
1550 compiler_exit_scope(c);
1551 return 0;
1552 }
1553 Py_DECREF(str);
1554 /* compile the body proper */
1555 if (!compiler_body(c, s->v.ClassDef.body)) {
1556 compiler_exit_scope(c);
1557 return 0;
1558 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001559 /* return the (empty) __class__ cell */
1560 str = PyUnicode_InternFromString("__class__");
1561 if (str == NULL) {
1562 compiler_exit_scope(c);
1563 return 0;
1564 }
1565 i = compiler_lookup_arg(c->u->u_cellvars, str);
1566 Py_DECREF(str);
1567 if (i == -1) {
1568 /* This happens when nobody references the cell */
1569 PyErr_Clear();
1570 /* Return None */
1571 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1572 }
1573 else {
1574 /* Return the cell where to store __class__ */
1575 ADDOP_I(c, LOAD_CLOSURE, i);
1576 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001577 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1578 /* create the code object */
1579 co = assemble(c, 1);
1580 }
1581 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001582 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001583 if (co == NULL)
1584 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001585
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001586 /* 2. load the 'build_class' function */
1587 ADDOP(c, LOAD_BUILD_CLASS);
1588
1589 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001590 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001591 Py_DECREF(co);
1592
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001593 /* 4. load class name */
1594 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1595
1596 /* 5. generate the rest of the code for the call */
1597 if (!compiler_call_helper(c, 2,
1598 s->v.ClassDef.bases,
1599 s->v.ClassDef.keywords,
1600 s->v.ClassDef.starargs,
1601 s->v.ClassDef.kwargs))
1602 return 0;
1603
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001604 /* 6. apply decorators */
1605 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1606 ADDOP_I(c, CALL_FUNCTION, 1);
1607 }
1608
1609 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001610 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1611 return 0;
1612 return 1;
1613}
1614
1615static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001616compiler_ifexp(struct compiler *c, expr_ty e)
1617{
1618 basicblock *end, *next;
1619
1620 assert(e->kind == IfExp_kind);
1621 end = compiler_new_block(c);
1622 if (end == NULL)
1623 return 0;
1624 next = compiler_new_block(c);
1625 if (next == NULL)
1626 return 0;
1627 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001628 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001629 VISIT(c, expr, e->v.IfExp.body);
1630 ADDOP_JREL(c, JUMP_FORWARD, end);
1631 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001632 VISIT(c, expr, e->v.IfExp.orelse);
1633 compiler_use_next_block(c, end);
1634 return 1;
1635}
1636
1637static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638compiler_lambda(struct compiler *c, expr_ty e)
1639{
1640 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001641 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001642 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643 arguments_ty args = e->v.Lambda.args;
1644 assert(e->kind == Lambda_kind);
1645
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001646 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001647 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001648 if (!name)
1649 return 0;
1650 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651
Guido van Rossum4f72a782006-10-27 23:31:49 +00001652 if (args->kwonlyargs) {
1653 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1654 args->kw_defaults);
1655 if (res < 0) return 0;
1656 kw_default_count = res;
1657 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658 if (args->defaults)
1659 VISIT_SEQ(c, expr, args->defaults);
1660 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1661 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001664 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001665 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001666 if (c->u->u_ste->ste_generator) {
1667 ADDOP_IN_SCOPE(c, POP_TOP);
1668 }
1669 else {
1670 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1671 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001672 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001673 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 if (co == NULL)
1675 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676
Guido van Rossum4f72a782006-10-27 23:31:49 +00001677 arglength = asdl_seq_LEN(args->defaults);
1678 arglength |= kw_default_count << 8;
1679 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001680 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681
1682 return 1;
1683}
1684
1685static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686compiler_if(struct compiler *c, stmt_ty s)
1687{
1688 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001689 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690 assert(s->kind == If_kind);
1691 end = compiler_new_block(c);
1692 if (end == NULL)
1693 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001694
1695 constant = expr_constant(s->v.If.test);
1696 /* constant = 0: "if 0"
1697 * constant = 1: "if 1", "if 2", ...
1698 * constant = -1: rest */
1699 if (constant == 0) {
1700 if (s->v.If.orelse)
1701 VISIT_SEQ(c, stmt, s->v.If.orelse);
1702 } else if (constant == 1) {
1703 VISIT_SEQ(c, stmt, s->v.If.body);
1704 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001705 if (s->v.If.orelse) {
1706 next = compiler_new_block(c);
1707 if (next == NULL)
1708 return 0;
1709 }
1710 else
1711 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001712 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001713 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001714 VISIT_SEQ(c, stmt, s->v.If.body);
1715 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001716 if (s->v.If.orelse) {
1717 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001718 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001719 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001721 compiler_use_next_block(c, end);
1722 return 1;
1723}
1724
1725static int
1726compiler_for(struct compiler *c, stmt_ty s)
1727{
1728 basicblock *start, *cleanup, *end;
1729
1730 start = compiler_new_block(c);
1731 cleanup = compiler_new_block(c);
1732 end = compiler_new_block(c);
1733 if (start == NULL || end == NULL || cleanup == NULL)
1734 return 0;
1735 ADDOP_JREL(c, SETUP_LOOP, end);
1736 if (!compiler_push_fblock(c, LOOP, start))
1737 return 0;
1738 VISIT(c, expr, s->v.For.iter);
1739 ADDOP(c, GET_ITER);
1740 compiler_use_next_block(c, start);
1741 ADDOP_JREL(c, FOR_ITER, cleanup);
1742 VISIT(c, expr, s->v.For.target);
1743 VISIT_SEQ(c, stmt, s->v.For.body);
1744 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1745 compiler_use_next_block(c, cleanup);
1746 ADDOP(c, POP_BLOCK);
1747 compiler_pop_fblock(c, LOOP, start);
1748 VISIT_SEQ(c, stmt, s->v.For.orelse);
1749 compiler_use_next_block(c, end);
1750 return 1;
1751}
1752
1753static int
1754compiler_while(struct compiler *c, stmt_ty s)
1755{
1756 basicblock *loop, *orelse, *end, *anchor = NULL;
1757 int constant = expr_constant(s->v.While.test);
1758
Christian Heimes969fe572008-01-25 11:23:10 +00001759 if (constant == 0) {
1760 if (s->v.While.orelse)
1761 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001762 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001763 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764 loop = compiler_new_block(c);
1765 end = compiler_new_block(c);
1766 if (constant == -1) {
1767 anchor = compiler_new_block(c);
1768 if (anchor == NULL)
1769 return 0;
1770 }
1771 if (loop == NULL || end == NULL)
1772 return 0;
1773 if (s->v.While.orelse) {
1774 orelse = compiler_new_block(c);
1775 if (orelse == NULL)
1776 return 0;
1777 }
1778 else
1779 orelse = NULL;
1780
1781 ADDOP_JREL(c, SETUP_LOOP, end);
1782 compiler_use_next_block(c, loop);
1783 if (!compiler_push_fblock(c, LOOP, loop))
1784 return 0;
1785 if (constant == -1) {
1786 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001787 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788 }
1789 VISIT_SEQ(c, stmt, s->v.While.body);
1790 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1791
1792 /* XXX should the two POP instructions be in a separate block
1793 if there is no else clause ?
1794 */
1795
1796 if (constant == -1) {
1797 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798 ADDOP(c, POP_BLOCK);
1799 }
1800 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001801 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802 VISIT_SEQ(c, stmt, s->v.While.orelse);
1803 compiler_use_next_block(c, end);
1804
1805 return 1;
1806}
1807
1808static int
1809compiler_continue(struct compiler *c)
1810{
1811 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001812 static const char IN_FINALLY_ERROR_MSG[] =
1813 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814 int i;
1815
1816 if (!c->u->u_nfblocks)
1817 return compiler_error(c, LOOP_ERROR_MSG);
1818 i = c->u->u_nfblocks - 1;
1819 switch (c->u->u_fblock[i].fb_type) {
1820 case LOOP:
1821 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1822 break;
1823 case EXCEPT:
1824 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001825 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1826 /* Prevent continue anywhere under a finally
1827 even if hidden in a sub-try or except. */
1828 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1829 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1830 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 if (i == -1)
1832 return compiler_error(c, LOOP_ERROR_MSG);
1833 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1834 break;
1835 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001836 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837 }
1838
1839 return 1;
1840}
1841
1842/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1843
1844 SETUP_FINALLY L
1845 <code for body>
1846 POP_BLOCK
1847 LOAD_CONST <None>
1848 L: <code for finalbody>
1849 END_FINALLY
1850
1851 The special instructions use the block stack. Each block
1852 stack entry contains the instruction that created it (here
1853 SETUP_FINALLY), the level of the value stack at the time the
1854 block stack entry was created, and a label (here L).
1855
1856 SETUP_FINALLY:
1857 Pushes the current value stack level and the label
1858 onto the block stack.
1859 POP_BLOCK:
1860 Pops en entry from the block stack, and pops the value
1861 stack until its level is the same as indicated on the
1862 block stack. (The label is ignored.)
1863 END_FINALLY:
1864 Pops a variable number of entries from the *value* stack
1865 and re-raises the exception they specify. The number of
1866 entries popped depends on the (pseudo) exception type.
1867
1868 The block stack is unwound when an exception is raised:
1869 when a SETUP_FINALLY entry is found, the exception is pushed
1870 onto the value stack (and the exception condition is cleared),
1871 and the interpreter jumps to the label gotten from the block
1872 stack.
1873*/
1874
1875static int
1876compiler_try_finally(struct compiler *c, stmt_ty s)
1877{
1878 basicblock *body, *end;
1879 body = compiler_new_block(c);
1880 end = compiler_new_block(c);
1881 if (body == NULL || end == NULL)
1882 return 0;
1883
1884 ADDOP_JREL(c, SETUP_FINALLY, end);
1885 compiler_use_next_block(c, body);
1886 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1887 return 0;
1888 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1889 ADDOP(c, POP_BLOCK);
1890 compiler_pop_fblock(c, FINALLY_TRY, body);
1891
1892 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1893 compiler_use_next_block(c, end);
1894 if (!compiler_push_fblock(c, FINALLY_END, end))
1895 return 0;
1896 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1897 ADDOP(c, END_FINALLY);
1898 compiler_pop_fblock(c, FINALLY_END, end);
1899
1900 return 1;
1901}
1902
1903/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001904 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905 (The contents of the value stack is shown in [], with the top
1906 at the right; 'tb' is trace-back info, 'val' the exception's
1907 associated value, and 'exc' the exception.)
1908
1909 Value stack Label Instruction Argument
1910 [] SETUP_EXCEPT L1
1911 [] <code for S>
1912 [] POP_BLOCK
1913 [] JUMP_FORWARD L0
1914
1915 [tb, val, exc] L1: DUP )
1916 [tb, val, exc, exc] <evaluate E1> )
1917 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001918 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919 [tb, val, exc] POP
1920 [tb, val] <assign to V1> (or POP if no V1)
1921 [tb] POP
1922 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001923 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001925 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926 .............................etc.......................
1927
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001928 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929
1930 [] L0: <next statement>
1931
1932 Of course, parts are not generated if Vi or Ei is not present.
1933*/
1934static int
1935compiler_try_except(struct compiler *c, stmt_ty s)
1936{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001937 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 int i, n;
1939
1940 body = compiler_new_block(c);
1941 except = compiler_new_block(c);
1942 orelse = compiler_new_block(c);
1943 end = compiler_new_block(c);
1944 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1945 return 0;
1946 ADDOP_JREL(c, SETUP_EXCEPT, except);
1947 compiler_use_next_block(c, body);
1948 if (!compiler_push_fblock(c, EXCEPT, body))
1949 return 0;
1950 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1951 ADDOP(c, POP_BLOCK);
1952 compiler_pop_fblock(c, EXCEPT, body);
1953 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1954 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1955 compiler_use_next_block(c, except);
1956 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001957 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001959 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001961 c->u->u_lineno_set = 0;
1962 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963 except = compiler_new_block(c);
1964 if (except == NULL)
1965 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001966 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001968 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001970 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971 }
1972 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001973 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001974 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001975
1976 cleanup_end = compiler_new_block(c);
1977 cleanup_body = compiler_new_block(c);
1978 if(!(cleanup_end || cleanup_body))
1979 return 0;
1980
Neal Norwitzad74aa82008-03-31 05:14:30 +00001981 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001982 ADDOP(c, POP_TOP);
1983
1984 /*
1985 try:
1986 # body
1987 except type as name:
1988 try:
1989 # body
1990 finally:
1991 name = None
1992 del name
1993 */
1994
1995 /* second try: */
1996 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
1997 compiler_use_next_block(c, cleanup_body);
1998 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
1999 return 0;
2000
2001 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002002 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002003 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002004 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002005 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2006
2007 /* finally: */
2008 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2009 compiler_use_next_block(c, cleanup_end);
2010 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2011 return 0;
2012
2013 /* name = None */
2014 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002015 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002016
Guido van Rossum16be03e2007-01-10 18:51:35 +00002017 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002018 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002019
2020 ADDOP(c, END_FINALLY);
2021 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 }
2023 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002024 basicblock *cleanup_body;
2025
2026 cleanup_body = compiler_new_block(c);
2027 if(!cleanup_body)
2028 return 0;
2029
2030 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002031 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002032 compiler_use_next_block(c, cleanup_body);
2033 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2034 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002035 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002036 ADDOP(c, POP_EXCEPT);
2037 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039 ADDOP_JREL(c, JUMP_FORWARD, end);
2040 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002041 }
2042 ADDOP(c, END_FINALLY);
2043 compiler_use_next_block(c, orelse);
2044 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2045 compiler_use_next_block(c, end);
2046 return 1;
2047}
2048
2049static int
2050compiler_import_as(struct compiler *c, identifier name, identifier asname)
2051{
2052 /* The IMPORT_NAME opcode was already generated. This function
2053 merely needs to bind the result to a name.
2054
2055 If there is a dot in name, we need to split it and emit a
2056 LOAD_ATTR for each name.
2057 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002058 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2059 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 if (dot) {
2061 /* Consume the base module name to get the first attribute */
2062 src = dot + 1;
2063 while (dot) {
2064 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002065 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002066 dot = Py_UNICODE_strchr(src, '.');
2067 attr = PyUnicode_FromUnicode(src,
2068 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002069 if (!attr)
2070 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002072 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 src = dot + 1;
2074 }
2075 }
2076 return compiler_nameop(c, asname, Store);
2077}
2078
2079static int
2080compiler_import(struct compiler *c, stmt_ty s)
2081{
2082 /* The Import node stores a module name like a.b.c as a single
2083 string. This is convenient for all cases except
2084 import a.b.c as d
2085 where we need to parse that string to extract the individual
2086 module names.
2087 XXX Perhaps change the representation to make this case simpler?
2088 */
2089 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002090
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002092 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002094 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095
Christian Heimes217cfd12007-12-02 14:31:20 +00002096 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002097 if (level == NULL)
2098 return 0;
2099
2100 ADDOP_O(c, LOAD_CONST, level, consts);
2101 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2103 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2104
2105 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002106 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002107 if (!r)
2108 return r;
2109 }
2110 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002112 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2113 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002115 tmp = PyUnicode_FromUnicode(base,
2116 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 r = compiler_nameop(c, tmp, Store);
2118 if (dot) {
2119 Py_DECREF(tmp);
2120 }
2121 if (!r)
2122 return r;
2123 }
2124 }
2125 return 1;
2126}
2127
2128static int
2129compiler_from_import(struct compiler *c, stmt_ty s)
2130{
2131 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132
2133 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002134 PyObject *level;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002135 static PyObject *empty_string;
2136
2137 if (!empty_string) {
2138 empty_string = PyUnicode_FromString("");
2139 if (!empty_string)
2140 return 0;
2141 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002142
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143 if (!names)
2144 return 0;
2145
Christian Heimes217cfd12007-12-02 14:31:20 +00002146 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002147 if (!level) {
2148 Py_DECREF(names);
2149 return 0;
2150 }
2151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 /* build up the names */
2153 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002154 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 Py_INCREF(alias->name);
2156 PyTuple_SET_ITEM(names, i, alias->name);
2157 }
2158
Benjamin Peterson78565b22009-06-28 19:19:51 +00002159 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2160 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2161 Py_DECREF(level);
2162 Py_DECREF(names);
2163 return compiler_error(c, "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002164 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165 }
2166
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002167 ADDOP_O(c, LOAD_CONST, level, consts);
2168 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002170 Py_DECREF(names);
Benjamin Peterson78565b22009-06-28 19:19:51 +00002171 if (s->v.ImportFrom.module) {
2172 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2173 }
2174 else {
2175 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2176 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002178 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179 identifier store_name;
2180
Martin v. Löwis5b222132007-06-10 09:51:05 +00002181 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182 assert(n == 1);
2183 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002184 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 }
2186
2187 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2188 store_name = alias->name;
2189 if (alias->asname)
2190 store_name = alias->asname;
2191
2192 if (!compiler_nameop(c, store_name, Store)) {
2193 Py_DECREF(names);
2194 return 0;
2195 }
2196 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002197 /* remove imported module */
2198 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199 return 1;
2200}
2201
2202static int
2203compiler_assert(struct compiler *c, stmt_ty s)
2204{
2205 static PyObject *assertion_error = NULL;
2206 basicblock *end;
2207
2208 if (Py_OptimizeFlag)
2209 return 1;
2210 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002211 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212 if (assertion_error == NULL)
2213 return 0;
2214 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002215 if (s->v.Assert.test->kind == Tuple_kind &&
2216 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2217 const char* msg =
2218 "assertion is always true, perhaps remove parentheses?";
2219 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2220 c->u->u_lineno, NULL, NULL) == -1)
2221 return 0;
2222 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 VISIT(c, expr, s->v.Assert.test);
2224 end = compiler_new_block(c);
2225 if (end == NULL)
2226 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002227 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002228 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2229 if (s->v.Assert.msg) {
2230 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002231 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002232 }
Collin Winter828f04a2007-08-31 00:04:24 +00002233 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002234 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235 return 1;
2236}
2237
2238static int
2239compiler_visit_stmt(struct compiler *c, stmt_ty s)
2240{
2241 int i, n;
2242
Thomas Wouters89f507f2006-12-13 04:49:30 +00002243 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002245 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002248 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002250 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002251 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002252 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253 if (c->u->u_ste->ste_type != FunctionBlock)
2254 return compiler_error(c, "'return' outside function");
2255 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256 VISIT(c, expr, s->v.Return.value);
2257 }
2258 else
2259 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2260 ADDOP(c, RETURN_VALUE);
2261 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 VISIT_SEQ(c, expr, s->v.Delete.targets)
2264 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002265 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 n = asdl_seq_LEN(s->v.Assign.targets);
2267 VISIT(c, expr, s->v.Assign.value);
2268 for (i = 0; i < n; i++) {
2269 if (i < n - 1)
2270 ADDOP(c, DUP_TOP);
2271 VISIT(c, expr,
2272 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2273 }
2274 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002275 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002277 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002279 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002281 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002283 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002285 if (s->v.Raise.exc) {
2286 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002288 if (s->v.Raise.cause) {
2289 VISIT(c, expr, s->v.Raise.cause);
2290 n++;
2291 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 }
2293 ADDOP_I(c, RAISE_VARARGS, n);
2294 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002295 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002297 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002299 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002301 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002303 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002305 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002306 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002308 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002310 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311 ADDOP(c, PRINT_EXPR);
2312 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002313 else if (s->v.Expr.value->kind != Str_kind &&
2314 s->v.Expr.value->kind != Num_kind) {
2315 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 ADDOP(c, POP_TOP);
2317 }
2318 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002321 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002322 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 return compiler_error(c, "'break' outside loop");
2324 ADDOP(c, BREAK_LOOP);
2325 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002326 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002328 case With_kind:
2329 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 }
2331 return 1;
2332}
2333
2334static int
2335unaryop(unaryop_ty op)
2336{
2337 switch (op) {
2338 case Invert:
2339 return UNARY_INVERT;
2340 case Not:
2341 return UNARY_NOT;
2342 case UAdd:
2343 return UNARY_POSITIVE;
2344 case USub:
2345 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002346 default:
2347 PyErr_Format(PyExc_SystemError,
2348 "unary op %d should not be possible", op);
2349 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351}
2352
2353static int
2354binop(struct compiler *c, operator_ty op)
2355{
2356 switch (op) {
2357 case Add:
2358 return BINARY_ADD;
2359 case Sub:
2360 return BINARY_SUBTRACT;
2361 case Mult:
2362 return BINARY_MULTIPLY;
2363 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002364 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365 case Mod:
2366 return BINARY_MODULO;
2367 case Pow:
2368 return BINARY_POWER;
2369 case LShift:
2370 return BINARY_LSHIFT;
2371 case RShift:
2372 return BINARY_RSHIFT;
2373 case BitOr:
2374 return BINARY_OR;
2375 case BitXor:
2376 return BINARY_XOR;
2377 case BitAnd:
2378 return BINARY_AND;
2379 case FloorDiv:
2380 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002381 default:
2382 PyErr_Format(PyExc_SystemError,
2383 "binary op %d should not be possible", op);
2384 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386}
2387
2388static int
2389cmpop(cmpop_ty op)
2390{
2391 switch (op) {
2392 case Eq:
2393 return PyCmp_EQ;
2394 case NotEq:
2395 return PyCmp_NE;
2396 case Lt:
2397 return PyCmp_LT;
2398 case LtE:
2399 return PyCmp_LE;
2400 case Gt:
2401 return PyCmp_GT;
2402 case GtE:
2403 return PyCmp_GE;
2404 case Is:
2405 return PyCmp_IS;
2406 case IsNot:
2407 return PyCmp_IS_NOT;
2408 case In:
2409 return PyCmp_IN;
2410 case NotIn:
2411 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002412 default:
2413 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002414 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415}
2416
2417static int
2418inplace_binop(struct compiler *c, operator_ty op)
2419{
2420 switch (op) {
2421 case Add:
2422 return INPLACE_ADD;
2423 case Sub:
2424 return INPLACE_SUBTRACT;
2425 case Mult:
2426 return INPLACE_MULTIPLY;
2427 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002428 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002429 case Mod:
2430 return INPLACE_MODULO;
2431 case Pow:
2432 return INPLACE_POWER;
2433 case LShift:
2434 return INPLACE_LSHIFT;
2435 case RShift:
2436 return INPLACE_RSHIFT;
2437 case BitOr:
2438 return INPLACE_OR;
2439 case BitXor:
2440 return INPLACE_XOR;
2441 case BitAnd:
2442 return INPLACE_AND;
2443 case FloorDiv:
2444 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002445 default:
2446 PyErr_Format(PyExc_SystemError,
2447 "inplace binary op %d should not be possible", op);
2448 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002449 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450}
2451
2452static int
2453compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2454{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002455 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2457
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002458 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002459 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 /* XXX AugStore isn't used anywhere! */
2461
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002462 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002463 if (!mangled)
2464 return 0;
2465
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 op = 0;
2467 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002468 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 switch (scope) {
2470 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002471 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472 optype = OP_DEREF;
2473 break;
2474 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002475 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 optype = OP_DEREF;
2477 break;
2478 case LOCAL:
2479 if (c->u->u_ste->ste_type == FunctionBlock)
2480 optype = OP_FAST;
2481 break;
2482 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002483 if (c->u->u_ste->ste_type == FunctionBlock &&
2484 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 optype = OP_GLOBAL;
2486 break;
2487 case GLOBAL_EXPLICIT:
2488 optype = OP_GLOBAL;
2489 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002490 default:
2491 /* scope can be 0 */
2492 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493 }
2494
2495 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002496 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497
2498 switch (optype) {
2499 case OP_DEREF:
2500 switch (ctx) {
2501 case Load: op = LOAD_DEREF; break;
2502 case Store: op = STORE_DEREF; break;
2503 case AugLoad:
2504 case AugStore:
2505 break;
2506 case Del:
2507 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002508 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002510 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002511 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002512 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002514 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002515 PyErr_SetString(PyExc_SystemError,
2516 "param invalid for deref variable");
2517 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518 }
2519 break;
2520 case OP_FAST:
2521 switch (ctx) {
2522 case Load: op = LOAD_FAST; break;
2523 case Store: op = STORE_FAST; break;
2524 case Del: op = DELETE_FAST; break;
2525 case AugLoad:
2526 case AugStore:
2527 break;
2528 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002529 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002530 PyErr_SetString(PyExc_SystemError,
2531 "param invalid for local variable");
2532 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002534 ADDOP_O(c, op, mangled, varnames);
2535 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536 return 1;
2537 case OP_GLOBAL:
2538 switch (ctx) {
2539 case Load: op = LOAD_GLOBAL; break;
2540 case Store: op = STORE_GLOBAL; break;
2541 case Del: op = DELETE_GLOBAL; break;
2542 case AugLoad:
2543 case AugStore:
2544 break;
2545 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002546 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002547 PyErr_SetString(PyExc_SystemError,
2548 "param invalid for global variable");
2549 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 }
2551 break;
2552 case OP_NAME:
2553 switch (ctx) {
2554 case Load: op = LOAD_NAME; break;
2555 case Store: op = STORE_NAME; break;
2556 case Del: op = DELETE_NAME; break;
2557 case AugLoad:
2558 case AugStore:
2559 break;
2560 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002561 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002562 PyErr_SetString(PyExc_SystemError,
2563 "param invalid for name variable");
2564 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565 }
2566 break;
2567 }
2568
2569 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002570 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002571 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002572 if (arg < 0)
2573 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002574 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575}
2576
2577static int
2578compiler_boolop(struct compiler *c, expr_ty e)
2579{
2580 basicblock *end;
2581 int jumpi, i, n;
2582 asdl_seq *s;
2583
2584 assert(e->kind == BoolOp_kind);
2585 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002586 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002588 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002590 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591 return 0;
2592 s = e->v.BoolOp.values;
2593 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002594 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002596 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002597 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002599 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 compiler_use_next_block(c, end);
2601 return 1;
2602}
2603
2604static int
2605compiler_list(struct compiler *c, expr_ty e)
2606{
2607 int n = asdl_seq_LEN(e->v.List.elts);
2608 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002609 int i, seen_star = 0;
2610 for (i = 0; i < n; i++) {
2611 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2612 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002613 if ((i >= (1 << 8)) ||
2614 (n-i-1 >= (INT_MAX >> 8)))
2615 return compiler_error(c,
2616 "too many expressions in "
2617 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002618 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2619 seen_star = 1;
2620 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2621 } else if (elt->kind == Starred_kind) {
2622 return compiler_error(c,
2623 "two starred expressions in assignment");
2624 }
2625 }
2626 if (!seen_star) {
2627 ADDOP_I(c, UNPACK_SEQUENCE, n);
2628 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 }
2630 VISIT_SEQ(c, expr, e->v.List.elts);
2631 if (e->v.List.ctx == Load) {
2632 ADDOP_I(c, BUILD_LIST, n);
2633 }
2634 return 1;
2635}
2636
2637static int
2638compiler_tuple(struct compiler *c, expr_ty e)
2639{
2640 int n = asdl_seq_LEN(e->v.Tuple.elts);
2641 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002642 int i, seen_star = 0;
2643 for (i = 0; i < n; i++) {
2644 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2645 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002646 if ((i >= (1 << 8)) ||
2647 (n-i-1 >= (INT_MAX >> 8)))
2648 return compiler_error(c,
2649 "too many expressions in "
2650 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002651 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2652 seen_star = 1;
2653 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2654 } else if (elt->kind == Starred_kind) {
2655 return compiler_error(c,
2656 "two starred expressions in assignment");
2657 }
2658 }
2659 if (!seen_star) {
2660 ADDOP_I(c, UNPACK_SEQUENCE, n);
2661 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662 }
2663 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2664 if (e->v.Tuple.ctx == Load) {
2665 ADDOP_I(c, BUILD_TUPLE, n);
2666 }
2667 return 1;
2668}
2669
2670static int
2671compiler_compare(struct compiler *c, expr_ty e)
2672{
2673 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002674 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675
2676 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2677 VISIT(c, expr, e->v.Compare.left);
2678 n = asdl_seq_LEN(e->v.Compare.ops);
2679 assert(n > 0);
2680 if (n > 1) {
2681 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002682 if (cleanup == NULL)
2683 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002684 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002685 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 }
2687 for (i = 1; i < n; i++) {
2688 ADDOP(c, DUP_TOP);
2689 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002691 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002692 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002693 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002696 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002697 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002699 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002701 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 if (n > 1) {
2703 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 if (end == NULL)
2705 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 ADDOP_JREL(c, JUMP_FORWARD, end);
2707 compiler_use_next_block(c, cleanup);
2708 ADDOP(c, ROT_TWO);
2709 ADDOP(c, POP_TOP);
2710 compiler_use_next_block(c, end);
2711 }
2712 return 1;
2713}
2714
2715static int
2716compiler_call(struct compiler *c, expr_ty e)
2717{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002719 return compiler_call_helper(c, 0,
2720 e->v.Call.args,
2721 e->v.Call.keywords,
2722 e->v.Call.starargs,
2723 e->v.Call.kwargs);
2724}
2725
2726/* shared code between compiler_call and compiler_class */
2727static int
2728compiler_call_helper(struct compiler *c,
2729 int n, /* Args already pushed */
2730 asdl_seq *args,
2731 asdl_seq *keywords,
2732 expr_ty starargs,
2733 expr_ty kwargs)
2734{
2735 int code = 0;
2736
2737 n += asdl_seq_LEN(args);
2738 VISIT_SEQ(c, expr, args);
2739 if (keywords) {
2740 VISIT_SEQ(c, keyword, keywords);
2741 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002743 if (starargs) {
2744 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745 code |= 1;
2746 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002747 if (kwargs) {
2748 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749 code |= 2;
2750 }
2751 switch (code) {
2752 case 0:
2753 ADDOP_I(c, CALL_FUNCTION, n);
2754 break;
2755 case 1:
2756 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2757 break;
2758 case 2:
2759 ADDOP_I(c, CALL_FUNCTION_KW, n);
2760 break;
2761 case 3:
2762 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2763 break;
2764 }
2765 return 1;
2766}
2767
Nick Coghlan650f0d02007-04-15 12:05:43 +00002768
2769/* List and set comprehensions and generator expressions work by creating a
2770 nested function to perform the actual iteration. This means that the
2771 iteration variables don't leak into the current scope.
2772 The defined function is called immediately following its definition, with the
2773 result of that call being the result of the expression.
2774 The LC/SC version returns the populated container, while the GE version is
2775 flagged in symtable.c as a generator, so it returns the generator object
2776 when the function is called.
2777 This code *knows* that the loop cannot contain break, continue, or return,
2778 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2779
2780 Possible cleanups:
2781 - iterate over the generator sequence instead of using recursion
2782*/
2783
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002785compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002786 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002787 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788{
2789 /* generate code for the iterator, then each of the ifs,
2790 and then write to the element */
2791
Nick Coghlan650f0d02007-04-15 12:05:43 +00002792 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002793 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002794 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795
2796 start = compiler_new_block(c);
2797 skip = compiler_new_block(c);
2798 if_cleanup = compiler_new_block(c);
2799 anchor = compiler_new_block(c);
2800
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002801 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002802 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002803 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804
Nick Coghlan650f0d02007-04-15 12:05:43 +00002805 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002806
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807 if (gen_index == 0) {
2808 /* Receive outermost iter as an implicit argument */
2809 c->u->u_argcount = 1;
2810 ADDOP_I(c, LOAD_FAST, 0);
2811 }
2812 else {
2813 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002814 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815 ADDOP(c, GET_ITER);
2816 }
2817 compiler_use_next_block(c, start);
2818 ADDOP_JREL(c, FOR_ITER, anchor);
2819 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002820 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002822 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002823 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002825 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002826 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002827 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002829 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002831 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002832 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002833 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002834 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002835 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836
Nick Coghlan650f0d02007-04-15 12:05:43 +00002837 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002838 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002839 /* comprehension specific code */
2840 switch (type) {
2841 case COMP_GENEXP:
2842 VISIT(c, expr, elt);
2843 ADDOP(c, YIELD_VALUE);
2844 ADDOP(c, POP_TOP);
2845 break;
2846 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002847 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002848 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002849 break;
2850 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002851 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002852 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002853 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002854 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002855 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002856 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002857 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002858 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002859 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002860 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002861 default:
2862 return 0;
2863 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864
2865 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002866 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002867 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2869 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870
2871 return 1;
2872}
2873
2874static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002876 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002877{
2878 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002879 expr_ty outermost_iter;
2880
2881 outermost_iter = ((comprehension_ty)
2882 asdl_seq_GET(generators, 0))->iter;
2883
2884 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2885 goto error;
2886
2887 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002888 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002889 switch (type) {
2890 case COMP_LISTCOMP:
2891 op = BUILD_LIST;
2892 break;
2893 case COMP_SETCOMP:
2894 op = BUILD_SET;
2895 break;
2896 case COMP_DICTCOMP:
2897 op = BUILD_MAP;
2898 break;
2899 default:
2900 PyErr_Format(PyExc_SystemError,
2901 "unknown comprehension type %d", type);
2902 goto error_in_scope;
2903 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002904
Guido van Rossum992d4a32007-07-11 13:09:30 +00002905 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002906 }
2907
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002908 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002909 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002910 goto error_in_scope;
2911
2912 if (type != COMP_GENEXP) {
2913 ADDOP(c, RETURN_VALUE);
2914 }
2915
2916 co = assemble(c, 1);
2917 compiler_exit_scope(c);
2918 if (co == NULL)
2919 goto error;
2920
2921 if (!compiler_make_closure(c, co, 0))
2922 goto error;
2923 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002924
2925 VISIT(c, expr, outermost_iter);
2926 ADDOP(c, GET_ITER);
2927 ADDOP_I(c, CALL_FUNCTION, 1);
2928 return 1;
2929error_in_scope:
2930 compiler_exit_scope(c);
2931error:
2932 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002933 return 0;
2934}
2935
2936static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937compiler_genexp(struct compiler *c, expr_ty e)
2938{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002939 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002940 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002941 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002942 if (!name)
2943 return 0;
2944 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002945 assert(e->kind == GeneratorExp_kind);
2946 return compiler_comprehension(c, e, COMP_GENEXP, name,
2947 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002948 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949}
2950
2951static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002952compiler_listcomp(struct compiler *c, expr_ty e)
2953{
2954 static identifier name;
2955 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002956 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002957 if (!name)
2958 return 0;
2959 }
2960 assert(e->kind == ListComp_kind);
2961 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2962 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002963 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002964}
2965
2966static int
2967compiler_setcomp(struct compiler *c, expr_ty e)
2968{
2969 static identifier name;
2970 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002971 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002972 if (!name)
2973 return 0;
2974 }
2975 assert(e->kind == SetComp_kind);
2976 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2977 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002978 e->v.SetComp.elt, NULL);
2979}
2980
2981
2982static int
2983compiler_dictcomp(struct compiler *c, expr_ty e)
2984{
2985 static identifier name;
2986 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00002987 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00002988 if (!name)
2989 return 0;
2990 }
2991 assert(e->kind == DictComp_kind);
2992 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2993 e->v.DictComp.generators,
2994 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002995}
2996
2997
2998static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999compiler_visit_keyword(struct compiler *c, keyword_ty k)
3000{
3001 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3002 VISIT(c, expr, k->value);
3003 return 1;
3004}
3005
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003006/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007 whether they are true or false.
3008
3009 Return values: 1 for true, 0 for false, -1 for non-constant.
3010 */
3011
3012static int
3013expr_constant(expr_ty e)
3014{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003015 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003017 case Ellipsis_kind:
3018 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 case Num_kind:
3020 return PyObject_IsTrue(e->v.Num.n);
3021 case Str_kind:
3022 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003023 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003024 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003025 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003026 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003027 if (strcmp(id, "True") == 0) return 1;
3028 if (strcmp(id, "False") == 0) return 0;
3029 if (strcmp(id, "None") == 0) return 0;
3030 if (strcmp(id, "__debug__") == 0)
3031 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003032 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 default:
3034 return -1;
3035 }
3036}
3037
Guido van Rossumc2e20742006-02-27 22:32:47 +00003038/*
3039 Implements the with statement from PEP 343.
3040
3041 The semantics outlined in that PEP are as follows:
3042
3043 with EXPR as VAR:
3044 BLOCK
3045
3046 It is implemented roughly as:
3047
Thomas Wouters477c8d52006-05-27 19:21:47 +00003048 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003049 exit = context.__exit__ # not calling it
3050 value = context.__enter__()
3051 try:
3052 VAR = value # if VAR present in the syntax
3053 BLOCK
3054 finally:
3055 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003056 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003057 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003058 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003059 exit(*exc)
3060 */
3061static int
3062compiler_with(struct compiler *c, stmt_ty s)
3063{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003064 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003065
3066 assert(s->kind == With_kind);
3067
Guido van Rossumc2e20742006-02-27 22:32:47 +00003068 block = compiler_new_block(c);
3069 finally = compiler_new_block(c);
3070 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003071 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003072
Thomas Wouters477c8d52006-05-27 19:21:47 +00003073 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003074 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003075 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003076
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003077 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003078 compiler_use_next_block(c, block);
3079 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003080 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 }
3082
3083 if (s->v.With.optional_vars) {
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003084 VISIT(c, expr, s->v.With.optional_vars);
3085 }
3086 else {
3087 /* Discard result from context.__enter__() */
3088 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003089 }
3090
3091 /* BLOCK code */
3092 VISIT_SEQ(c, stmt, s->v.With.body);
3093
3094 /* End of try block; start the finally block */
3095 ADDOP(c, POP_BLOCK);
3096 compiler_pop_fblock(c, FINALLY_TRY, block);
3097
3098 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3099 compiler_use_next_block(c, finally);
3100 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003101 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003102
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003103 /* Finally block starts; context.__exit__ is on the stack under
3104 the exception or return information. Just issue our magic
3105 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003106 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003107
3108 /* Finally block ends. */
3109 ADDOP(c, END_FINALLY);
3110 compiler_pop_fblock(c, FINALLY_END, finally);
3111 return 1;
3112}
3113
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003114static int
3115compiler_visit_expr(struct compiler *c, expr_ty e)
3116{
3117 int i, n;
3118
Thomas Wouters89f507f2006-12-13 04:49:30 +00003119 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003120 set a new line number for the next instruction.
3121 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122 if (e->lineno > c->u->u_lineno) {
3123 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003124 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125 }
3126 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003127 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003129 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130 VISIT(c, expr, e->v.BinOp.left);
3131 VISIT(c, expr, e->v.BinOp.right);
3132 ADDOP(c, binop(c, e->v.BinOp.op));
3133 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135 VISIT(c, expr, e->v.UnaryOp.operand);
3136 ADDOP(c, unaryop(e->v.UnaryOp.op));
3137 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003140 case IfExp_kind:
3141 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003142 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003144 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003146 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003147 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003148 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003149 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003150 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151 }
3152 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003153 case Set_kind:
3154 n = asdl_seq_LEN(e->v.Set.elts);
3155 VISIT_SEQ(c, expr, e->v.Set.elts);
3156 ADDOP_I(c, BUILD_SET, n);
3157 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003160 case ListComp_kind:
3161 return compiler_listcomp(c, e);
3162 case SetComp_kind:
3163 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003164 case DictComp_kind:
3165 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166 case Yield_kind:
3167 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003168 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169 if (e->v.Yield.value) {
3170 VISIT(c, expr, e->v.Yield.value);
3171 }
3172 else {
3173 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3174 }
3175 ADDOP(c, YIELD_VALUE);
3176 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3183 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003184 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3186 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003187 case Bytes_kind:
3188 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003189 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003190 case Ellipsis_kind:
3191 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3192 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003194 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195 if (e->v.Attribute.ctx != AugStore)
3196 VISIT(c, expr, e->v.Attribute.value);
3197 switch (e->v.Attribute.ctx) {
3198 case AugLoad:
3199 ADDOP(c, DUP_TOP);
3200 /* Fall through to load */
3201 case Load:
3202 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3203 break;
3204 case AugStore:
3205 ADDOP(c, ROT_TWO);
3206 /* Fall through to save */
3207 case Store:
3208 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3209 break;
3210 case Del:
3211 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3212 break;
3213 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003214 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003215 PyErr_SetString(PyExc_SystemError,
3216 "param invalid in attribute expression");
3217 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 }
3219 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003220 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 switch (e->v.Subscript.ctx) {
3222 case AugLoad:
3223 VISIT(c, expr, e->v.Subscript.value);
3224 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3225 break;
3226 case Load:
3227 VISIT(c, expr, e->v.Subscript.value);
3228 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3229 break;
3230 case AugStore:
3231 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3232 break;
3233 case Store:
3234 VISIT(c, expr, e->v.Subscript.value);
3235 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3236 break;
3237 case Del:
3238 VISIT(c, expr, e->v.Subscript.value);
3239 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3240 break;
3241 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003242 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003243 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003244 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003245 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246 }
3247 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003248 case Starred_kind:
3249 switch (e->v.Starred.ctx) {
3250 case Store:
3251 /* In all legitimate cases, the Starred node was already replaced
3252 * by compiler_list/compiler_tuple. XXX: is that okay? */
3253 return compiler_error(c,
3254 "starred assignment target must be in a list or tuple");
3255 default:
3256 return compiler_error(c,
3257 "can use starred expression only as assignment target");
3258 }
3259 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003260 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3262 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003265 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266 return compiler_tuple(c, e);
3267 }
3268 return 1;
3269}
3270
3271static int
3272compiler_augassign(struct compiler *c, stmt_ty s)
3273{
3274 expr_ty e = s->v.AugAssign.target;
3275 expr_ty auge;
3276
3277 assert(s->kind == AugAssign_kind);
3278
3279 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003280 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003282 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003283 if (auge == NULL)
3284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285 VISIT(c, expr, auge);
3286 VISIT(c, expr, s->v.AugAssign.value);
3287 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3288 auge->v.Attribute.ctx = AugStore;
3289 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290 break;
3291 case Subscript_kind:
3292 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003293 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003294 if (auge == NULL)
3295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296 VISIT(c, expr, auge);
3297 VISIT(c, expr, s->v.AugAssign.value);
3298 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003299 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003301 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003303 if (!compiler_nameop(c, e->v.Name.id, Load))
3304 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305 VISIT(c, expr, s->v.AugAssign.value);
3306 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3307 return compiler_nameop(c, e->v.Name.id, Store);
3308 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003309 PyErr_Format(PyExc_SystemError,
3310 "invalid node type (%d) for augmented assignment",
3311 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003312 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313 }
3314 return 1;
3315}
3316
3317static int
3318compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3319{
3320 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003321 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3322 PyErr_SetString(PyExc_SystemError,
3323 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003325 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326 f = &c->u->u_fblock[c->u->u_nfblocks++];
3327 f->fb_type = t;
3328 f->fb_block = b;
3329 return 1;
3330}
3331
3332static void
3333compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3334{
3335 struct compiler_unit *u = c->u;
3336 assert(u->u_nfblocks > 0);
3337 u->u_nfblocks--;
3338 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3339 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3340}
3341
Thomas Wouters89f507f2006-12-13 04:49:30 +00003342static int
3343compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003344 int i;
3345 struct compiler_unit *u = c->u;
3346 for (i = 0; i < u->u_nfblocks; ++i) {
3347 if (u->u_fblock[i].fb_type == LOOP)
3348 return 1;
3349 }
3350 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003351}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352/* Raises a SyntaxError and returns 0.
3353 If something goes wrong, a different exception may be raised.
3354*/
3355
3356static int
3357compiler_error(struct compiler *c, const char *errstr)
3358{
3359 PyObject *loc;
3360 PyObject *u = NULL, *v = NULL;
3361
3362 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3363 if (!loc) {
3364 Py_INCREF(Py_None);
3365 loc = Py_None;
3366 }
3367 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3368 Py_None, loc);
3369 if (!u)
3370 goto exit;
3371 v = Py_BuildValue("(zO)", errstr, u);
3372 if (!v)
3373 goto exit;
3374 PyErr_SetObject(PyExc_SyntaxError, v);
3375 exit:
3376 Py_DECREF(loc);
3377 Py_XDECREF(u);
3378 Py_XDECREF(v);
3379 return 0;
3380}
3381
3382static int
3383compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003384 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003386 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003388 /* XXX this code is duplicated */
3389 switch (ctx) {
3390 case AugLoad: /* fall through to Load */
3391 case Load: op = BINARY_SUBSCR; break;
3392 case AugStore:/* fall through to Store */
3393 case Store: op = STORE_SUBSCR; break;
3394 case Del: op = DELETE_SUBSCR; break;
3395 case Param:
3396 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003397 "invalid %s kind %d in subscript\n",
3398 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003399 return 0;
3400 }
3401 if (ctx == AugLoad) {
3402 ADDOP_I(c, DUP_TOPX, 2);
3403 }
3404 else if (ctx == AugStore) {
3405 ADDOP(c, ROT_THREE);
3406 }
3407 ADDOP(c, op);
3408 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003409}
3410
3411static int
3412compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3413{
3414 int n = 2;
3415 assert(s->kind == Slice_kind);
3416
3417 /* only handles the cases where BUILD_SLICE is emitted */
3418 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003419 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420 }
3421 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003422 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003426 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427 }
3428 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003429 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430 }
3431
3432 if (s->v.Slice.step) {
3433 n++;
3434 VISIT(c, expr, s->v.Slice.step);
3435 }
3436 ADDOP_I(c, BUILD_SLICE, n);
3437 return 1;
3438}
3439
3440static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3442 expr_context_ty ctx)
3443{
3444 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003445 case Slice_kind:
3446 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447 case Index_kind:
3448 VISIT(c, expr, s->v.Index.value);
3449 break;
3450 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003451 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003452 PyErr_SetString(PyExc_SystemError,
3453 "extended slice invalid in nested slice");
3454 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455 }
3456 return 1;
3457}
3458
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459static int
3460compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3461{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003462 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003463 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003464 case Index_kind:
3465 kindname = "index";
3466 if (ctx != AugStore) {
3467 VISIT(c, expr, s->v.Index.value);
3468 }
3469 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003470 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003471 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003472 if (ctx != AugStore) {
3473 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474 return 0;
3475 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003476 break;
3477 case ExtSlice_kind:
3478 kindname = "extended slice";
3479 if (ctx != AugStore) {
3480 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3481 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003482 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003483 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003484 if (!compiler_visit_nested_slice(c, sub, ctx))
3485 return 0;
3486 }
3487 ADDOP_I(c, BUILD_TUPLE, n);
3488 }
3489 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003490 default:
3491 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003492 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003493 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003495 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496}
3497
Thomas Wouters89f507f2006-12-13 04:49:30 +00003498/* End of the compiler section, beginning of the assembler section */
3499
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500/* do depth-first search of basic block graph, starting with block.
3501 post records the block indices in post-order.
3502
3503 XXX must handle implicit jumps from one block to next
3504*/
3505
Thomas Wouters89f507f2006-12-13 04:49:30 +00003506struct assembler {
3507 PyObject *a_bytecode; /* string containing bytecode */
3508 int a_offset; /* offset into bytecode */
3509 int a_nblocks; /* number of reachable blocks */
3510 basicblock **a_postorder; /* list of blocks in dfs postorder */
3511 PyObject *a_lnotab; /* string containing lnotab */
3512 int a_lnotab_off; /* offset into lnotab */
3513 int a_lineno; /* last lineno of emitted instruction */
3514 int a_lineno_off; /* bytecode offset of last lineno */
3515};
3516
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517static void
3518dfs(struct compiler *c, basicblock *b, struct assembler *a)
3519{
3520 int i;
3521 struct instr *instr = NULL;
3522
3523 if (b->b_seen)
3524 return;
3525 b->b_seen = 1;
3526 if (b->b_next != NULL)
3527 dfs(c, b->b_next, a);
3528 for (i = 0; i < b->b_iused; i++) {
3529 instr = &b->b_instr[i];
3530 if (instr->i_jrel || instr->i_jabs)
3531 dfs(c, instr->i_target, a);
3532 }
3533 a->a_postorder[a->a_nblocks++] = b;
3534}
3535
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003536static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3538{
Neil Schemenauere441cb72009-10-14 19:14:38 +00003539 int i, target_depth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 struct instr *instr;
3541 if (b->b_seen || b->b_startdepth >= depth)
3542 return maxdepth;
3543 b->b_seen = 1;
3544 b->b_startdepth = depth;
3545 for (i = 0; i < b->b_iused; i++) {
3546 instr = &b->b_instr[i];
3547 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3548 if (depth > maxdepth)
3549 maxdepth = depth;
3550 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3551 if (instr->i_jrel || instr->i_jabs) {
Neil Schemenauere441cb72009-10-14 19:14:38 +00003552 target_depth = depth;
3553 if (instr->i_opcode == FOR_ITER) {
3554 target_depth = depth-2;
3555 } else if (instr->i_opcode == SETUP_FINALLY ||
3556 instr->i_opcode == SETUP_EXCEPT) {
3557 target_depth = depth+3;
3558 if (target_depth > maxdepth)
3559 maxdepth = target_depth;
3560 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 maxdepth = stackdepth_walk(c, instr->i_target,
Neil Schemenauere441cb72009-10-14 19:14:38 +00003562 target_depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 if (instr->i_opcode == JUMP_ABSOLUTE ||
3564 instr->i_opcode == JUMP_FORWARD) {
3565 goto out; /* remaining code is dead */
3566 }
3567 }
3568 }
3569 if (b->b_next)
3570 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3571out:
3572 b->b_seen = 0;
3573 return maxdepth;
3574}
3575
3576/* Find the flow path that needs the largest stack. We assume that
3577 * cycles in the flow graph have no net effect on the stack depth.
3578 */
3579static int
3580stackdepth(struct compiler *c)
3581{
3582 basicblock *b, *entryblock;
3583 entryblock = NULL;
3584 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3585 b->b_seen = 0;
3586 b->b_startdepth = INT_MIN;
3587 entryblock = b;
3588 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003589 if (!entryblock)
3590 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591 return stackdepth_walk(c, entryblock, 0, 0);
3592}
3593
3594static int
3595assemble_init(struct assembler *a, int nblocks, int firstlineno)
3596{
3597 memset(a, 0, sizeof(struct assembler));
3598 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003599 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 if (!a->a_bytecode)
3601 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003602 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003603 if (!a->a_lnotab)
3604 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003605 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3606 PyErr_NoMemory();
3607 return 0;
3608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003610 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003611 if (!a->a_postorder) {
3612 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615 return 1;
3616}
3617
3618static void
3619assemble_free(struct assembler *a)
3620{
3621 Py_XDECREF(a->a_bytecode);
3622 Py_XDECREF(a->a_lnotab);
3623 if (a->a_postorder)
3624 PyObject_Free(a->a_postorder);
3625}
3626
3627/* Return the size of a basic block in bytes. */
3628
3629static int
3630instrsize(struct instr *instr)
3631{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003632 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003633 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003634 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003635 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3636 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637}
3638
3639static int
3640blocksize(basicblock *b)
3641{
3642 int i;
3643 int size = 0;
3644
3645 for (i = 0; i < b->b_iused; i++)
3646 size += instrsize(&b->b_instr[i]);
3647 return size;
3648}
3649
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003650/* Appends a pair to the end of the line number table, a_lnotab, representing
3651 the instruction's bytecode offset and line number. See
3652 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003653
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003654static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003656{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 int d_bytecode, d_lineno;
3658 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003659 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660
3661 d_bytecode = a->a_offset - a->a_lineno_off;
3662 d_lineno = i->i_lineno - a->a_lineno;
3663
3664 assert(d_bytecode >= 0);
3665 assert(d_lineno >= 0);
3666
Christian Heimes2202f872008-02-06 14:31:34 +00003667 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003668 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003669
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003671 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003673 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003675 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003677 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003678 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003679 else {
3680 PyErr_NoMemory();
3681 return 0;
3682 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003683 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003685 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003686 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003687 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003688 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689 *lnotab++ = 255;
3690 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003691 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003692 d_bytecode -= ncodes * 255;
3693 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003694 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 assert(d_bytecode <= 255);
3696 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003697 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003699 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003701 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003703 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003705 else {
3706 PyErr_NoMemory();
3707 return 0;
3708 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003709 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003711 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003712 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003713 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003714 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003715 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003717 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003719 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 d_lineno -= ncodes * 255;
3722 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003723 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003724
Christian Heimes72b710a2008-05-26 13:28:38 +00003725 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003727 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003728 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003729 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003730 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003731 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003732
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003733 a->a_lnotab_off += 2;
3734 if (d_bytecode) {
3735 *lnotab++ = d_bytecode;
3736 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003737 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003738 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 *lnotab++ = 0;
3740 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003741 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742 a->a_lineno = i->i_lineno;
3743 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003744 return 1;
3745}
3746
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747/* assemble_emit()
3748 Extend the bytecode with a new instruction.
3749 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003750*/
3751
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003752static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003754{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003755 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003756 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 char *code;
3758
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003759 size = instrsize(i);
3760 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003762 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003763 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003765 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003767 if (len > PY_SSIZE_T_MAX / 2)
3768 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003769 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003770 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003771 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003772 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003774 if (size == 6) {
3775 assert(i->i_hasarg);
3776 *code++ = (char)EXTENDED_ARG;
3777 *code++ = ext & 0xff;
3778 *code++ = ext >> 8;
3779 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003780 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003781 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003782 if (i->i_hasarg) {
3783 assert(size == 3 || size == 6);
3784 *code++ = arg & 0xff;
3785 *code++ = arg >> 8;
3786 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003788}
3789
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003790static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003792{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793 basicblock *b;
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003794 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003795 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003796
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797 /* Compute the size of each block and fixup jump args.
3798 Replace block pointer with position in bytecode. */
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003799 do {
3800 totsize = 0;
3801 for (i = a->a_nblocks - 1; i >= 0; i--) {
3802 b = a->a_postorder[i];
3803 bsize = blocksize(b);
3804 b->b_offset = totsize;
3805 totsize += bsize;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003806 }
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003807 last_extended_arg_count = extended_arg_count;
3808 extended_arg_count = 0;
3809 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3810 bsize = b->b_offset;
3811 for (i = 0; i < b->b_iused; i++) {
3812 struct instr *instr = &b->b_instr[i];
3813 /* Relative jumps are computed relative to
3814 the instruction pointer after fetching
3815 the jump instruction.
3816 */
3817 bsize += instrsize(instr);
3818 if (instr->i_jabs)
3819 instr->i_oparg = instr->i_target->b_offset;
3820 else if (instr->i_jrel) {
3821 int delta = instr->i_target->b_offset - bsize;
3822 instr->i_oparg = delta;
3823 }
3824 else
3825 continue;
3826 if (instr->i_oparg > 0xffff)
3827 extended_arg_count++;
3828 }
3829 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003830
3831 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003832 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003833 with a better solution.
3834
Neal Norwitzf1d50682005-10-23 23:00:41 +00003835 The issue is that in the first loop blocksize() is called
3836 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003837 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003838 i_oparg is calculated in the second loop above.
3839
3840 So we loop until we stop seeing new EXTENDED_ARGs.
3841 The only EXTENDED_ARGs that could be popping up are
3842 ones in jump instructions. So this should converge
3843 fairly quickly.
3844 */
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003845 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003846}
3847
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003848static PyObject *
3849dict_keys_inorder(PyObject *dict, int offset)
3850{
3851 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003852 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003853
3854 tuple = PyTuple_New(size);
3855 if (tuple == NULL)
3856 return NULL;
3857 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003858 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003859 /* The keys of the dictionary are tuples. (see compiler_add_o)
3860 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003861 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003862 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003863 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003864 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003865 PyTuple_SET_ITEM(tuple, i - offset, k);
3866 }
3867 return tuple;
3868}
3869
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003870static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003872{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 PySTEntryObject *ste = c->u->u_ste;
3874 int flags = 0, n;
3875 if (ste->ste_type != ModuleBlock)
3876 flags |= CO_NEWLOCALS;
3877 if (ste->ste_type == FunctionBlock) {
3878 if (!ste->ste_unoptimized)
3879 flags |= CO_OPTIMIZED;
3880 if (ste->ste_nested)
3881 flags |= CO_NESTED;
3882 if (ste->ste_generator)
3883 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003884 if (ste->ste_varargs)
3885 flags |= CO_VARARGS;
3886 if (ste->ste_varkeywords)
3887 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003888 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003889
3890 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003891 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 n = PyDict_Size(c->u->u_freevars);
3894 if (n < 0)
3895 return -1;
3896 if (n == 0) {
3897 n = PyDict_Size(c->u->u_cellvars);
3898 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003899 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 if (n == 0) {
3901 flags |= CO_NOFREE;
3902 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003903 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003904
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003905 return flags;
3906}
3907
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908static PyCodeObject *
3909makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003910{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911 PyObject *tmp;
3912 PyCodeObject *co = NULL;
3913 PyObject *consts = NULL;
3914 PyObject *names = NULL;
3915 PyObject *varnames = NULL;
3916 PyObject *filename = NULL;
3917 PyObject *name = NULL;
3918 PyObject *freevars = NULL;
3919 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003920 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003922
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923 tmp = dict_keys_inorder(c->u->u_consts, 0);
3924 if (!tmp)
3925 goto error;
3926 consts = PySequence_List(tmp); /* optimize_code requires a list */
3927 Py_DECREF(tmp);
3928
3929 names = dict_keys_inorder(c->u->u_names, 0);
3930 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3931 if (!consts || !names || !varnames)
3932 goto error;
3933
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003934 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3935 if (!cellvars)
3936 goto error;
3937 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3938 if (!freevars)
3939 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003940 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003941 if (!filename)
3942 goto error;
3943
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003944 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945 flags = compute_code_flags(c);
3946 if (flags < 0)
3947 goto error;
3948
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003949 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003950 if (!bytecode)
3951 goto error;
3952
3953 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3954 if (!tmp)
3955 goto error;
3956 Py_DECREF(consts);
3957 consts = tmp;
3958
Guido van Rossum4f72a782006-10-27 23:31:49 +00003959 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3960 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003961 bytecode, consts, names, varnames,
3962 freevars, cellvars,
3963 filename, c->u->u_name,
3964 c->u->u_firstlineno,
3965 a->a_lnotab);
3966 error:
3967 Py_XDECREF(consts);
3968 Py_XDECREF(names);
3969 Py_XDECREF(varnames);
3970 Py_XDECREF(filename);
3971 Py_XDECREF(name);
3972 Py_XDECREF(freevars);
3973 Py_XDECREF(cellvars);
3974 Py_XDECREF(bytecode);
3975 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003976}
3977
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003978
3979/* For debugging purposes only */
3980#if 0
3981static void
3982dump_instr(const struct instr *i)
3983{
3984 const char *jrel = i->i_jrel ? "jrel " : "";
3985 const char *jabs = i->i_jabs ? "jabs " : "";
3986 char arg[128];
3987
3988 *arg = '\0';
3989 if (i->i_hasarg)
3990 sprintf(arg, "arg: %d ", i->i_oparg);
3991
3992 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3993 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3994}
3995
3996static void
3997dump_basicblock(const basicblock *b)
3998{
3999 const char *seen = b->b_seen ? "seen " : "";
4000 const char *b_return = b->b_return ? "return " : "";
4001 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4002 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4003 if (b->b_instr) {
4004 int i;
4005 for (i = 0; i < b->b_iused; i++) {
4006 fprintf(stderr, " [%02d] ", i);
4007 dump_instr(b->b_instr + i);
4008 }
4009 }
4010}
4011#endif
4012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004013static PyCodeObject *
4014assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004015{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004016 basicblock *b, *entryblock;
4017 struct assembler a;
4018 int i, j, nblocks;
4019 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004021 /* Make sure every block that falls off the end returns None.
4022 XXX NEXT_BLOCK() isn't quite right, because if the last
4023 block ends with a jump or return b_next shouldn't set.
4024 */
4025 if (!c->u->u_curblock->b_return) {
4026 NEXT_BLOCK(c);
4027 if (addNone)
4028 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4029 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004030 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004031
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004032 nblocks = 0;
4033 entryblock = NULL;
4034 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4035 nblocks++;
4036 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004037 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004038
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004039 /* Set firstlineno if it wasn't explicitly set. */
4040 if (!c->u->u_firstlineno) {
4041 if (entryblock && entryblock->b_instr)
4042 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4043 else
4044 c->u->u_firstlineno = 1;
4045 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004046 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4047 goto error;
4048 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004050 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004051 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004053 /* Emit code in reverse postorder from dfs. */
4054 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004055 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004056 for (j = 0; j < b->b_iused; j++)
4057 if (!assemble_emit(&a, &b->b_instr[j]))
4058 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004059 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004060
Christian Heimes72b710a2008-05-26 13:28:38 +00004061 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004062 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004063 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004064 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004065
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066 co = makecode(c, &a);
4067 error:
4068 assemble_free(&a);
4069 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004070}