blob: d8fb47b16ecb5de890742fab4f2d4fcb9f6dbcb2 [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;
Mark Dickinson42e30552009-10-15 19:55:18 +0000898 unsigned char *p;
Christian Heimes400adb02008-02-01 08:12:03 +0000899 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000900
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000901 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000902 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
903 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000904 d = PyFloat_AS_DOUBLE(o);
905 p = (unsigned char*) &d;
906 /* all we need is to make the tuple different in either the 0.0
907 * or -0.0 case from all others, just to avoid the "coercion".
908 */
909 if (*p==0 && p[sizeof(double)-1]==0)
910 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
911 else
912 t = PyTuple_Pack(2, o, o->ob_type);
913 }
914 else if (PyComplex_Check(o)) {
Mark Dickinson42e30552009-10-15 19:55:18 +0000915 Py_complex z;
916 int real_part_zero, imag_part_zero;
917 unsigned char *q;
Christian Heimes400adb02008-02-01 08:12:03 +0000918 /* complex case is even messier: we need to make complex(x,
919 0.) different from complex(x, -0.) and complex(0., y)
920 different from complex(-0., y), for any x and y. In
921 particular, all four complex zeros should be
922 distinguished.*/
923 z = PyComplex_AsCComplex(o);
924 p = (unsigned char*) &(z.real);
925 q = (unsigned char*) &(z.imag);
926 /* all that matters here is that on IEEE platforms
927 real_part_zero will be true if z.real == 0., and false if
928 z.real == -0. In fact, real_part_zero will also be true
929 for some other rarely occurring nonzero floats, but this
930 doesn't matter. Similar comments apply to
931 imag_part_zero. */
932 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
933 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
934 if (real_part_zero && imag_part_zero) {
935 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
936 }
937 else if (real_part_zero && !imag_part_zero) {
938 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
939 }
940 else if (!real_part_zero && imag_part_zero) {
941 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
942 }
943 else {
944 t = PyTuple_Pack(2, o, o->ob_type);
945 }
946 }
947 else {
948 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000949 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000950 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000951 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
953 v = PyDict_GetItem(dict, t);
954 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000955 if (PyErr_Occurred())
956 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000958 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959 if (!v) {
960 Py_DECREF(t);
961 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000962 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963 if (PyDict_SetItem(dict, t, v) < 0) {
964 Py_DECREF(t);
965 Py_DECREF(v);
966 return -1;
967 }
968 Py_DECREF(v);
969 }
970 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000971 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000973 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974}
975
976static int
977compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
978 PyObject *o)
979{
980 int arg = compiler_add_o(c, dict, o);
981 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983 return compiler_addop_i(c, opcode, arg);
984}
985
986static int
987compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000988 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989{
990 int arg;
991 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
992 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000993 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994 arg = compiler_add_o(c, dict, mangled);
995 Py_DECREF(mangled);
996 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000997 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998 return compiler_addop_i(c, opcode, arg);
999}
1000
1001/* Add an opcode with an integer argument.
1002 Returns 0 on failure, 1 on success.
1003*/
1004
1005static int
1006compiler_addop_i(struct compiler *c, int opcode, int oparg)
1007{
1008 struct instr *i;
1009 int off;
1010 off = compiler_next_instr(c, c->u->u_curblock);
1011 if (off < 0)
1012 return 0;
1013 i = &c->u->u_curblock->b_instr[off];
1014 i->i_opcode = opcode;
1015 i->i_oparg = oparg;
1016 i->i_hasarg = 1;
1017 compiler_set_lineno(c, off);
1018 return 1;
1019}
1020
1021static int
1022compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1023{
1024 struct instr *i;
1025 int off;
1026
1027 assert(b != NULL);
1028 off = compiler_next_instr(c, c->u->u_curblock);
1029 if (off < 0)
1030 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031 i = &c->u->u_curblock->b_instr[off];
1032 i->i_opcode = opcode;
1033 i->i_target = b;
1034 i->i_hasarg = 1;
1035 if (absolute)
1036 i->i_jabs = 1;
1037 else
1038 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001039 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040 return 1;
1041}
1042
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001043/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1044 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045 it as the current block. NEXT_BLOCK() also creates an implicit jump
1046 from the current block to the new block.
1047*/
1048
Thomas Wouters89f507f2006-12-13 04:49:30 +00001049/* The returns inside these macros make it impossible to decref objects
1050 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051*/
1052
1053
1054#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001055 if (compiler_use_new_block((C)) == NULL) \
1056 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057}
1058
1059#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001060 if (compiler_next_block((C)) == NULL) \
1061 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062}
1063
1064#define ADDOP(C, OP) { \
1065 if (!compiler_addop((C), (OP))) \
1066 return 0; \
1067}
1068
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001069#define ADDOP_IN_SCOPE(C, OP) { \
1070 if (!compiler_addop((C), (OP))) { \
1071 compiler_exit_scope(c); \
1072 return 0; \
1073 } \
1074}
1075
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076#define ADDOP_O(C, OP, O, TYPE) { \
1077 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1078 return 0; \
1079}
1080
1081#define ADDOP_NAME(C, OP, O, TYPE) { \
1082 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1083 return 0; \
1084}
1085
1086#define ADDOP_I(C, OP, O) { \
1087 if (!compiler_addop_i((C), (OP), (O))) \
1088 return 0; \
1089}
1090
1091#define ADDOP_JABS(C, OP, O) { \
1092 if (!compiler_addop_j((C), (OP), (O), 1)) \
1093 return 0; \
1094}
1095
1096#define ADDOP_JREL(C, OP, O) { \
1097 if (!compiler_addop_j((C), (OP), (O), 0)) \
1098 return 0; \
1099}
1100
1101/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1102 the ASDL name to synthesize the name of the C type and the visit function.
1103*/
1104
1105#define VISIT(C, TYPE, V) {\
1106 if (!compiler_visit_ ## TYPE((C), (V))) \
1107 return 0; \
1108}
1109
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001110#define VISIT_IN_SCOPE(C, TYPE, V) {\
1111 if (!compiler_visit_ ## TYPE((C), (V))) { \
1112 compiler_exit_scope(c); \
1113 return 0; \
1114 } \
1115}
1116
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117#define VISIT_SLICE(C, V, CTX) {\
1118 if (!compiler_visit_slice((C), (V), (CTX))) \
1119 return 0; \
1120}
1121
1122#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001123 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001125 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127 if (!compiler_visit_ ## TYPE((C), elt)) \
1128 return 0; \
1129 } \
1130}
1131
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001132#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001133 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001134 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001135 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001136 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001137 if (!compiler_visit_ ## TYPE((C), elt)) { \
1138 compiler_exit_scope(c); \
1139 return 0; \
1140 } \
1141 } \
1142}
1143
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144static int
1145compiler_isdocstring(stmt_ty s)
1146{
1147 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001148 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149 return s->v.Expr.value->kind == Str_kind;
1150}
1151
1152/* Compile a sequence of statements, checking for a docstring. */
1153
1154static int
1155compiler_body(struct compiler *c, asdl_seq *stmts)
1156{
1157 int i = 0;
1158 stmt_ty st;
1159
1160 if (!asdl_seq_LEN(stmts))
1161 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001162 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001163 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1164 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 i = 1;
1166 VISIT(c, expr, st->v.Expr.value);
1167 if (!compiler_nameop(c, __doc__, Store))
1168 return 0;
1169 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001170 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001171 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 return 1;
1173}
1174
1175static PyCodeObject *
1176compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001177{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001178 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001179 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180 static PyObject *module;
1181 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001182 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 if (!module)
1184 return NULL;
1185 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001186 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1187 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001188 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 switch (mod->kind) {
1190 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001191 if (!compiler_body(c, mod->v.Module.body)) {
1192 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001194 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 break;
1196 case Interactive_kind:
1197 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001198 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 break;
1201 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001202 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001203 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 break;
1205 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001206 PyErr_SetString(PyExc_SystemError,
1207 "suite should not be possible");
1208 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001210 PyErr_Format(PyExc_SystemError,
1211 "module kind %d should not be possible",
1212 mod->kind);
1213 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001214 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215 co = assemble(c, addNone);
1216 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001217 return co;
1218}
1219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220/* The test for LOCAL must come before the test for FREE in order to
1221 handle classes where name is both local and free. The local var is
1222 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001223*/
1224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225static int
1226get_ref_type(struct compiler *c, PyObject *name)
1227{
1228 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001229 if (scope == 0) {
1230 char buf[350];
1231 PyOS_snprintf(buf, sizeof(buf),
1232 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001233 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001234 PyBytes_AS_STRING(name),
1235 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001236 PyObject_REPR(c->u->u_ste->ste_id),
1237 c->c_filename,
1238 PyObject_REPR(c->u->u_ste->ste_symbols),
1239 PyObject_REPR(c->u->u_varnames),
1240 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001242 Py_FatalError(buf);
1243 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001244
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
1248static int
1249compiler_lookup_arg(PyObject *dict, PyObject *name)
1250{
1251 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001252 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001254 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001256 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001258 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001259 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260}
1261
1262static int
1263compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1264{
1265 int i, free = PyCode_GetNumFree(co);
1266 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001267 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1268 ADDOP_I(c, MAKE_FUNCTION, args);
1269 return 1;
1270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271 for (i = 0; i < free; ++i) {
1272 /* Bypass com_addop_varname because it will generate
1273 LOAD_DEREF but LOAD_CLOSURE is needed.
1274 */
1275 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1276 int arg, reftype;
1277
1278 /* Special case: If a class contains a method with a
1279 free variable that has the same name as a method,
1280 the name will be considered free *and* local in the
1281 class. It should be handled by the closure, as
1282 well as by the normal name loookup logic.
1283 */
1284 reftype = get_ref_type(c, name);
1285 if (reftype == CELL)
1286 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1287 else /* (reftype == FREE) */
1288 arg = compiler_lookup_arg(c->u->u_freevars, name);
1289 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001290 fprintf(stderr,
1291 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 "freevars of %s: %s\n",
1293 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001294 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001296 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297 PyObject_REPR(co->co_freevars));
1298 Py_FatalError("compiler_make_closure()");
1299 }
1300 ADDOP_I(c, LOAD_CLOSURE, arg);
1301 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001302 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001304 ADDOP_I(c, MAKE_CLOSURE, args);
1305 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306}
1307
1308static int
1309compiler_decorators(struct compiler *c, asdl_seq* decos)
1310{
1311 int i;
1312
1313 if (!decos)
1314 return 1;
1315
1316 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001317 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318 }
1319 return 1;
1320}
1321
1322static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001323compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1324 asdl_seq *kw_defaults)
1325{
1326 int i, default_count = 0;
1327 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001328 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001329 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1330 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001331 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001332 if (!compiler_visit_expr(c, default_)) {
1333 return -1;
1334 }
1335 default_count++;
1336 }
1337 }
1338 return default_count;
1339}
1340
1341static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001342compiler_visit_argannotation(struct compiler *c, identifier id,
1343 expr_ty annotation, PyObject *names)
1344{
1345 if (annotation) {
1346 VISIT(c, expr, annotation);
1347 if (PyList_Append(names, id))
1348 return -1;
1349 }
1350 return 0;
1351}
1352
1353static int
1354compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1355 PyObject *names)
1356{
1357 int i, error;
1358 for (i = 0; i < asdl_seq_LEN(args); i++) {
1359 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001360 error = compiler_visit_argannotation(
1361 c,
1362 arg->arg,
1363 arg->annotation,
1364 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001365 if (error)
1366 return error;
1367 }
1368 return 0;
1369}
1370
1371static int
1372compiler_visit_annotations(struct compiler *c, arguments_ty args,
1373 expr_ty returns)
1374{
Guido van Rossum0240b922007-02-26 21:23:50 +00001375 /* Push arg annotations and a list of the argument names. Return the #
1376 of items pushed. The expressions are evaluated out-of-order wrt the
1377 source code.
1378
1379 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1380 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001381 static identifier return_str;
1382 PyObject *names;
1383 int len;
1384 names = PyList_New(0);
1385 if (!names)
1386 return -1;
1387
1388 if (compiler_visit_argannotations(c, args->args, names))
1389 goto error;
1390 if (args->varargannotation &&
1391 compiler_visit_argannotation(c, args->vararg,
1392 args->varargannotation, names))
1393 goto error;
1394 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1395 goto error;
1396 if (args->kwargannotation &&
1397 compiler_visit_argannotation(c, args->kwarg,
1398 args->kwargannotation, names))
1399 goto error;
1400
1401 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001402 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001403 if (!return_str)
1404 goto error;
1405 }
1406 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1407 goto error;
1408 }
1409
1410 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001411 if (len > 65534) {
1412 /* len must fit in 16 bits, and len is incremented below */
1413 PyErr_SetString(PyExc_SyntaxError,
1414 "too many annotations");
1415 goto error;
1416 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001417 if (len) {
1418 /* convert names to a tuple and place on stack */
1419 PyObject *elt;
1420 int i;
1421 PyObject *s = PyTuple_New(len);
1422 if (!s)
1423 goto error;
1424 for (i = 0; i < len; i++) {
1425 elt = PyList_GET_ITEM(names, i);
1426 Py_INCREF(elt);
1427 PyTuple_SET_ITEM(s, i, elt);
1428 }
1429 ADDOP_O(c, LOAD_CONST, s, consts);
1430 Py_DECREF(s);
1431 len++; /* include the just-pushed tuple */
1432 }
1433 Py_DECREF(names);
1434 return len;
1435
1436error:
1437 Py_DECREF(names);
1438 return -1;
1439}
1440
1441static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442compiler_function(struct compiler *c, stmt_ty s)
1443{
1444 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001445 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001447 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001448 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001449 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001450 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001451 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452
1453 assert(s->kind == FunctionDef_kind);
1454
1455 if (!compiler_decorators(c, decos))
1456 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001457 if (args->kwonlyargs) {
1458 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1459 args->kw_defaults);
1460 if (res < 0)
1461 return 0;
1462 kw_default_count = res;
1463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464 if (args->defaults)
1465 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001466 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001467 if (num_annotations < 0)
1468 return 0;
1469 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001470
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1472 s->lineno))
1473 return 0;
1474
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001475 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001476 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001477 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001478 first_const = st->v.Expr.value->v.Str.s;
1479 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001480 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001482 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001485 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001487 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001489 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1490 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491 }
1492 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001493 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494 if (co == NULL)
1495 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
Guido van Rossum4f72a782006-10-27 23:31:49 +00001497 arglength = asdl_seq_LEN(args->defaults);
1498 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001499 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001500 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001501 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502
Neal Norwitzc1505362006-12-28 06:47:50 +00001503 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1505 ADDOP_I(c, CALL_FUNCTION, 1);
1506 }
1507
1508 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1509}
1510
1511static int
1512compiler_class(struct compiler *c, stmt_ty s)
1513{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001515 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001516 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001517 asdl_seq* decos = s->v.ClassDef.decorator_list;
1518
1519 if (!compiler_decorators(c, decos))
1520 return 0;
1521
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001522 /* ultimately generate code for:
1523 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1524 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001525 <func> is a function/closure created from the class body;
1526 it has a single argument (__locals__) where the dict
1527 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001528 <name> is the class name
1529 <bases> is the positional arguments and *varargs argument
1530 <keywords> is the keyword arguments and **kwds argument
1531 This borrows from compiler_call.
1532 */
1533
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001534 /* 1. compile the class body into a code object */
1535 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1536 return 0;
1537 /* this block represents what we do in the new scope */
1538 {
1539 /* use the class name for name mangling */
1540 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001541 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001542 c->u->u_private = s->v.ClassDef.name;
1543 /* force it to have one mandatory argument */
1544 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001545 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001546 ADDOP_I(c, LOAD_FAST, 0);
1547 /* ... and store it into f_locals */
1548 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001549 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001550 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001551 if (!str || !compiler_nameop(c, str, Load)) {
1552 Py_XDECREF(str);
1553 compiler_exit_scope(c);
1554 return 0;
1555 }
1556 Py_DECREF(str);
1557 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001558 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001559 if (!str || !compiler_nameop(c, str, Store)) {
1560 Py_XDECREF(str);
1561 compiler_exit_scope(c);
1562 return 0;
1563 }
1564 Py_DECREF(str);
1565 /* compile the body proper */
1566 if (!compiler_body(c, s->v.ClassDef.body)) {
1567 compiler_exit_scope(c);
1568 return 0;
1569 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001570 /* return the (empty) __class__ cell */
1571 str = PyUnicode_InternFromString("__class__");
1572 if (str == NULL) {
1573 compiler_exit_scope(c);
1574 return 0;
1575 }
1576 i = compiler_lookup_arg(c->u->u_cellvars, str);
1577 Py_DECREF(str);
1578 if (i == -1) {
1579 /* This happens when nobody references the cell */
1580 PyErr_Clear();
1581 /* Return None */
1582 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1583 }
1584 else {
1585 /* Return the cell where to store __class__ */
1586 ADDOP_I(c, LOAD_CLOSURE, i);
1587 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001588 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1589 /* create the code object */
1590 co = assemble(c, 1);
1591 }
1592 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001593 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594 if (co == NULL)
1595 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001597 /* 2. load the 'build_class' function */
1598 ADDOP(c, LOAD_BUILD_CLASS);
1599
1600 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001601 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001602 Py_DECREF(co);
1603
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001604 /* 4. load class name */
1605 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1606
1607 /* 5. generate the rest of the code for the call */
1608 if (!compiler_call_helper(c, 2,
1609 s->v.ClassDef.bases,
1610 s->v.ClassDef.keywords,
1611 s->v.ClassDef.starargs,
1612 s->v.ClassDef.kwargs))
1613 return 0;
1614
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001615 /* 6. apply decorators */
1616 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1617 ADDOP_I(c, CALL_FUNCTION, 1);
1618 }
1619
1620 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1622 return 0;
1623 return 1;
1624}
1625
1626static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001627compiler_ifexp(struct compiler *c, expr_ty e)
1628{
1629 basicblock *end, *next;
1630
1631 assert(e->kind == IfExp_kind);
1632 end = compiler_new_block(c);
1633 if (end == NULL)
1634 return 0;
1635 next = compiler_new_block(c);
1636 if (next == NULL)
1637 return 0;
1638 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001639 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001640 VISIT(c, expr, e->v.IfExp.body);
1641 ADDOP_JREL(c, JUMP_FORWARD, end);
1642 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001643 VISIT(c, expr, e->v.IfExp.orelse);
1644 compiler_use_next_block(c, end);
1645 return 1;
1646}
1647
1648static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649compiler_lambda(struct compiler *c, expr_ty e)
1650{
1651 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001652 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001653 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654 arguments_ty args = e->v.Lambda.args;
1655 assert(e->kind == Lambda_kind);
1656
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001657 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001658 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001659 if (!name)
1660 return 0;
1661 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662
Guido van Rossum4f72a782006-10-27 23:31:49 +00001663 if (args->kwonlyargs) {
1664 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1665 args->kw_defaults);
1666 if (res < 0) return 0;
1667 kw_default_count = res;
1668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001669 if (args->defaults)
1670 VISIT_SEQ(c, expr, args->defaults);
1671 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1672 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001673
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001675 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001676 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001677 if (c->u->u_ste->ste_generator) {
1678 ADDOP_IN_SCOPE(c, POP_TOP);
1679 }
1680 else {
1681 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1682 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001684 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001685 if (co == NULL)
1686 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687
Guido van Rossum4f72a782006-10-27 23:31:49 +00001688 arglength = asdl_seq_LEN(args->defaults);
1689 arglength |= kw_default_count << 8;
1690 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001691 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
1693 return 1;
1694}
1695
1696static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697compiler_if(struct compiler *c, stmt_ty s)
1698{
1699 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001700 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701 assert(s->kind == If_kind);
1702 end = compiler_new_block(c);
1703 if (end == NULL)
1704 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001705
1706 constant = expr_constant(s->v.If.test);
1707 /* constant = 0: "if 0"
1708 * constant = 1: "if 1", "if 2", ...
1709 * constant = -1: rest */
1710 if (constant == 0) {
1711 if (s->v.If.orelse)
1712 VISIT_SEQ(c, stmt, s->v.If.orelse);
1713 } else if (constant == 1) {
1714 VISIT_SEQ(c, stmt, s->v.If.body);
1715 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001716 if (s->v.If.orelse) {
1717 next = compiler_new_block(c);
1718 if (next == NULL)
1719 return 0;
1720 }
1721 else
1722 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001723 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001724 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001725 VISIT_SEQ(c, stmt, s->v.If.body);
1726 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001727 if (s->v.If.orelse) {
1728 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001729 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001730 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001731 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732 compiler_use_next_block(c, end);
1733 return 1;
1734}
1735
1736static int
1737compiler_for(struct compiler *c, stmt_ty s)
1738{
1739 basicblock *start, *cleanup, *end;
1740
1741 start = compiler_new_block(c);
1742 cleanup = compiler_new_block(c);
1743 end = compiler_new_block(c);
1744 if (start == NULL || end == NULL || cleanup == NULL)
1745 return 0;
1746 ADDOP_JREL(c, SETUP_LOOP, end);
1747 if (!compiler_push_fblock(c, LOOP, start))
1748 return 0;
1749 VISIT(c, expr, s->v.For.iter);
1750 ADDOP(c, GET_ITER);
1751 compiler_use_next_block(c, start);
1752 ADDOP_JREL(c, FOR_ITER, cleanup);
1753 VISIT(c, expr, s->v.For.target);
1754 VISIT_SEQ(c, stmt, s->v.For.body);
1755 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1756 compiler_use_next_block(c, cleanup);
1757 ADDOP(c, POP_BLOCK);
1758 compiler_pop_fblock(c, LOOP, start);
1759 VISIT_SEQ(c, stmt, s->v.For.orelse);
1760 compiler_use_next_block(c, end);
1761 return 1;
1762}
1763
1764static int
1765compiler_while(struct compiler *c, stmt_ty s)
1766{
1767 basicblock *loop, *orelse, *end, *anchor = NULL;
1768 int constant = expr_constant(s->v.While.test);
1769
Christian Heimes969fe572008-01-25 11:23:10 +00001770 if (constant == 0) {
1771 if (s->v.While.orelse)
1772 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001774 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001775 loop = compiler_new_block(c);
1776 end = compiler_new_block(c);
1777 if (constant == -1) {
1778 anchor = compiler_new_block(c);
1779 if (anchor == NULL)
1780 return 0;
1781 }
1782 if (loop == NULL || end == NULL)
1783 return 0;
1784 if (s->v.While.orelse) {
1785 orelse = compiler_new_block(c);
1786 if (orelse == NULL)
1787 return 0;
1788 }
1789 else
1790 orelse = NULL;
1791
1792 ADDOP_JREL(c, SETUP_LOOP, end);
1793 compiler_use_next_block(c, loop);
1794 if (!compiler_push_fblock(c, LOOP, loop))
1795 return 0;
1796 if (constant == -1) {
1797 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001798 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799 }
1800 VISIT_SEQ(c, stmt, s->v.While.body);
1801 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1802
1803 /* XXX should the two POP instructions be in a separate block
1804 if there is no else clause ?
1805 */
1806
1807 if (constant == -1) {
1808 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 ADDOP(c, POP_BLOCK);
1810 }
1811 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001812 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813 VISIT_SEQ(c, stmt, s->v.While.orelse);
1814 compiler_use_next_block(c, end);
1815
1816 return 1;
1817}
1818
1819static int
1820compiler_continue(struct compiler *c)
1821{
1822 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001823 static const char IN_FINALLY_ERROR_MSG[] =
1824 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825 int i;
1826
1827 if (!c->u->u_nfblocks)
1828 return compiler_error(c, LOOP_ERROR_MSG);
1829 i = c->u->u_nfblocks - 1;
1830 switch (c->u->u_fblock[i].fb_type) {
1831 case LOOP:
1832 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1833 break;
1834 case EXCEPT:
1835 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001836 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1837 /* Prevent continue anywhere under a finally
1838 even if hidden in a sub-try or except. */
1839 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1840 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1841 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 if (i == -1)
1843 return compiler_error(c, LOOP_ERROR_MSG);
1844 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1845 break;
1846 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001847 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848 }
1849
1850 return 1;
1851}
1852
1853/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1854
1855 SETUP_FINALLY L
1856 <code for body>
1857 POP_BLOCK
1858 LOAD_CONST <None>
1859 L: <code for finalbody>
1860 END_FINALLY
1861
1862 The special instructions use the block stack. Each block
1863 stack entry contains the instruction that created it (here
1864 SETUP_FINALLY), the level of the value stack at the time the
1865 block stack entry was created, and a label (here L).
1866
1867 SETUP_FINALLY:
1868 Pushes the current value stack level and the label
1869 onto the block stack.
1870 POP_BLOCK:
1871 Pops en entry from the block stack, and pops the value
1872 stack until its level is the same as indicated on the
1873 block stack. (The label is ignored.)
1874 END_FINALLY:
1875 Pops a variable number of entries from the *value* stack
1876 and re-raises the exception they specify. The number of
1877 entries popped depends on the (pseudo) exception type.
1878
1879 The block stack is unwound when an exception is raised:
1880 when a SETUP_FINALLY entry is found, the exception is pushed
1881 onto the value stack (and the exception condition is cleared),
1882 and the interpreter jumps to the label gotten from the block
1883 stack.
1884*/
1885
1886static int
1887compiler_try_finally(struct compiler *c, stmt_ty s)
1888{
1889 basicblock *body, *end;
1890 body = compiler_new_block(c);
1891 end = compiler_new_block(c);
1892 if (body == NULL || end == NULL)
1893 return 0;
1894
1895 ADDOP_JREL(c, SETUP_FINALLY, end);
1896 compiler_use_next_block(c, body);
1897 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1898 return 0;
1899 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1900 ADDOP(c, POP_BLOCK);
1901 compiler_pop_fblock(c, FINALLY_TRY, body);
1902
1903 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1904 compiler_use_next_block(c, end);
1905 if (!compiler_push_fblock(c, FINALLY_END, end))
1906 return 0;
1907 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1908 ADDOP(c, END_FINALLY);
1909 compiler_pop_fblock(c, FINALLY_END, end);
1910
1911 return 1;
1912}
1913
1914/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001915 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 (The contents of the value stack is shown in [], with the top
1917 at the right; 'tb' is trace-back info, 'val' the exception's
1918 associated value, and 'exc' the exception.)
1919
1920 Value stack Label Instruction Argument
1921 [] SETUP_EXCEPT L1
1922 [] <code for S>
1923 [] POP_BLOCK
1924 [] JUMP_FORWARD L0
1925
1926 [tb, val, exc] L1: DUP )
1927 [tb, val, exc, exc] <evaluate E1> )
1928 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001929 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930 [tb, val, exc] POP
1931 [tb, val] <assign to V1> (or POP if no V1)
1932 [tb] POP
1933 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001934 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001936 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937 .............................etc.......................
1938
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001939 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940
1941 [] L0: <next statement>
1942
1943 Of course, parts are not generated if Vi or Ei is not present.
1944*/
1945static int
1946compiler_try_except(struct compiler *c, stmt_ty s)
1947{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001948 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949 int i, n;
1950
1951 body = compiler_new_block(c);
1952 except = compiler_new_block(c);
1953 orelse = compiler_new_block(c);
1954 end = compiler_new_block(c);
1955 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1956 return 0;
1957 ADDOP_JREL(c, SETUP_EXCEPT, except);
1958 compiler_use_next_block(c, body);
1959 if (!compiler_push_fblock(c, EXCEPT, body))
1960 return 0;
1961 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1962 ADDOP(c, POP_BLOCK);
1963 compiler_pop_fblock(c, EXCEPT, body);
1964 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1965 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1966 compiler_use_next_block(c, except);
1967 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001968 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001970 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001972 c->u->u_lineno_set = 0;
1973 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974 except = compiler_new_block(c);
1975 if (except == NULL)
1976 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001977 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001979 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001981 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 }
1983 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001984 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001985 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001986
1987 cleanup_end = compiler_new_block(c);
1988 cleanup_body = compiler_new_block(c);
1989 if(!(cleanup_end || cleanup_body))
1990 return 0;
1991
Neal Norwitzad74aa82008-03-31 05:14:30 +00001992 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001993 ADDOP(c, POP_TOP);
1994
1995 /*
1996 try:
1997 # body
1998 except type as name:
1999 try:
2000 # body
2001 finally:
2002 name = None
2003 del name
2004 */
2005
2006 /* second try: */
2007 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2008 compiler_use_next_block(c, cleanup_body);
2009 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2010 return 0;
2011
2012 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002013 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002014 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002015 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002016 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2017
2018 /* finally: */
2019 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2020 compiler_use_next_block(c, cleanup_end);
2021 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2022 return 0;
2023
2024 /* name = None */
2025 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002026 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002027
Guido van Rossum16be03e2007-01-10 18:51:35 +00002028 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002029 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002030
2031 ADDOP(c, END_FINALLY);
2032 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 }
2034 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002035 basicblock *cleanup_body;
2036
2037 cleanup_body = compiler_new_block(c);
2038 if(!cleanup_body)
2039 return 0;
2040
2041 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002042 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002043 compiler_use_next_block(c, cleanup_body);
2044 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2045 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002046 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002047 ADDOP(c, POP_EXCEPT);
2048 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002049 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 ADDOP_JREL(c, JUMP_FORWARD, end);
2051 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 }
2053 ADDOP(c, END_FINALLY);
2054 compiler_use_next_block(c, orelse);
2055 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2056 compiler_use_next_block(c, end);
2057 return 1;
2058}
2059
2060static int
2061compiler_import_as(struct compiler *c, identifier name, identifier asname)
2062{
2063 /* The IMPORT_NAME opcode was already generated. This function
2064 merely needs to bind the result to a name.
2065
2066 If there is a dot in name, we need to split it and emit a
2067 LOAD_ATTR for each name.
2068 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002069 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2070 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 if (dot) {
2072 /* Consume the base module name to get the first attribute */
2073 src = dot + 1;
2074 while (dot) {
2075 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002076 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002077 dot = Py_UNICODE_strchr(src, '.');
2078 attr = PyUnicode_FromUnicode(src,
2079 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002080 if (!attr)
2081 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002083 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 src = dot + 1;
2085 }
2086 }
2087 return compiler_nameop(c, asname, Store);
2088}
2089
2090static int
2091compiler_import(struct compiler *c, stmt_ty s)
2092{
2093 /* The Import node stores a module name like a.b.c as a single
2094 string. This is convenient for all cases except
2095 import a.b.c as d
2096 where we need to parse that string to extract the individual
2097 module names.
2098 XXX Perhaps change the representation to make this case simpler?
2099 */
2100 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002103 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002105 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106
Christian Heimes217cfd12007-12-02 14:31:20 +00002107 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002108 if (level == NULL)
2109 return 0;
2110
2111 ADDOP_O(c, LOAD_CONST, level, consts);
2112 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2114 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2115
2116 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002117 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002118 if (!r)
2119 return r;
2120 }
2121 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002123 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2124 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002126 tmp = PyUnicode_FromUnicode(base,
2127 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 r = compiler_nameop(c, tmp, Store);
2129 if (dot) {
2130 Py_DECREF(tmp);
2131 }
2132 if (!r)
2133 return r;
2134 }
2135 }
2136 return 1;
2137}
2138
2139static int
2140compiler_from_import(struct compiler *c, stmt_ty s)
2141{
2142 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143
2144 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002145 PyObject *level;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002146 static PyObject *empty_string;
2147
2148 if (!empty_string) {
2149 empty_string = PyUnicode_FromString("");
2150 if (!empty_string)
2151 return 0;
2152 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002153
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 if (!names)
2155 return 0;
2156
Christian Heimes217cfd12007-12-02 14:31:20 +00002157 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002158 if (!level) {
2159 Py_DECREF(names);
2160 return 0;
2161 }
2162
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 /* build up the names */
2164 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002165 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166 Py_INCREF(alias->name);
2167 PyTuple_SET_ITEM(names, i, alias->name);
2168 }
2169
Benjamin Peterson78565b22009-06-28 19:19:51 +00002170 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2171 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2172 Py_DECREF(level);
2173 Py_DECREF(names);
2174 return compiler_error(c, "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002175 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 }
2177
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002178 ADDOP_O(c, LOAD_CONST, level, consts);
2179 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002181 Py_DECREF(names);
Benjamin Peterson78565b22009-06-28 19:19:51 +00002182 if (s->v.ImportFrom.module) {
2183 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2184 }
2185 else {
2186 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2187 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002189 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 identifier store_name;
2191
Martin v. Löwis5b222132007-06-10 09:51:05 +00002192 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 assert(n == 1);
2194 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 }
2197
2198 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2199 store_name = alias->name;
2200 if (alias->asname)
2201 store_name = alias->asname;
2202
2203 if (!compiler_nameop(c, store_name, Store)) {
2204 Py_DECREF(names);
2205 return 0;
2206 }
2207 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002208 /* remove imported module */
2209 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210 return 1;
2211}
2212
2213static int
2214compiler_assert(struct compiler *c, stmt_ty s)
2215{
2216 static PyObject *assertion_error = NULL;
2217 basicblock *end;
2218
2219 if (Py_OptimizeFlag)
2220 return 1;
2221 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002222 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 if (assertion_error == NULL)
2224 return 0;
2225 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002226 if (s->v.Assert.test->kind == Tuple_kind &&
2227 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2228 const char* msg =
2229 "assertion is always true, perhaps remove parentheses?";
2230 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2231 c->u->u_lineno, NULL, NULL) == -1)
2232 return 0;
2233 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 VISIT(c, expr, s->v.Assert.test);
2235 end = compiler_new_block(c);
2236 if (end == NULL)
2237 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002238 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2240 if (s->v.Assert.msg) {
2241 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002242 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243 }
Collin Winter828f04a2007-08-31 00:04:24 +00002244 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002245 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246 return 1;
2247}
2248
2249static int
2250compiler_visit_stmt(struct compiler *c, stmt_ty s)
2251{
2252 int i, n;
2253
Thomas Wouters89f507f2006-12-13 04:49:30 +00002254 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002256 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002257
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002259 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002261 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002263 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264 if (c->u->u_ste->ste_type != FunctionBlock)
2265 return compiler_error(c, "'return' outside function");
2266 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 VISIT(c, expr, s->v.Return.value);
2268 }
2269 else
2270 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2271 ADDOP(c, RETURN_VALUE);
2272 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002273 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 VISIT_SEQ(c, expr, s->v.Delete.targets)
2275 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002276 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277 n = asdl_seq_LEN(s->v.Assign.targets);
2278 VISIT(c, expr, s->v.Assign.value);
2279 for (i = 0; i < n; i++) {
2280 if (i < n - 1)
2281 ADDOP(c, DUP_TOP);
2282 VISIT(c, expr,
2283 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2284 }
2285 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002286 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002288 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002290 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002292 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002294 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002295 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002296 if (s->v.Raise.exc) {
2297 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002299 if (s->v.Raise.cause) {
2300 VISIT(c, expr, s->v.Raise.cause);
2301 n++;
2302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303 }
2304 ADDOP_I(c, RAISE_VARARGS, n);
2305 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002306 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002308 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002310 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002312 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002314 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002316 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002317 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002321 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322 ADDOP(c, PRINT_EXPR);
2323 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002324 else if (s->v.Expr.value->kind != Str_kind &&
2325 s->v.Expr.value->kind != Num_kind) {
2326 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327 ADDOP(c, POP_TOP);
2328 }
2329 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002330 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002332 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002333 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 return compiler_error(c, "'break' outside loop");
2335 ADDOP(c, BREAK_LOOP);
2336 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002337 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002339 case With_kind:
2340 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 }
2342 return 1;
2343}
2344
2345static int
2346unaryop(unaryop_ty op)
2347{
2348 switch (op) {
2349 case Invert:
2350 return UNARY_INVERT;
2351 case Not:
2352 return UNARY_NOT;
2353 case UAdd:
2354 return UNARY_POSITIVE;
2355 case USub:
2356 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002357 default:
2358 PyErr_Format(PyExc_SystemError,
2359 "unary op %d should not be possible", op);
2360 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362}
2363
2364static int
2365binop(struct compiler *c, operator_ty op)
2366{
2367 switch (op) {
2368 case Add:
2369 return BINARY_ADD;
2370 case Sub:
2371 return BINARY_SUBTRACT;
2372 case Mult:
2373 return BINARY_MULTIPLY;
2374 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002375 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376 case Mod:
2377 return BINARY_MODULO;
2378 case Pow:
2379 return BINARY_POWER;
2380 case LShift:
2381 return BINARY_LSHIFT;
2382 case RShift:
2383 return BINARY_RSHIFT;
2384 case BitOr:
2385 return BINARY_OR;
2386 case BitXor:
2387 return BINARY_XOR;
2388 case BitAnd:
2389 return BINARY_AND;
2390 case FloorDiv:
2391 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002392 default:
2393 PyErr_Format(PyExc_SystemError,
2394 "binary op %d should not be possible", op);
2395 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397}
2398
2399static int
2400cmpop(cmpop_ty op)
2401{
2402 switch (op) {
2403 case Eq:
2404 return PyCmp_EQ;
2405 case NotEq:
2406 return PyCmp_NE;
2407 case Lt:
2408 return PyCmp_LT;
2409 case LtE:
2410 return PyCmp_LE;
2411 case Gt:
2412 return PyCmp_GT;
2413 case GtE:
2414 return PyCmp_GE;
2415 case Is:
2416 return PyCmp_IS;
2417 case IsNot:
2418 return PyCmp_IS_NOT;
2419 case In:
2420 return PyCmp_IN;
2421 case NotIn:
2422 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002423 default:
2424 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002426}
2427
2428static int
2429inplace_binop(struct compiler *c, operator_ty op)
2430{
2431 switch (op) {
2432 case Add:
2433 return INPLACE_ADD;
2434 case Sub:
2435 return INPLACE_SUBTRACT;
2436 case Mult:
2437 return INPLACE_MULTIPLY;
2438 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002439 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440 case Mod:
2441 return INPLACE_MODULO;
2442 case Pow:
2443 return INPLACE_POWER;
2444 case LShift:
2445 return INPLACE_LSHIFT;
2446 case RShift:
2447 return INPLACE_RSHIFT;
2448 case BitOr:
2449 return INPLACE_OR;
2450 case BitXor:
2451 return INPLACE_XOR;
2452 case BitAnd:
2453 return INPLACE_AND;
2454 case FloorDiv:
2455 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002456 default:
2457 PyErr_Format(PyExc_SystemError,
2458 "inplace binary op %d should not be possible", op);
2459 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461}
2462
2463static int
2464compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2465{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002466 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2468
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002469 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002470 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 /* XXX AugStore isn't used anywhere! */
2472
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002473 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002474 if (!mangled)
2475 return 0;
2476
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 op = 0;
2478 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002479 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480 switch (scope) {
2481 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002482 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 optype = OP_DEREF;
2484 break;
2485 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002486 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487 optype = OP_DEREF;
2488 break;
2489 case LOCAL:
2490 if (c->u->u_ste->ste_type == FunctionBlock)
2491 optype = OP_FAST;
2492 break;
2493 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002494 if (c->u->u_ste->ste_type == FunctionBlock &&
2495 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496 optype = OP_GLOBAL;
2497 break;
2498 case GLOBAL_EXPLICIT:
2499 optype = OP_GLOBAL;
2500 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002501 default:
2502 /* scope can be 0 */
2503 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504 }
2505
2506 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002507 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508
2509 switch (optype) {
2510 case OP_DEREF:
2511 switch (ctx) {
2512 case Load: op = LOAD_DEREF; break;
2513 case Store: op = STORE_DEREF; break;
2514 case AugLoad:
2515 case AugStore:
2516 break;
2517 case Del:
2518 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002519 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002521 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002522 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002525 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002526 PyErr_SetString(PyExc_SystemError,
2527 "param invalid for deref variable");
2528 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 }
2530 break;
2531 case OP_FAST:
2532 switch (ctx) {
2533 case Load: op = LOAD_FAST; break;
2534 case Store: op = STORE_FAST; break;
2535 case Del: op = DELETE_FAST; break;
2536 case AugLoad:
2537 case AugStore:
2538 break;
2539 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002540 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002541 PyErr_SetString(PyExc_SystemError,
2542 "param invalid for local variable");
2543 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002545 ADDOP_O(c, op, mangled, varnames);
2546 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547 return 1;
2548 case OP_GLOBAL:
2549 switch (ctx) {
2550 case Load: op = LOAD_GLOBAL; break;
2551 case Store: op = STORE_GLOBAL; break;
2552 case Del: op = DELETE_GLOBAL; break;
2553 case AugLoad:
2554 case AugStore:
2555 break;
2556 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002557 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002558 PyErr_SetString(PyExc_SystemError,
2559 "param invalid for global variable");
2560 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561 }
2562 break;
2563 case OP_NAME:
2564 switch (ctx) {
2565 case Load: op = LOAD_NAME; break;
2566 case Store: op = STORE_NAME; break;
2567 case Del: op = DELETE_NAME; break;
2568 case AugLoad:
2569 case AugStore:
2570 break;
2571 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002572 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002573 PyErr_SetString(PyExc_SystemError,
2574 "param invalid for name variable");
2575 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576 }
2577 break;
2578 }
2579
2580 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002581 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002582 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002583 if (arg < 0)
2584 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002585 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586}
2587
2588static int
2589compiler_boolop(struct compiler *c, expr_ty e)
2590{
2591 basicblock *end;
2592 int jumpi, i, n;
2593 asdl_seq *s;
2594
2595 assert(e->kind == BoolOp_kind);
2596 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002597 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002599 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002601 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602 return 0;
2603 s = e->v.BoolOp.values;
2604 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002605 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002607 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002608 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002610 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 compiler_use_next_block(c, end);
2612 return 1;
2613}
2614
2615static int
2616compiler_list(struct compiler *c, expr_ty e)
2617{
2618 int n = asdl_seq_LEN(e->v.List.elts);
2619 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002620 int i, seen_star = 0;
2621 for (i = 0; i < n; i++) {
2622 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2623 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002624 if ((i >= (1 << 8)) ||
2625 (n-i-1 >= (INT_MAX >> 8)))
2626 return compiler_error(c,
2627 "too many expressions in "
2628 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002629 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2630 seen_star = 1;
2631 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2632 } else if (elt->kind == Starred_kind) {
2633 return compiler_error(c,
2634 "two starred expressions in assignment");
2635 }
2636 }
2637 if (!seen_star) {
2638 ADDOP_I(c, UNPACK_SEQUENCE, n);
2639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640 }
2641 VISIT_SEQ(c, expr, e->v.List.elts);
2642 if (e->v.List.ctx == Load) {
2643 ADDOP_I(c, BUILD_LIST, n);
2644 }
2645 return 1;
2646}
2647
2648static int
2649compiler_tuple(struct compiler *c, expr_ty e)
2650{
2651 int n = asdl_seq_LEN(e->v.Tuple.elts);
2652 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002653 int i, seen_star = 0;
2654 for (i = 0; i < n; i++) {
2655 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2656 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002657 if ((i >= (1 << 8)) ||
2658 (n-i-1 >= (INT_MAX >> 8)))
2659 return compiler_error(c,
2660 "too many expressions in "
2661 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002662 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2663 seen_star = 1;
2664 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2665 } else if (elt->kind == Starred_kind) {
2666 return compiler_error(c,
2667 "two starred expressions in assignment");
2668 }
2669 }
2670 if (!seen_star) {
2671 ADDOP_I(c, UNPACK_SEQUENCE, n);
2672 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 }
2674 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2675 if (e->v.Tuple.ctx == Load) {
2676 ADDOP_I(c, BUILD_TUPLE, n);
2677 }
2678 return 1;
2679}
2680
2681static int
2682compiler_compare(struct compiler *c, expr_ty e)
2683{
2684 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002685 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686
2687 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2688 VISIT(c, expr, e->v.Compare.left);
2689 n = asdl_seq_LEN(e->v.Compare.ops);
2690 assert(n > 0);
2691 if (n > 1) {
2692 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 if (cleanup == NULL)
2694 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002695 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002696 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 }
2698 for (i = 1; i < n; i++) {
2699 ADDOP(c, DUP_TOP);
2700 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002702 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002703 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002704 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002707 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002708 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002710 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002712 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713 if (n > 1) {
2714 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002715 if (end == NULL)
2716 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 ADDOP_JREL(c, JUMP_FORWARD, end);
2718 compiler_use_next_block(c, cleanup);
2719 ADDOP(c, ROT_TWO);
2720 ADDOP(c, POP_TOP);
2721 compiler_use_next_block(c, end);
2722 }
2723 return 1;
2724}
2725
2726static int
2727compiler_call(struct compiler *c, expr_ty e)
2728{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002730 return compiler_call_helper(c, 0,
2731 e->v.Call.args,
2732 e->v.Call.keywords,
2733 e->v.Call.starargs,
2734 e->v.Call.kwargs);
2735}
2736
2737/* shared code between compiler_call and compiler_class */
2738static int
2739compiler_call_helper(struct compiler *c,
2740 int n, /* Args already pushed */
2741 asdl_seq *args,
2742 asdl_seq *keywords,
2743 expr_ty starargs,
2744 expr_ty kwargs)
2745{
2746 int code = 0;
2747
2748 n += asdl_seq_LEN(args);
2749 VISIT_SEQ(c, expr, args);
2750 if (keywords) {
2751 VISIT_SEQ(c, keyword, keywords);
2752 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002754 if (starargs) {
2755 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756 code |= 1;
2757 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002758 if (kwargs) {
2759 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760 code |= 2;
2761 }
2762 switch (code) {
2763 case 0:
2764 ADDOP_I(c, CALL_FUNCTION, n);
2765 break;
2766 case 1:
2767 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2768 break;
2769 case 2:
2770 ADDOP_I(c, CALL_FUNCTION_KW, n);
2771 break;
2772 case 3:
2773 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2774 break;
2775 }
2776 return 1;
2777}
2778
Nick Coghlan650f0d02007-04-15 12:05:43 +00002779
2780/* List and set comprehensions and generator expressions work by creating a
2781 nested function to perform the actual iteration. This means that the
2782 iteration variables don't leak into the current scope.
2783 The defined function is called immediately following its definition, with the
2784 result of that call being the result of the expression.
2785 The LC/SC version returns the populated container, while the GE version is
2786 flagged in symtable.c as a generator, so it returns the generator object
2787 when the function is called.
2788 This code *knows* that the loop cannot contain break, continue, or return,
2789 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2790
2791 Possible cleanups:
2792 - iterate over the generator sequence instead of using recursion
2793*/
2794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002796compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002797 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002798 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799{
2800 /* generate code for the iterator, then each of the ifs,
2801 and then write to the element */
2802
Nick Coghlan650f0d02007-04-15 12:05:43 +00002803 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002805 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002806
2807 start = compiler_new_block(c);
2808 skip = compiler_new_block(c);
2809 if_cleanup = compiler_new_block(c);
2810 anchor = compiler_new_block(c);
2811
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002812 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002813 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815
Nick Coghlan650f0d02007-04-15 12:05:43 +00002816 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818 if (gen_index == 0) {
2819 /* Receive outermost iter as an implicit argument */
2820 c->u->u_argcount = 1;
2821 ADDOP_I(c, LOAD_FAST, 0);
2822 }
2823 else {
2824 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002825 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002826 ADDOP(c, GET_ITER);
2827 }
2828 compiler_use_next_block(c, start);
2829 ADDOP_JREL(c, FOR_ITER, anchor);
2830 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002831 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002833 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002834 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002836 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002838 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002840 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002843 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002844 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002845 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002846 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847
Nick Coghlan650f0d02007-04-15 12:05:43 +00002848 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002849 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002850 /* comprehension specific code */
2851 switch (type) {
2852 case COMP_GENEXP:
2853 VISIT(c, expr, elt);
2854 ADDOP(c, YIELD_VALUE);
2855 ADDOP(c, POP_TOP);
2856 break;
2857 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002858 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002859 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002860 break;
2861 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002862 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002863 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002864 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002865 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002866 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002867 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002868 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002869 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002870 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002871 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002872 default:
2873 return 0;
2874 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875
2876 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002877 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002878 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2880 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881
2882 return 1;
2883}
2884
2885static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002886compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002887 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002888{
2889 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002890 expr_ty outermost_iter;
2891
2892 outermost_iter = ((comprehension_ty)
2893 asdl_seq_GET(generators, 0))->iter;
2894
2895 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2896 goto error;
2897
2898 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002899 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002900 switch (type) {
2901 case COMP_LISTCOMP:
2902 op = BUILD_LIST;
2903 break;
2904 case COMP_SETCOMP:
2905 op = BUILD_SET;
2906 break;
2907 case COMP_DICTCOMP:
2908 op = BUILD_MAP;
2909 break;
2910 default:
2911 PyErr_Format(PyExc_SystemError,
2912 "unknown comprehension type %d", type);
2913 goto error_in_scope;
2914 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002915
Guido van Rossum992d4a32007-07-11 13:09:30 +00002916 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002917 }
2918
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002919 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002920 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002921 goto error_in_scope;
2922
2923 if (type != COMP_GENEXP) {
2924 ADDOP(c, RETURN_VALUE);
2925 }
2926
2927 co = assemble(c, 1);
2928 compiler_exit_scope(c);
2929 if (co == NULL)
2930 goto error;
2931
2932 if (!compiler_make_closure(c, co, 0))
2933 goto error;
2934 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002935
2936 VISIT(c, expr, outermost_iter);
2937 ADDOP(c, GET_ITER);
2938 ADDOP_I(c, CALL_FUNCTION, 1);
2939 return 1;
2940error_in_scope:
2941 compiler_exit_scope(c);
2942error:
2943 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002944 return 0;
2945}
2946
2947static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948compiler_genexp(struct compiler *c, expr_ty e)
2949{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002950 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002951 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002952 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002953 if (!name)
2954 return 0;
2955 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002956 assert(e->kind == GeneratorExp_kind);
2957 return compiler_comprehension(c, e, COMP_GENEXP, name,
2958 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002959 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960}
2961
2962static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002963compiler_listcomp(struct compiler *c, expr_ty e)
2964{
2965 static identifier name;
2966 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002967 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002968 if (!name)
2969 return 0;
2970 }
2971 assert(e->kind == ListComp_kind);
2972 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2973 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002974 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002975}
2976
2977static int
2978compiler_setcomp(struct compiler *c, expr_ty e)
2979{
2980 static identifier name;
2981 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002982 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002983 if (!name)
2984 return 0;
2985 }
2986 assert(e->kind == SetComp_kind);
2987 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2988 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002989 e->v.SetComp.elt, NULL);
2990}
2991
2992
2993static int
2994compiler_dictcomp(struct compiler *c, expr_ty e)
2995{
2996 static identifier name;
2997 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00002998 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00002999 if (!name)
3000 return 0;
3001 }
3002 assert(e->kind == DictComp_kind);
3003 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3004 e->v.DictComp.generators,
3005 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003006}
3007
3008
3009static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010compiler_visit_keyword(struct compiler *c, keyword_ty k)
3011{
3012 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3013 VISIT(c, expr, k->value);
3014 return 1;
3015}
3016
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003017/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018 whether they are true or false.
3019
3020 Return values: 1 for true, 0 for false, -1 for non-constant.
3021 */
3022
3023static int
3024expr_constant(expr_ty e)
3025{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003026 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003028 case Ellipsis_kind:
3029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 case Num_kind:
3031 return PyObject_IsTrue(e->v.Num.n);
3032 case Str_kind:
3033 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003034 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003035 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003036 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003037 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003038 if (strcmp(id, "True") == 0) return 1;
3039 if (strcmp(id, "False") == 0) return 0;
3040 if (strcmp(id, "None") == 0) return 0;
3041 if (strcmp(id, "__debug__") == 0)
3042 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003043 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 default:
3045 return -1;
3046 }
3047}
3048
Guido van Rossumc2e20742006-02-27 22:32:47 +00003049/*
3050 Implements the with statement from PEP 343.
3051
3052 The semantics outlined in that PEP are as follows:
3053
3054 with EXPR as VAR:
3055 BLOCK
3056
3057 It is implemented roughly as:
3058
Thomas Wouters477c8d52006-05-27 19:21:47 +00003059 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003060 exit = context.__exit__ # not calling it
3061 value = context.__enter__()
3062 try:
3063 VAR = value # if VAR present in the syntax
3064 BLOCK
3065 finally:
3066 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003067 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003068 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003069 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003070 exit(*exc)
3071 */
3072static int
3073compiler_with(struct compiler *c, stmt_ty s)
3074{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003076
3077 assert(s->kind == With_kind);
3078
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079 block = compiler_new_block(c);
3080 finally = compiler_new_block(c);
3081 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003082 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003083
Thomas Wouters477c8d52006-05-27 19:21:47 +00003084 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003085 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003086 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003087
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003088 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003089 compiler_use_next_block(c, block);
3090 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003091 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003092 }
3093
3094 if (s->v.With.optional_vars) {
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003095 VISIT(c, expr, s->v.With.optional_vars);
3096 }
3097 else {
3098 /* Discard result from context.__enter__() */
3099 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003100 }
3101
3102 /* BLOCK code */
3103 VISIT_SEQ(c, stmt, s->v.With.body);
3104
3105 /* End of try block; start the finally block */
3106 ADDOP(c, POP_BLOCK);
3107 compiler_pop_fblock(c, FINALLY_TRY, block);
3108
3109 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3110 compiler_use_next_block(c, finally);
3111 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003112 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003113
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003114 /* Finally block starts; context.__exit__ is on the stack under
3115 the exception or return information. Just issue our magic
3116 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003117 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003118
3119 /* Finally block ends. */
3120 ADDOP(c, END_FINALLY);
3121 compiler_pop_fblock(c, FINALLY_END, finally);
3122 return 1;
3123}
3124
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125static int
3126compiler_visit_expr(struct compiler *c, expr_ty e)
3127{
3128 int i, n;
3129
Thomas Wouters89f507f2006-12-13 04:49:30 +00003130 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003131 set a new line number for the next instruction.
3132 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003133 if (e->lineno > c->u->u_lineno) {
3134 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003135 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136 }
3137 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003140 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141 VISIT(c, expr, e->v.BinOp.left);
3142 VISIT(c, expr, e->v.BinOp.right);
3143 ADDOP(c, binop(c, e->v.BinOp.op));
3144 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003145 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146 VISIT(c, expr, e->v.UnaryOp.operand);
3147 ADDOP(c, unaryop(e->v.UnaryOp.op));
3148 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003149 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003151 case IfExp_kind:
3152 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003153 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003155 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003157 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003158 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003159 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003160 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003161 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162 }
3163 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003164 case Set_kind:
3165 n = asdl_seq_LEN(e->v.Set.elts);
3166 VISIT_SEQ(c, expr, e->v.Set.elts);
3167 ADDOP_I(c, BUILD_SET, n);
3168 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003171 case ListComp_kind:
3172 return compiler_listcomp(c, e);
3173 case SetComp_kind:
3174 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003175 case DictComp_kind:
3176 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177 case Yield_kind:
3178 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 if (e->v.Yield.value) {
3181 VISIT(c, expr, e->v.Yield.value);
3182 }
3183 else {
3184 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3185 }
3186 ADDOP(c, YIELD_VALUE);
3187 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003188 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003190 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3194 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3197 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003198 case Bytes_kind:
3199 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003200 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003201 case Ellipsis_kind:
3202 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3203 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 if (e->v.Attribute.ctx != AugStore)
3207 VISIT(c, expr, e->v.Attribute.value);
3208 switch (e->v.Attribute.ctx) {
3209 case AugLoad:
3210 ADDOP(c, DUP_TOP);
3211 /* Fall through to load */
3212 case Load:
3213 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3214 break;
3215 case AugStore:
3216 ADDOP(c, ROT_TWO);
3217 /* Fall through to save */
3218 case Store:
3219 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3220 break;
3221 case Del:
3222 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3223 break;
3224 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003225 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003226 PyErr_SetString(PyExc_SystemError,
3227 "param invalid in attribute expression");
3228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229 }
3230 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003231 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 switch (e->v.Subscript.ctx) {
3233 case AugLoad:
3234 VISIT(c, expr, e->v.Subscript.value);
3235 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3236 break;
3237 case Load:
3238 VISIT(c, expr, e->v.Subscript.value);
3239 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3240 break;
3241 case AugStore:
3242 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3243 break;
3244 case Store:
3245 VISIT(c, expr, e->v.Subscript.value);
3246 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3247 break;
3248 case Del:
3249 VISIT(c, expr, e->v.Subscript.value);
3250 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3251 break;
3252 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003253 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003254 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003255 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003256 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257 }
3258 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003259 case Starred_kind:
3260 switch (e->v.Starred.ctx) {
3261 case Store:
3262 /* In all legitimate cases, the Starred node was already replaced
3263 * by compiler_list/compiler_tuple. XXX: is that okay? */
3264 return compiler_error(c,
3265 "starred assignment target must be in a list or tuple");
3266 default:
3267 return compiler_error(c,
3268 "can use starred expression only as assignment target");
3269 }
3270 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003271 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3273 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003274 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003276 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 return compiler_tuple(c, e);
3278 }
3279 return 1;
3280}
3281
3282static int
3283compiler_augassign(struct compiler *c, stmt_ty s)
3284{
3285 expr_ty e = s->v.AugAssign.target;
3286 expr_ty auge;
3287
3288 assert(s->kind == AugAssign_kind);
3289
3290 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003291 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
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));
3299 auge->v.Attribute.ctx = AugStore;
3300 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 break;
3302 case Subscript_kind:
3303 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003304 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003305 if (auge == NULL)
3306 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307 VISIT(c, expr, auge);
3308 VISIT(c, expr, s->v.AugAssign.value);
3309 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003310 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003312 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003314 if (!compiler_nameop(c, e->v.Name.id, Load))
3315 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 VISIT(c, expr, s->v.AugAssign.value);
3317 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3318 return compiler_nameop(c, e->v.Name.id, Store);
3319 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003320 PyErr_Format(PyExc_SystemError,
3321 "invalid node type (%d) for augmented assignment",
3322 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003323 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 }
3325 return 1;
3326}
3327
3328static int
3329compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3330{
3331 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003332 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3333 PyErr_SetString(PyExc_SystemError,
3334 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337 f = &c->u->u_fblock[c->u->u_nfblocks++];
3338 f->fb_type = t;
3339 f->fb_block = b;
3340 return 1;
3341}
3342
3343static void
3344compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3345{
3346 struct compiler_unit *u = c->u;
3347 assert(u->u_nfblocks > 0);
3348 u->u_nfblocks--;
3349 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3350 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3351}
3352
Thomas Wouters89f507f2006-12-13 04:49:30 +00003353static int
3354compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003355 int i;
3356 struct compiler_unit *u = c->u;
3357 for (i = 0; i < u->u_nfblocks; ++i) {
3358 if (u->u_fblock[i].fb_type == LOOP)
3359 return 1;
3360 }
3361 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003362}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363/* Raises a SyntaxError and returns 0.
3364 If something goes wrong, a different exception may be raised.
3365*/
3366
3367static int
3368compiler_error(struct compiler *c, const char *errstr)
3369{
3370 PyObject *loc;
3371 PyObject *u = NULL, *v = NULL;
3372
3373 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3374 if (!loc) {
3375 Py_INCREF(Py_None);
3376 loc = Py_None;
3377 }
3378 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3379 Py_None, loc);
3380 if (!u)
3381 goto exit;
3382 v = Py_BuildValue("(zO)", errstr, u);
3383 if (!v)
3384 goto exit;
3385 PyErr_SetObject(PyExc_SyntaxError, v);
3386 exit:
3387 Py_DECREF(loc);
3388 Py_XDECREF(u);
3389 Py_XDECREF(v);
3390 return 0;
3391}
3392
3393static int
3394compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003395 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003397 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003399 /* XXX this code is duplicated */
3400 switch (ctx) {
3401 case AugLoad: /* fall through to Load */
3402 case Load: op = BINARY_SUBSCR; break;
3403 case AugStore:/* fall through to Store */
3404 case Store: op = STORE_SUBSCR; break;
3405 case Del: op = DELETE_SUBSCR; break;
3406 case Param:
3407 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003408 "invalid %s kind %d in subscript\n",
3409 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003410 return 0;
3411 }
3412 if (ctx == AugLoad) {
3413 ADDOP_I(c, DUP_TOPX, 2);
3414 }
3415 else if (ctx == AugStore) {
3416 ADDOP(c, ROT_THREE);
3417 }
3418 ADDOP(c, op);
3419 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420}
3421
3422static int
3423compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3424{
3425 int n = 2;
3426 assert(s->kind == Slice_kind);
3427
3428 /* only handles the cases where BUILD_SLICE is emitted */
3429 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003430 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431 }
3432 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003433 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003435
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003437 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003438 }
3439 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003440 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441 }
3442
3443 if (s->v.Slice.step) {
3444 n++;
3445 VISIT(c, expr, s->v.Slice.step);
3446 }
3447 ADDOP_I(c, BUILD_SLICE, n);
3448 return 1;
3449}
3450
3451static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3453 expr_context_ty ctx)
3454{
3455 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456 case Slice_kind:
3457 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458 case Index_kind:
3459 VISIT(c, expr, s->v.Index.value);
3460 break;
3461 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003462 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003463 PyErr_SetString(PyExc_SystemError,
3464 "extended slice invalid in nested slice");
3465 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466 }
3467 return 1;
3468}
3469
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003470static int
3471compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3472{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003473 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003475 case Index_kind:
3476 kindname = "index";
3477 if (ctx != AugStore) {
3478 VISIT(c, expr, s->v.Index.value);
3479 }
3480 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003482 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003483 if (ctx != AugStore) {
3484 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003485 return 0;
3486 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003487 break;
3488 case ExtSlice_kind:
3489 kindname = "extended slice";
3490 if (ctx != AugStore) {
3491 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3492 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003493 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003494 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003495 if (!compiler_visit_nested_slice(c, sub, ctx))
3496 return 0;
3497 }
3498 ADDOP_I(c, BUILD_TUPLE, n);
3499 }
3500 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003501 default:
3502 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003503 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003504 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003506 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507}
3508
Thomas Wouters89f507f2006-12-13 04:49:30 +00003509/* End of the compiler section, beginning of the assembler section */
3510
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003511/* do depth-first search of basic block graph, starting with block.
3512 post records the block indices in post-order.
3513
3514 XXX must handle implicit jumps from one block to next
3515*/
3516
Thomas Wouters89f507f2006-12-13 04:49:30 +00003517struct assembler {
3518 PyObject *a_bytecode; /* string containing bytecode */
3519 int a_offset; /* offset into bytecode */
3520 int a_nblocks; /* number of reachable blocks */
3521 basicblock **a_postorder; /* list of blocks in dfs postorder */
3522 PyObject *a_lnotab; /* string containing lnotab */
3523 int a_lnotab_off; /* offset into lnotab */
3524 int a_lineno; /* last lineno of emitted instruction */
3525 int a_lineno_off; /* bytecode offset of last lineno */
3526};
3527
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528static void
3529dfs(struct compiler *c, basicblock *b, struct assembler *a)
3530{
3531 int i;
3532 struct instr *instr = NULL;
3533
3534 if (b->b_seen)
3535 return;
3536 b->b_seen = 1;
3537 if (b->b_next != NULL)
3538 dfs(c, b->b_next, a);
3539 for (i = 0; i < b->b_iused; i++) {
3540 instr = &b->b_instr[i];
3541 if (instr->i_jrel || instr->i_jabs)
3542 dfs(c, instr->i_target, a);
3543 }
3544 a->a_postorder[a->a_nblocks++] = b;
3545}
3546
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003547static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3549{
Neil Schemenauere441cb72009-10-14 19:14:38 +00003550 int i, target_depth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 struct instr *instr;
3552 if (b->b_seen || b->b_startdepth >= depth)
3553 return maxdepth;
3554 b->b_seen = 1;
3555 b->b_startdepth = depth;
3556 for (i = 0; i < b->b_iused; i++) {
3557 instr = &b->b_instr[i];
3558 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3559 if (depth > maxdepth)
3560 maxdepth = depth;
3561 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3562 if (instr->i_jrel || instr->i_jabs) {
Neil Schemenauere441cb72009-10-14 19:14:38 +00003563 target_depth = depth;
3564 if (instr->i_opcode == FOR_ITER) {
3565 target_depth = depth-2;
3566 } else if (instr->i_opcode == SETUP_FINALLY ||
3567 instr->i_opcode == SETUP_EXCEPT) {
3568 target_depth = depth+3;
3569 if (target_depth > maxdepth)
3570 maxdepth = target_depth;
3571 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572 maxdepth = stackdepth_walk(c, instr->i_target,
Neil Schemenauere441cb72009-10-14 19:14:38 +00003573 target_depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 if (instr->i_opcode == JUMP_ABSOLUTE ||
3575 instr->i_opcode == JUMP_FORWARD) {
3576 goto out; /* remaining code is dead */
3577 }
3578 }
3579 }
3580 if (b->b_next)
3581 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3582out:
3583 b->b_seen = 0;
3584 return maxdepth;
3585}
3586
3587/* Find the flow path that needs the largest stack. We assume that
3588 * cycles in the flow graph have no net effect on the stack depth.
3589 */
3590static int
3591stackdepth(struct compiler *c)
3592{
3593 basicblock *b, *entryblock;
3594 entryblock = NULL;
3595 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3596 b->b_seen = 0;
3597 b->b_startdepth = INT_MIN;
3598 entryblock = b;
3599 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003600 if (!entryblock)
3601 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 return stackdepth_walk(c, entryblock, 0, 0);
3603}
3604
3605static int
3606assemble_init(struct assembler *a, int nblocks, int firstlineno)
3607{
3608 memset(a, 0, sizeof(struct assembler));
3609 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003610 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 if (!a->a_bytecode)
3612 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003613 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 if (!a->a_lnotab)
3615 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003616 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3617 PyErr_NoMemory();
3618 return 0;
3619 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003621 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003622 if (!a->a_postorder) {
3623 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 return 1;
3627}
3628
3629static void
3630assemble_free(struct assembler *a)
3631{
3632 Py_XDECREF(a->a_bytecode);
3633 Py_XDECREF(a->a_lnotab);
3634 if (a->a_postorder)
3635 PyObject_Free(a->a_postorder);
3636}
3637
3638/* Return the size of a basic block in bytes. */
3639
3640static int
3641instrsize(struct instr *instr)
3642{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003643 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003644 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003645 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003646 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3647 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648}
3649
3650static int
3651blocksize(basicblock *b)
3652{
3653 int i;
3654 int size = 0;
3655
3656 for (i = 0; i < b->b_iused; i++)
3657 size += instrsize(&b->b_instr[i]);
3658 return size;
3659}
3660
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003661/* Appends a pair to the end of the line number table, a_lnotab, representing
3662 the instruction's bytecode offset and line number. See
3663 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003664
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003665static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003667{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 int d_bytecode, d_lineno;
3669 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003670 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671
3672 d_bytecode = a->a_offset - a->a_lineno_off;
3673 d_lineno = i->i_lineno - a->a_lineno;
3674
3675 assert(d_bytecode >= 0);
3676 assert(d_lineno >= 0);
3677
Christian Heimes2202f872008-02-06 14:31:34 +00003678 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003679 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003680
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003682 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003684 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003686 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003688 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003690 else {
3691 PyErr_NoMemory();
3692 return 0;
3693 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003694 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003696 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003697 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003698 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003699 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700 *lnotab++ = 255;
3701 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703 d_bytecode -= ncodes * 255;
3704 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003705 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003706 assert(d_bytecode <= 255);
3707 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003708 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003710 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003711 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003712 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003714 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003715 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003716 else {
3717 PyErr_NoMemory();
3718 return 0;
3719 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003720 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003722 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003723 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003724 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003726 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003728 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003730 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003731 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003732 d_lineno -= ncodes * 255;
3733 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003734 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003735
Christian Heimes72b710a2008-05-26 13:28:38 +00003736 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003737 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003738 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003739 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003740 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003741 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003742 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003743
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744 a->a_lnotab_off += 2;
3745 if (d_bytecode) {
3746 *lnotab++ = d_bytecode;
3747 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003748 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003749 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 *lnotab++ = 0;
3751 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003752 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753 a->a_lineno = i->i_lineno;
3754 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003755 return 1;
3756}
3757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758/* assemble_emit()
3759 Extend the bytecode with a new instruction.
3760 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003761*/
3762
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003763static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003765{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003766 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003767 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768 char *code;
3769
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003770 size = instrsize(i);
3771 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003773 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003774 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003776 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003778 if (len > PY_SSIZE_T_MAX / 2)
3779 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003780 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003781 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003782 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003783 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003785 if (size == 6) {
3786 assert(i->i_hasarg);
3787 *code++ = (char)EXTENDED_ARG;
3788 *code++ = ext & 0xff;
3789 *code++ = ext >> 8;
3790 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003791 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003793 if (i->i_hasarg) {
3794 assert(size == 3 || size == 6);
3795 *code++ = arg & 0xff;
3796 *code++ = arg >> 8;
3797 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003799}
3800
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003801static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003803{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 basicblock *b;
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003805 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003806 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003807
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808 /* Compute the size of each block and fixup jump args.
3809 Replace block pointer with position in bytecode. */
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003810 do {
3811 totsize = 0;
3812 for (i = a->a_nblocks - 1; i >= 0; i--) {
3813 b = a->a_postorder[i];
3814 bsize = blocksize(b);
3815 b->b_offset = totsize;
3816 totsize += bsize;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003817 }
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003818 last_extended_arg_count = extended_arg_count;
3819 extended_arg_count = 0;
3820 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3821 bsize = b->b_offset;
3822 for (i = 0; i < b->b_iused; i++) {
3823 struct instr *instr = &b->b_instr[i];
3824 /* Relative jumps are computed relative to
3825 the instruction pointer after fetching
3826 the jump instruction.
3827 */
3828 bsize += instrsize(instr);
3829 if (instr->i_jabs)
3830 instr->i_oparg = instr->i_target->b_offset;
3831 else if (instr->i_jrel) {
3832 int delta = instr->i_target->b_offset - bsize;
3833 instr->i_oparg = delta;
3834 }
3835 else
3836 continue;
3837 if (instr->i_oparg > 0xffff)
3838 extended_arg_count++;
3839 }
3840 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003841
3842 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003843 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003844 with a better solution.
3845
Neal Norwitzf1d50682005-10-23 23:00:41 +00003846 The issue is that in the first loop blocksize() is called
3847 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003848 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003849 i_oparg is calculated in the second loop above.
3850
3851 So we loop until we stop seeing new EXTENDED_ARGs.
3852 The only EXTENDED_ARGs that could be popping up are
3853 ones in jump instructions. So this should converge
3854 fairly quickly.
3855 */
Benjamin Petersonf6489f92009-11-25 17:46:26 +00003856 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003857}
3858
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003859static PyObject *
3860dict_keys_inorder(PyObject *dict, int offset)
3861{
3862 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003863 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003864
3865 tuple = PyTuple_New(size);
3866 if (tuple == NULL)
3867 return NULL;
3868 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003869 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003870 /* The keys of the dictionary are tuples. (see compiler_add_o)
3871 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003872 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003873 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003874 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003875 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003876 PyTuple_SET_ITEM(tuple, i - offset, k);
3877 }
3878 return tuple;
3879}
3880
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003881static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003883{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 PySTEntryObject *ste = c->u->u_ste;
3885 int flags = 0, n;
3886 if (ste->ste_type != ModuleBlock)
3887 flags |= CO_NEWLOCALS;
3888 if (ste->ste_type == FunctionBlock) {
3889 if (!ste->ste_unoptimized)
3890 flags |= CO_OPTIMIZED;
3891 if (ste->ste_nested)
3892 flags |= CO_NESTED;
3893 if (ste->ste_generator)
3894 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003895 if (ste->ste_varargs)
3896 flags |= CO_VARARGS;
3897 if (ste->ste_varkeywords)
3898 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003899 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003900
3901 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003902 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 n = PyDict_Size(c->u->u_freevars);
3905 if (n < 0)
3906 return -1;
3907 if (n == 0) {
3908 n = PyDict_Size(c->u->u_cellvars);
3909 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003910 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911 if (n == 0) {
3912 flags |= CO_NOFREE;
3913 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003914 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003915
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003916 return flags;
3917}
3918
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003919static PyCodeObject *
3920makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003921{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922 PyObject *tmp;
3923 PyCodeObject *co = NULL;
3924 PyObject *consts = NULL;
3925 PyObject *names = NULL;
3926 PyObject *varnames = NULL;
3927 PyObject *filename = NULL;
3928 PyObject *name = NULL;
3929 PyObject *freevars = NULL;
3930 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003931 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934 tmp = dict_keys_inorder(c->u->u_consts, 0);
3935 if (!tmp)
3936 goto error;
3937 consts = PySequence_List(tmp); /* optimize_code requires a list */
3938 Py_DECREF(tmp);
3939
3940 names = dict_keys_inorder(c->u->u_names, 0);
3941 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3942 if (!consts || !names || !varnames)
3943 goto error;
3944
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003945 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3946 if (!cellvars)
3947 goto error;
3948 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3949 if (!freevars)
3950 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003951 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003952 if (!filename)
3953 goto error;
3954
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003955 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003956 flags = compute_code_flags(c);
3957 if (flags < 0)
3958 goto error;
3959
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003960 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003961 if (!bytecode)
3962 goto error;
3963
3964 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3965 if (!tmp)
3966 goto error;
3967 Py_DECREF(consts);
3968 consts = tmp;
3969
Guido van Rossum4f72a782006-10-27 23:31:49 +00003970 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3971 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972 bytecode, consts, names, varnames,
3973 freevars, cellvars,
3974 filename, c->u->u_name,
3975 c->u->u_firstlineno,
3976 a->a_lnotab);
3977 error:
3978 Py_XDECREF(consts);
3979 Py_XDECREF(names);
3980 Py_XDECREF(varnames);
3981 Py_XDECREF(filename);
3982 Py_XDECREF(name);
3983 Py_XDECREF(freevars);
3984 Py_XDECREF(cellvars);
3985 Py_XDECREF(bytecode);
3986 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003987}
3988
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003989
3990/* For debugging purposes only */
3991#if 0
3992static void
3993dump_instr(const struct instr *i)
3994{
3995 const char *jrel = i->i_jrel ? "jrel " : "";
3996 const char *jabs = i->i_jabs ? "jabs " : "";
3997 char arg[128];
3998
3999 *arg = '\0';
4000 if (i->i_hasarg)
4001 sprintf(arg, "arg: %d ", i->i_oparg);
4002
4003 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4004 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4005}
4006
4007static void
4008dump_basicblock(const basicblock *b)
4009{
4010 const char *seen = b->b_seen ? "seen " : "";
4011 const char *b_return = b->b_return ? "return " : "";
4012 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4013 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4014 if (b->b_instr) {
4015 int i;
4016 for (i = 0; i < b->b_iused; i++) {
4017 fprintf(stderr, " [%02d] ", i);
4018 dump_instr(b->b_instr + i);
4019 }
4020 }
4021}
4022#endif
4023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004024static PyCodeObject *
4025assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004026{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004027 basicblock *b, *entryblock;
4028 struct assembler a;
4029 int i, j, nblocks;
4030 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004031
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004032 /* Make sure every block that falls off the end returns None.
4033 XXX NEXT_BLOCK() isn't quite right, because if the last
4034 block ends with a jump or return b_next shouldn't set.
4035 */
4036 if (!c->u->u_curblock->b_return) {
4037 NEXT_BLOCK(c);
4038 if (addNone)
4039 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4040 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004041 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004043 nblocks = 0;
4044 entryblock = NULL;
4045 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4046 nblocks++;
4047 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004048 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004049
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004050 /* Set firstlineno if it wasn't explicitly set. */
4051 if (!c->u->u_firstlineno) {
4052 if (entryblock && entryblock->b_instr)
4053 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4054 else
4055 c->u->u_firstlineno = 1;
4056 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4058 goto error;
4059 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004060
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004062 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004063
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004064 /* Emit code in reverse postorder from dfs. */
4065 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004066 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067 for (j = 0; j < b->b_iused; j++)
4068 if (!assemble_emit(&a, &b->b_instr[j]))
4069 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004070 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004071
Christian Heimes72b710a2008-05-26 13:28:38 +00004072 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004074 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004075 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004076
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077 co = makecode(c, &a);
4078 error:
4079 assemble_free(&a);
4080 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004081}