blob: 95ebd76910085040fc62e57e37e9c165f97ee730 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Guido van Rossumd8faa362007-04-27 19:54:29 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Nick Coghlan650f0d02007-04-15 12:05:43 +000042#define COMP_GENEXP 0
43#define COMP_LISTCOMP 1
44#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000045#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
50 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000072 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000073 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
88enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
89
90struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000091 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092 basicblock *fb_block;
93};
94
95/* The following items change on entry and exit of code blocks.
96 They must be saved and restored when returning to a block.
97*/
98struct compiler_unit {
99 PySTEntryObject *u_ste;
100
101 PyObject *u_name;
102 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000103 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000104 the argument for opcodes that refer to those collections.
105 */
106 PyObject *u_consts; /* all constants */
107 PyObject *u_names; /* all names */
108 PyObject *u_varnames; /* local variables */
109 PyObject *u_cellvars; /* cell variables */
110 PyObject *u_freevars; /* free variables */
111
112 PyObject *u_private; /* for private name mangling */
113
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000114 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000115 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 /* Pointer to the most recently allocated block. By following b_list
117 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
122 int u_nfblocks;
123 struct fblockinfo u_fblock[CO_MAXBLOCKS];
124
125 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000126 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000127 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128 has been generated with current lineno */
129};
130
131/* This struct captures the global state of a compilation.
132
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133The u pointer points to the current compilation unit, while units
134for enclosing blocks are stored in c_stack. The u and c_stack are
135managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136*/
137
138struct compiler {
139 const char *c_filename;
140 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142 PyCompilerFlags *c_flags;
143
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 struct compiler_unit *u; /* compiler state for current block */
148 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151};
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153static int compiler_enter_scope(struct compiler *, identifier, void *, int);
154static void compiler_free(struct compiler *);
155static basicblock *compiler_new_block(struct compiler *);
156static int compiler_next_instr(struct compiler *, basicblock *);
157static int compiler_addop(struct compiler *, int);
158static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
159static int compiler_addop_i(struct compiler *, int, int);
160static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161static basicblock *compiler_use_new_block(struct compiler *);
162static int compiler_error(struct compiler *, const char *);
163static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
164
165static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
166static int compiler_visit_stmt(struct compiler *, stmt_ty);
167static int compiler_visit_keyword(struct compiler *, keyword_ty);
168static int compiler_visit_expr(struct compiler *, expr_ty);
169static int compiler_augassign(struct compiler *, stmt_ty);
170static int compiler_visit_slice(struct compiler *, slice_ty,
171 expr_context_ty);
172
173static int compiler_push_fblock(struct compiler *, enum fblocktype,
174 basicblock *);
175static void compiler_pop_fblock(struct compiler *, enum fblocktype,
176 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177/* Returns true if there is a loop on the fblock stack. */
178static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179
180static int inplace_binop(struct compiler *, operator_ty);
181static int expr_constant(expr_ty e);
182
Guido van Rossumc2e20742006-02-27 22:32:47 +0000183static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000184static int compiler_call_helper(struct compiler *c, int n,
185 asdl_seq *args,
186 asdl_seq *keywords,
187 expr_ty starargs,
188 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static PyCodeObject *assemble(struct compiler *, int addNone);
191static PyObject *__doc__;
192
193PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000195{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 /* Name mangling: __private becomes _classname__private.
197 This is independent from how the name is used. */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000198 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
199 Py_UNICODE *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200 size_t nlen, plen;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000201 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000202 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000203 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000206 p = PyUnicode_AS_UNICODE(privateobj);
207 nlen = Py_UNICODE_strlen(name);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 /* Don't mangle __id__ or names with dots.
209
210 The only time a name with a dot can occur is when
211 we are compiling an import statement that has a
212 package name.
213
214 TODO(jhylton): Decide whether we want to support
215 mangling of the module name, e.g. __M.X.
216 */
217 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Martin v. Löwis5b222132007-06-10 09:51:05 +0000218 || Py_UNICODE_strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 /* Strip leading underscores from class name */
223 while (*p == '_')
224 p++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000225 if (*p == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000229 plen = Py_UNICODE_strlen(p);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000230
231 assert(1 <= PY_SSIZE_T_MAX - nlen);
232 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
233
Martin v. Löwis5b222132007-06-10 09:51:05 +0000234 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 if (!ident)
236 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000238 buffer = PyUnicode_AS_UNICODE(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000239 buffer[0] = '_';
Martin v. Löwis5b222132007-06-10 09:51:05 +0000240 Py_UNICODE_strncpy(buffer+1, p, plen);
241 Py_UNICODE_strcpy(buffer+1+plen, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000243}
244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245static int
246compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000247{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000248 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250 c->c_stack = PyList_New(0);
251 if (!c->c_stack)
252 return 0;
253
254 return 1;
255}
256
257PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000258PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000259 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260{
261 struct compiler c;
262 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000263 PyCompilerFlags local_flags;
264 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000266 if (!__doc__) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000267 __doc__ = PyUnicode_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000268 if (!__doc__)
269 return NULL;
270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271
272 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000273 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000274 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000275 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000276 c.c_future = PyFuture_FromAST(mod, filename);
277 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000278 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000280 local_flags.cf_flags = 0;
281 flags = &local_flags;
282 }
283 merged = c.c_future->ff_features | flags->cf_flags;
284 c.c_future->ff_features = merged;
285 flags->cf_flags = merged;
286 c.c_flags = flags;
287 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288
289 c.c_st = PySymtable_Build(mod, filename, c.c_future);
290 if (c.c_st == NULL) {
291 if (!PyErr_Occurred())
292 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 }
295
296 /* XXX initialize to NULL for now, need to handle */
297 c.c_encoding = NULL;
298
299 co = compiler_mod(&c, mod);
300
Thomas Wouters1175c432006-02-27 22:49:54 +0000301 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000303 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304 return co;
305}
306
307PyCodeObject *
308PyNode_Compile(struct _node *n, const char *filename)
309{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000310 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000311 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000312 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000313 if (!arena)
314 return NULL;
315 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000316 if (mod)
317 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000318 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000319 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000320}
321
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000324{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 if (c->c_st)
326 PySymtable_Free(c->c_st);
327 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000330}
331
Guido van Rossum79f25d91997-04-29 20:08:16 +0000332static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000334{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000335 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000336 PyObject *v, *k;
337 PyObject *dict = PyDict_New();
338 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340 n = PyList_Size(list);
341 for (i = 0; i < n; i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000342 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 if (!v) {
344 Py_DECREF(dict);
345 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000347 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000348 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
350 Py_XDECREF(k);
351 Py_DECREF(v);
352 Py_DECREF(dict);
353 return NULL;
354 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000355 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000357 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 return dict;
359}
360
361/* Return new dict containing names from src that match scope(s).
362
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000363src is a symbol table dictionary. If the scope of a name matches
364either scope_type or flag is set, insert it into the new dict. The
365values are integers, starting at offset and increasing by one for
366each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367*/
368
369static PyObject *
370dictbytype(PyObject *src, int scope_type, int flag, int offset)
371{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000372 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000373 PyObject *k, *v, *dest = PyDict_New();
374
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000375 assert(offset >= 0);
376 if (dest == NULL)
377 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378
379 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000380 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000381 long vi;
Christian Heimes217cfd12007-12-02 14:31:20 +0000382 assert(PyLong_Check(v));
383 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000384 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000386 if (scope == scope_type || vi & flag) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000387 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 if (item == NULL) {
389 Py_DECREF(dest);
390 return NULL;
391 }
392 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000393 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000394 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
395 Py_DECREF(item);
396 Py_DECREF(dest);
397 Py_XDECREF(tuple);
398 return NULL;
399 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000401 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403 }
404 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000405}
406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407static void
408compiler_unit_check(struct compiler_unit *u)
409{
410 basicblock *block;
411 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Christian Heimes77c02eb2008-02-09 02:18:51 +0000412 assert((void *)block != (void *)0xcbcbcbcb);
413 assert((void *)block != (void *)0xfbfbfbfb);
414 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415 if (block->b_instr != NULL) {
416 assert(block->b_ialloc > 0);
417 assert(block->b_iused > 0);
418 assert(block->b_ialloc >= block->b_iused);
419 }
420 else {
421 assert (block->b_iused == 0);
422 assert (block->b_ialloc == 0);
423 }
424 }
425}
426
427static void
428compiler_unit_free(struct compiler_unit *u)
429{
430 basicblock *b, *next;
431
432 compiler_unit_check(u);
433 b = u->u_blocks;
434 while (b != NULL) {
435 if (b->b_instr)
436 PyObject_Free((void *)b->b_instr);
437 next = b->b_list;
438 PyObject_Free((void *)b);
439 b = next;
440 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000441 Py_CLEAR(u->u_ste);
442 Py_CLEAR(u->u_name);
443 Py_CLEAR(u->u_consts);
444 Py_CLEAR(u->u_names);
445 Py_CLEAR(u->u_varnames);
446 Py_CLEAR(u->u_freevars);
447 Py_CLEAR(u->u_cellvars);
448 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449 PyObject_Free(u);
450}
451
452static int
453compiler_enter_scope(struct compiler *c, identifier name, void *key,
454 int lineno)
455{
456 struct compiler_unit *u;
457
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000459 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000460 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 PyErr_NoMemory();
462 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000463 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000465 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000466 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 u->u_ste = PySymtable_Lookup(c->c_st, key);
468 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000469 compiler_unit_free(u);
470 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471 }
472 Py_INCREF(name);
473 u->u_name = name;
474 u->u_varnames = list2dict(u->u_ste->ste_varnames);
475 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000476 if (!u->u_varnames || !u->u_cellvars) {
477 compiler_unit_free(u);
478 return 0;
479 }
480
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000482 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000483 if (!u->u_freevars) {
484 compiler_unit_free(u);
485 return 0;
486 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487
488 u->u_blocks = NULL;
489 u->u_tmpname = 0;
490 u->u_nfblocks = 0;
491 u->u_firstlineno = lineno;
492 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000493 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000494 u->u_consts = PyDict_New();
495 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000496 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497 return 0;
498 }
499 u->u_names = PyDict_New();
500 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000501 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502 return 0;
503 }
504
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000505 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000506
507 /* Push the old compiler_unit on the stack. */
508 if (c->u) {
509 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000510 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
511 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513 return 0;
514 }
515 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000516 u->u_private = c->u->u_private;
517 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518 }
519 c->u = u;
520
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000521 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000522 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523 return 0;
524
525 return 1;
526}
527
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000528static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529compiler_exit_scope(struct compiler *c)
530{
531 int n;
532 PyObject *wrapper;
533
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000534 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535 compiler_unit_free(c->u);
536 /* Restore c->u to the parent unit. */
537 n = PyList_GET_SIZE(c->c_stack) - 1;
538 if (n >= 0) {
539 wrapper = PyList_GET_ITEM(c->c_stack, n);
540 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000541 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000542 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000544 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545 compiler_unit_check(c->u);
546 }
547 else
548 c->u = NULL;
549
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550}
551
Guido van Rossumc2e20742006-02-27 22:32:47 +0000552/* Allocate a new "anonymous" local variable.
553 Used by list comprehensions and with statements.
554*/
555
556static PyObject *
557compiler_new_tmpname(struct compiler *c)
558{
559 char tmpname[256];
560 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000561 return PyUnicode_FromString(tmpname);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000562}
563
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564/* Allocate a new block and return a pointer to it.
565 Returns NULL on error.
566*/
567
568static basicblock *
569compiler_new_block(struct compiler *c)
570{
571 basicblock *b;
572 struct compiler_unit *u;
573
574 u = c->u;
575 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000576 if (b == NULL) {
577 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582 b->b_list = u->u_blocks;
583 u->u_blocks = b;
584 return b;
585}
586
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587static basicblock *
588compiler_use_new_block(struct compiler *c)
589{
590 basicblock *block = compiler_new_block(c);
591 if (block == NULL)
592 return NULL;
593 c->u->u_curblock = block;
594 return block;
595}
596
597static basicblock *
598compiler_next_block(struct compiler *c)
599{
600 basicblock *block = compiler_new_block(c);
601 if (block == NULL)
602 return NULL;
603 c->u->u_curblock->b_next = block;
604 c->u->u_curblock = block;
605 return block;
606}
607
608static basicblock *
609compiler_use_next_block(struct compiler *c, basicblock *block)
610{
611 assert(block != NULL);
612 c->u->u_curblock->b_next = block;
613 c->u->u_curblock = block;
614 return block;
615}
616
617/* Returns the offset of the next instruction in the current block's
618 b_instr array. Resizes the b_instr as necessary.
619 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000620*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
622static int
623compiler_next_instr(struct compiler *c, basicblock *b)
624{
625 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000626 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000628 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629 if (b->b_instr == NULL) {
630 PyErr_NoMemory();
631 return -1;
632 }
633 b->b_ialloc = DEFAULT_BLOCK_SIZE;
634 memset((char *)b->b_instr, 0,
635 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000636 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639 size_t oldsize, newsize;
640 oldsize = b->b_ialloc * sizeof(struct instr);
641 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000642
643 if (oldsize > (PY_SIZE_MAX >> 1)) {
644 PyErr_NoMemory();
645 return -1;
646 }
647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648 if (newsize == 0) {
649 PyErr_NoMemory();
650 return -1;
651 }
652 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655 if (tmp == NULL) {
656 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658 }
659 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
661 }
662 return b->b_iused++;
663}
664
Christian Heimes2202f872008-02-06 14:31:34 +0000665/* Set the i_lineno member of the instruction at offset off if the
666 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000667 already been set. If it has been set, the call has no effect.
668
Christian Heimes2202f872008-02-06 14:31:34 +0000669 The line number is reset in the following cases:
670 - when entering a new scope
671 - on each statement
672 - on each expression that start a new line
673 - before the "except" clause
674 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677static void
678compiler_set_lineno(struct compiler *c, int off)
679{
680 basicblock *b;
681 if (c->u->u_lineno_set)
682 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000683 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000685 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686}
687
688static int
689opcode_stack_effect(int opcode, int oparg)
690{
691 switch (opcode) {
692 case POP_TOP:
693 return -1;
694 case ROT_TWO:
695 case ROT_THREE:
696 return 0;
697 case DUP_TOP:
698 return 1;
699 case ROT_FOUR:
700 return 0;
701
702 case UNARY_POSITIVE:
703 case UNARY_NEGATIVE:
704 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705 case UNARY_INVERT:
706 return 0;
707
Nick Coghlan650f0d02007-04-15 12:05:43 +0000708 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000709 case LIST_APPEND:
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000710 return -1;
711 case MAP_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000712 return -2;
713
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714 case BINARY_POWER:
715 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716 case BINARY_MODULO:
717 case BINARY_ADD:
718 case BINARY_SUBTRACT:
719 case BINARY_SUBSCR:
720 case BINARY_FLOOR_DIVIDE:
721 case BINARY_TRUE_DIVIDE:
722 return -1;
723 case INPLACE_FLOOR_DIVIDE:
724 case INPLACE_TRUE_DIVIDE:
725 return -1;
726
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000727 case INPLACE_ADD:
728 case INPLACE_SUBTRACT:
729 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 case INPLACE_MODULO:
731 return -1;
732 case STORE_SUBSCR:
733 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000734 case STORE_MAP:
735 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736 case DELETE_SUBSCR:
737 return -2;
738
739 case BINARY_LSHIFT:
740 case BINARY_RSHIFT:
741 case BINARY_AND:
742 case BINARY_XOR:
743 case BINARY_OR:
744 return -1;
745 case INPLACE_POWER:
746 return -1;
747 case GET_ITER:
748 return 0;
749
750 case PRINT_EXPR:
751 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000752 case LOAD_BUILD_CLASS:
753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754 case INPLACE_LSHIFT:
755 case INPLACE_RSHIFT:
756 case INPLACE_AND:
757 case INPLACE_XOR:
758 case INPLACE_OR:
759 return -1;
760 case BREAK_LOOP:
761 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000762 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000763 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000764 case STORE_LOCALS:
765 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766 case RETURN_VALUE:
767 return -1;
768 case IMPORT_STAR:
769 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770 case YIELD_VALUE:
771 return 0;
772
773 case POP_BLOCK:
774 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000775 case POP_EXCEPT:
776 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777 case END_FINALLY:
778 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779
780 case STORE_NAME:
781 return -1;
782 case DELETE_NAME:
783 return 0;
784 case UNPACK_SEQUENCE:
785 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000786 case UNPACK_EX:
787 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788 case FOR_ITER:
789 return 1;
790
791 case STORE_ATTR:
792 return -2;
793 case DELETE_ATTR:
794 return -1;
795 case STORE_GLOBAL:
796 return -1;
797 case DELETE_GLOBAL:
798 return 0;
799 case DUP_TOPX:
800 return oparg;
801 case LOAD_CONST:
802 return 1;
803 case LOAD_NAME:
804 return 1;
805 case BUILD_TUPLE:
806 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000807 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808 return 1-oparg;
809 case BUILD_MAP:
810 return 1;
811 case LOAD_ATTR:
812 return 0;
813 case COMPARE_OP:
814 return -1;
815 case IMPORT_NAME:
816 return 0;
817 case IMPORT_FROM:
818 return 1;
819
820 case JUMP_FORWARD:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000821 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
822 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000823 case JUMP_ABSOLUTE:
824 return 0;
825
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000826 case POP_JUMP_IF_FALSE:
827 case POP_JUMP_IF_TRUE:
828 return -1;
829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830 case LOAD_GLOBAL:
831 return 1;
832
833 case CONTINUE_LOOP:
834 return 0;
835 case SETUP_LOOP:
836 return 0;
837 case SETUP_EXCEPT:
838 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000839 return 6; /* can push 3 values for the new exception
840 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
842 case LOAD_FAST:
843 return 1;
844 case STORE_FAST:
845 return -1;
846 case DELETE_FAST:
847 return 0;
848
849 case RAISE_VARARGS:
850 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000851#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852 case CALL_FUNCTION:
853 return -NARGS(oparg);
854 case CALL_FUNCTION_VAR:
855 case CALL_FUNCTION_KW:
856 return -NARGS(oparg)-1;
857 case CALL_FUNCTION_VAR_KW:
858 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000860 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000861 case MAKE_CLOSURE:
862 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000863#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864 case BUILD_SLICE:
865 if (oparg == 3)
866 return -2;
867 else
868 return -1;
869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870 case LOAD_CLOSURE:
871 return 1;
872 case LOAD_DEREF:
873 return 1;
874 case STORE_DEREF:
875 return -1;
876 default:
877 fprintf(stderr, "opcode = %d\n", opcode);
878 Py_FatalError("opcode_stack_effect()");
879
880 }
881 return 0; /* not reachable */
882}
883
884/* Add an opcode with no argument.
885 Returns 0 on failure, 1 on success.
886*/
887
888static int
889compiler_addop(struct compiler *c, int opcode)
890{
891 basicblock *b;
892 struct instr *i;
893 int off;
894 off = compiler_next_instr(c, c->u->u_curblock);
895 if (off < 0)
896 return 0;
897 b = c->u->u_curblock;
898 i = &b->b_instr[off];
899 i->i_opcode = opcode;
900 i->i_hasarg = 0;
901 if (opcode == RETURN_VALUE)
902 b->b_return = 1;
903 compiler_set_lineno(c, off);
904 return 1;
905}
906
907static int
908compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
909{
910 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000911 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000912 unsigned char *p, *q;
913 Py_complex z;
914 double d;
915 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000916
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000917 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000918 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
919 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000920 d = PyFloat_AS_DOUBLE(o);
921 p = (unsigned char*) &d;
922 /* all we need is to make the tuple different in either the 0.0
923 * or -0.0 case from all others, just to avoid the "coercion".
924 */
925 if (*p==0 && p[sizeof(double)-1]==0)
926 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
927 else
928 t = PyTuple_Pack(2, o, o->ob_type);
929 }
930 else if (PyComplex_Check(o)) {
931 /* complex case is even messier: we need to make complex(x,
932 0.) different from complex(x, -0.) and complex(0., y)
933 different from complex(-0., y), for any x and y. In
934 particular, all four complex zeros should be
935 distinguished.*/
936 z = PyComplex_AsCComplex(o);
937 p = (unsigned char*) &(z.real);
938 q = (unsigned char*) &(z.imag);
939 /* all that matters here is that on IEEE platforms
940 real_part_zero will be true if z.real == 0., and false if
941 z.real == -0. In fact, real_part_zero will also be true
942 for some other rarely occurring nonzero floats, but this
943 doesn't matter. Similar comments apply to
944 imag_part_zero. */
945 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
946 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
947 if (real_part_zero && imag_part_zero) {
948 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
949 }
950 else if (real_part_zero && !imag_part_zero) {
951 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
952 }
953 else if (!real_part_zero && imag_part_zero) {
954 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
955 }
956 else {
957 t = PyTuple_Pack(2, o, o->ob_type);
958 }
959 }
960 else {
961 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000962 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000963 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000964 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000965
966 v = PyDict_GetItem(dict, t);
967 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000968 if (PyErr_Occurred())
969 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000971 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 if (!v) {
973 Py_DECREF(t);
974 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000975 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976 if (PyDict_SetItem(dict, t, v) < 0) {
977 Py_DECREF(t);
978 Py_DECREF(v);
979 return -1;
980 }
981 Py_DECREF(v);
982 }
983 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000984 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987}
988
989static int
990compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
991 PyObject *o)
992{
993 int arg = compiler_add_o(c, dict, o);
994 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000995 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000996 return compiler_addop_i(c, opcode, arg);
997}
998
999static int
1000compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001001 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001002{
1003 int arg;
1004 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1005 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007 arg = compiler_add_o(c, dict, mangled);
1008 Py_DECREF(mangled);
1009 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001010 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011 return compiler_addop_i(c, opcode, arg);
1012}
1013
1014/* Add an opcode with an integer argument.
1015 Returns 0 on failure, 1 on success.
1016*/
1017
1018static int
1019compiler_addop_i(struct compiler *c, int opcode, int oparg)
1020{
1021 struct instr *i;
1022 int off;
1023 off = compiler_next_instr(c, c->u->u_curblock);
1024 if (off < 0)
1025 return 0;
1026 i = &c->u->u_curblock->b_instr[off];
1027 i->i_opcode = opcode;
1028 i->i_oparg = oparg;
1029 i->i_hasarg = 1;
1030 compiler_set_lineno(c, off);
1031 return 1;
1032}
1033
1034static int
1035compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1036{
1037 struct instr *i;
1038 int off;
1039
1040 assert(b != NULL);
1041 off = compiler_next_instr(c, c->u->u_curblock);
1042 if (off < 0)
1043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044 i = &c->u->u_curblock->b_instr[off];
1045 i->i_opcode = opcode;
1046 i->i_target = b;
1047 i->i_hasarg = 1;
1048 if (absolute)
1049 i->i_jabs = 1;
1050 else
1051 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001052 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001053 return 1;
1054}
1055
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001056/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1057 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058 it as the current block. NEXT_BLOCK() also creates an implicit jump
1059 from the current block to the new block.
1060*/
1061
Thomas Wouters89f507f2006-12-13 04:49:30 +00001062/* The returns inside these macros make it impossible to decref objects
1063 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064*/
1065
1066
1067#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001068 if (compiler_use_new_block((C)) == NULL) \
1069 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070}
1071
1072#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001073 if (compiler_next_block((C)) == NULL) \
1074 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075}
1076
1077#define ADDOP(C, OP) { \
1078 if (!compiler_addop((C), (OP))) \
1079 return 0; \
1080}
1081
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001082#define ADDOP_IN_SCOPE(C, OP) { \
1083 if (!compiler_addop((C), (OP))) { \
1084 compiler_exit_scope(c); \
1085 return 0; \
1086 } \
1087}
1088
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089#define ADDOP_O(C, OP, O, TYPE) { \
1090 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1091 return 0; \
1092}
1093
1094#define ADDOP_NAME(C, OP, O, TYPE) { \
1095 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1096 return 0; \
1097}
1098
1099#define ADDOP_I(C, OP, O) { \
1100 if (!compiler_addop_i((C), (OP), (O))) \
1101 return 0; \
1102}
1103
1104#define ADDOP_JABS(C, OP, O) { \
1105 if (!compiler_addop_j((C), (OP), (O), 1)) \
1106 return 0; \
1107}
1108
1109#define ADDOP_JREL(C, OP, O) { \
1110 if (!compiler_addop_j((C), (OP), (O), 0)) \
1111 return 0; \
1112}
1113
1114/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1115 the ASDL name to synthesize the name of the C type and the visit function.
1116*/
1117
1118#define VISIT(C, TYPE, V) {\
1119 if (!compiler_visit_ ## TYPE((C), (V))) \
1120 return 0; \
1121}
1122
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001123#define VISIT_IN_SCOPE(C, TYPE, V) {\
1124 if (!compiler_visit_ ## TYPE((C), (V))) { \
1125 compiler_exit_scope(c); \
1126 return 0; \
1127 } \
1128}
1129
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130#define VISIT_SLICE(C, V, CTX) {\
1131 if (!compiler_visit_slice((C), (V), (CTX))) \
1132 return 0; \
1133}
1134
1135#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001136 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001138 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001139 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 if (!compiler_visit_ ## TYPE((C), elt)) \
1141 return 0; \
1142 } \
1143}
1144
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001145#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001146 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001147 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001148 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001149 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001150 if (!compiler_visit_ ## TYPE((C), elt)) { \
1151 compiler_exit_scope(c); \
1152 return 0; \
1153 } \
1154 } \
1155}
1156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157static int
1158compiler_isdocstring(stmt_ty s)
1159{
1160 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001161 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 return s->v.Expr.value->kind == Str_kind;
1163}
1164
1165/* Compile a sequence of statements, checking for a docstring. */
1166
1167static int
1168compiler_body(struct compiler *c, asdl_seq *stmts)
1169{
1170 int i = 0;
1171 stmt_ty st;
1172
1173 if (!asdl_seq_LEN(stmts))
1174 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001176 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1177 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 i = 1;
1179 VISIT(c, expr, st->v.Expr.value);
1180 if (!compiler_nameop(c, __doc__, Store))
1181 return 0;
1182 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001183 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001184 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 return 1;
1186}
1187
1188static PyCodeObject *
1189compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001190{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001191 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001192 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 static PyObject *module;
1194 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001195 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 if (!module)
1197 return NULL;
1198 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001199 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1200 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001201 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202 switch (mod->kind) {
1203 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001204 if (!compiler_body(c, mod->v.Module.body)) {
1205 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001207 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 break;
1209 case Interactive_kind:
1210 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001211 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 break;
1214 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001215 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001216 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217 break;
1218 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001219 PyErr_SetString(PyExc_SystemError,
1220 "suite should not be possible");
1221 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001222 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001223 PyErr_Format(PyExc_SystemError,
1224 "module kind %d should not be possible",
1225 mod->kind);
1226 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001227 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228 co = assemble(c, addNone);
1229 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001230 return co;
1231}
1232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233/* The test for LOCAL must come before the test for FREE in order to
1234 handle classes where name is both local and free. The local var is
1235 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001236*/
1237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001238static int
1239get_ref_type(struct compiler *c, PyObject *name)
1240{
1241 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001242 if (scope == 0) {
1243 char buf[350];
1244 PyOS_snprintf(buf, sizeof(buf),
1245 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001246 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001247 PyBytes_AS_STRING(name),
1248 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001249 PyObject_REPR(c->u->u_ste->ste_id),
1250 c->c_filename,
1251 PyObject_REPR(c->u->u_ste->ste_symbols),
1252 PyObject_REPR(c->u->u_varnames),
1253 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001255 Py_FatalError(buf);
1256 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001257
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001258 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259}
1260
1261static int
1262compiler_lookup_arg(PyObject *dict, PyObject *name)
1263{
1264 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001265 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001267 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001269 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001271 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001272 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273}
1274
1275static int
1276compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1277{
1278 int i, free = PyCode_GetNumFree(co);
1279 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001280 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1281 ADDOP_I(c, MAKE_FUNCTION, args);
1282 return 1;
1283 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284 for (i = 0; i < free; ++i) {
1285 /* Bypass com_addop_varname because it will generate
1286 LOAD_DEREF but LOAD_CLOSURE is needed.
1287 */
1288 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1289 int arg, reftype;
1290
1291 /* Special case: If a class contains a method with a
1292 free variable that has the same name as a method,
1293 the name will be considered free *and* local in the
1294 class. It should be handled by the closure, as
1295 well as by the normal name loookup logic.
1296 */
1297 reftype = get_ref_type(c, name);
1298 if (reftype == CELL)
1299 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1300 else /* (reftype == FREE) */
1301 arg = compiler_lookup_arg(c->u->u_freevars, name);
1302 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001303 fprintf(stderr,
1304 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001305 "freevars of %s: %s\n",
1306 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001307 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001309 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310 PyObject_REPR(co->co_freevars));
1311 Py_FatalError("compiler_make_closure()");
1312 }
1313 ADDOP_I(c, LOAD_CLOSURE, arg);
1314 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001315 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001317 ADDOP_I(c, MAKE_CLOSURE, args);
1318 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319}
1320
1321static int
1322compiler_decorators(struct compiler *c, asdl_seq* decos)
1323{
1324 int i;
1325
1326 if (!decos)
1327 return 1;
1328
1329 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001330 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 }
1332 return 1;
1333}
1334
1335static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001336compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1337 asdl_seq *kw_defaults)
1338{
1339 int i, default_count = 0;
1340 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001341 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001342 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1343 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001344 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001345 if (!compiler_visit_expr(c, default_)) {
1346 return -1;
1347 }
1348 default_count++;
1349 }
1350 }
1351 return default_count;
1352}
1353
1354static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001355compiler_visit_argannotation(struct compiler *c, identifier id,
1356 expr_ty annotation, PyObject *names)
1357{
1358 if (annotation) {
1359 VISIT(c, expr, annotation);
1360 if (PyList_Append(names, id))
1361 return -1;
1362 }
1363 return 0;
1364}
1365
1366static int
1367compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1368 PyObject *names)
1369{
1370 int i, error;
1371 for (i = 0; i < asdl_seq_LEN(args); i++) {
1372 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001373 error = compiler_visit_argannotation(
1374 c,
1375 arg->arg,
1376 arg->annotation,
1377 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001378 if (error)
1379 return error;
1380 }
1381 return 0;
1382}
1383
1384static int
1385compiler_visit_annotations(struct compiler *c, arguments_ty args,
1386 expr_ty returns)
1387{
Guido van Rossum0240b922007-02-26 21:23:50 +00001388 /* Push arg annotations and a list of the argument names. Return the #
1389 of items pushed. The expressions are evaluated out-of-order wrt the
1390 source code.
1391
1392 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1393 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001394 static identifier return_str;
1395 PyObject *names;
1396 int len;
1397 names = PyList_New(0);
1398 if (!names)
1399 return -1;
1400
1401 if (compiler_visit_argannotations(c, args->args, names))
1402 goto error;
1403 if (args->varargannotation &&
1404 compiler_visit_argannotation(c, args->vararg,
1405 args->varargannotation, names))
1406 goto error;
1407 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1408 goto error;
1409 if (args->kwargannotation &&
1410 compiler_visit_argannotation(c, args->kwarg,
1411 args->kwargannotation, names))
1412 goto error;
1413
1414 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001415 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001416 if (!return_str)
1417 goto error;
1418 }
1419 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1420 goto error;
1421 }
1422
1423 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001424 if (len > 65534) {
1425 /* len must fit in 16 bits, and len is incremented below */
1426 PyErr_SetString(PyExc_SyntaxError,
1427 "too many annotations");
1428 goto error;
1429 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001430 if (len) {
1431 /* convert names to a tuple and place on stack */
1432 PyObject *elt;
1433 int i;
1434 PyObject *s = PyTuple_New(len);
1435 if (!s)
1436 goto error;
1437 for (i = 0; i < len; i++) {
1438 elt = PyList_GET_ITEM(names, i);
1439 Py_INCREF(elt);
1440 PyTuple_SET_ITEM(s, i, elt);
1441 }
1442 ADDOP_O(c, LOAD_CONST, s, consts);
1443 Py_DECREF(s);
1444 len++; /* include the just-pushed tuple */
1445 }
1446 Py_DECREF(names);
1447 return len;
1448
1449error:
1450 Py_DECREF(names);
1451 return -1;
1452}
1453
1454static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455compiler_function(struct compiler *c, stmt_ty s)
1456{
1457 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001458 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001460 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001461 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001462 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001463 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001464 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465
1466 assert(s->kind == FunctionDef_kind);
1467
1468 if (!compiler_decorators(c, decos))
1469 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001470 if (args->kwonlyargs) {
1471 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1472 args->kw_defaults);
1473 if (res < 0)
1474 return 0;
1475 kw_default_count = res;
1476 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477 if (args->defaults)
1478 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001479 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001480 if (num_annotations < 0)
1481 return 0;
1482 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001483
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1485 s->lineno))
1486 return 0;
1487
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001488 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001489 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001490 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001491 first_const = st->v.Expr.value->v.Str.s;
1492 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001493 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001494 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001495 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001498 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001500 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001502 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1503 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504 }
1505 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001506 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507 if (co == NULL)
1508 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509
Guido van Rossum4f72a782006-10-27 23:31:49 +00001510 arglength = asdl_seq_LEN(args->defaults);
1511 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001512 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001513 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001514 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515
Neal Norwitzc1505362006-12-28 06:47:50 +00001516 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1518 ADDOP_I(c, CALL_FUNCTION, 1);
1519 }
1520
1521 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1522}
1523
1524static int
1525compiler_class(struct compiler *c, stmt_ty s)
1526{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001528 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001529 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001530 asdl_seq* decos = s->v.ClassDef.decorator_list;
1531
1532 if (!compiler_decorators(c, decos))
1533 return 0;
1534
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001535 /* ultimately generate code for:
1536 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1537 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001538 <func> is a function/closure created from the class body;
1539 it has a single argument (__locals__) where the dict
1540 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001541 <name> is the class name
1542 <bases> is the positional arguments and *varargs argument
1543 <keywords> is the keyword arguments and **kwds argument
1544 This borrows from compiler_call.
1545 */
1546
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001547 /* 1. compile the class body into a code object */
1548 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1549 return 0;
1550 /* this block represents what we do in the new scope */
1551 {
1552 /* use the class name for name mangling */
1553 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001554 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001555 c->u->u_private = s->v.ClassDef.name;
1556 /* force it to have one mandatory argument */
1557 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001558 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001559 ADDOP_I(c, LOAD_FAST, 0);
1560 /* ... and store it into f_locals */
1561 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001562 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001563 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001564 if (!str || !compiler_nameop(c, str, Load)) {
1565 Py_XDECREF(str);
1566 compiler_exit_scope(c);
1567 return 0;
1568 }
1569 Py_DECREF(str);
1570 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001571 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001572 if (!str || !compiler_nameop(c, str, Store)) {
1573 Py_XDECREF(str);
1574 compiler_exit_scope(c);
1575 return 0;
1576 }
1577 Py_DECREF(str);
1578 /* compile the body proper */
1579 if (!compiler_body(c, s->v.ClassDef.body)) {
1580 compiler_exit_scope(c);
1581 return 0;
1582 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001583 /* return the (empty) __class__ cell */
1584 str = PyUnicode_InternFromString("__class__");
1585 if (str == NULL) {
1586 compiler_exit_scope(c);
1587 return 0;
1588 }
1589 i = compiler_lookup_arg(c->u->u_cellvars, str);
1590 Py_DECREF(str);
1591 if (i == -1) {
1592 /* This happens when nobody references the cell */
1593 PyErr_Clear();
1594 /* Return None */
1595 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1596 }
1597 else {
1598 /* Return the cell where to store __class__ */
1599 ADDOP_I(c, LOAD_CLOSURE, i);
1600 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001601 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1602 /* create the code object */
1603 co = assemble(c, 1);
1604 }
1605 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001606 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001607 if (co == NULL)
1608 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001609
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001610 /* 2. load the 'build_class' function */
1611 ADDOP(c, LOAD_BUILD_CLASS);
1612
1613 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001614 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001615 Py_DECREF(co);
1616
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001617 /* 4. load class name */
1618 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1619
1620 /* 5. generate the rest of the code for the call */
1621 if (!compiler_call_helper(c, 2,
1622 s->v.ClassDef.bases,
1623 s->v.ClassDef.keywords,
1624 s->v.ClassDef.starargs,
1625 s->v.ClassDef.kwargs))
1626 return 0;
1627
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001628 /* 6. apply decorators */
1629 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1630 ADDOP_I(c, CALL_FUNCTION, 1);
1631 }
1632
1633 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001634 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1635 return 0;
1636 return 1;
1637}
1638
1639static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001640compiler_ifexp(struct compiler *c, expr_ty e)
1641{
1642 basicblock *end, *next;
1643
1644 assert(e->kind == IfExp_kind);
1645 end = compiler_new_block(c);
1646 if (end == NULL)
1647 return 0;
1648 next = compiler_new_block(c);
1649 if (next == NULL)
1650 return 0;
1651 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001652 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001653 VISIT(c, expr, e->v.IfExp.body);
1654 ADDOP_JREL(c, JUMP_FORWARD, end);
1655 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001656 VISIT(c, expr, e->v.IfExp.orelse);
1657 compiler_use_next_block(c, end);
1658 return 1;
1659}
1660
1661static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662compiler_lambda(struct compiler *c, expr_ty e)
1663{
1664 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001665 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001666 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667 arguments_ty args = e->v.Lambda.args;
1668 assert(e->kind == Lambda_kind);
1669
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001670 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001671 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001672 if (!name)
1673 return 0;
1674 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675
Guido van Rossum4f72a782006-10-27 23:31:49 +00001676 if (args->kwonlyargs) {
1677 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1678 args->kw_defaults);
1679 if (res < 0) return 0;
1680 kw_default_count = res;
1681 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 if (args->defaults)
1683 VISIT_SEQ(c, expr, args->defaults);
1684 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1685 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001686
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001688 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001689 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001690 if (c->u->u_ste->ste_generator) {
1691 ADDOP_IN_SCOPE(c, POP_TOP);
1692 }
1693 else {
1694 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001697 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698 if (co == NULL)
1699 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700
Guido van Rossum4f72a782006-10-27 23:31:49 +00001701 arglength = asdl_seq_LEN(args->defaults);
1702 arglength |= kw_default_count << 8;
1703 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001704 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705
1706 return 1;
1707}
1708
1709static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710compiler_if(struct compiler *c, stmt_ty s)
1711{
1712 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001713 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714 assert(s->kind == If_kind);
1715 end = compiler_new_block(c);
1716 if (end == NULL)
1717 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001718
1719 constant = expr_constant(s->v.If.test);
1720 /* constant = 0: "if 0"
1721 * constant = 1: "if 1", "if 2", ...
1722 * constant = -1: rest */
1723 if (constant == 0) {
1724 if (s->v.If.orelse)
1725 VISIT_SEQ(c, stmt, s->v.If.orelse);
1726 } else if (constant == 1) {
1727 VISIT_SEQ(c, stmt, s->v.If.body);
1728 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001729 if (s->v.If.orelse) {
1730 next = compiler_new_block(c);
1731 if (next == NULL)
1732 return 0;
1733 }
1734 else
1735 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001736 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001737 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001738 VISIT_SEQ(c, stmt, s->v.If.body);
1739 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001740 if (s->v.If.orelse) {
1741 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001742 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001743 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001744 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001745 compiler_use_next_block(c, end);
1746 return 1;
1747}
1748
1749static int
1750compiler_for(struct compiler *c, stmt_ty s)
1751{
1752 basicblock *start, *cleanup, *end;
1753
1754 start = compiler_new_block(c);
1755 cleanup = compiler_new_block(c);
1756 end = compiler_new_block(c);
1757 if (start == NULL || end == NULL || cleanup == NULL)
1758 return 0;
1759 ADDOP_JREL(c, SETUP_LOOP, end);
1760 if (!compiler_push_fblock(c, LOOP, start))
1761 return 0;
1762 VISIT(c, expr, s->v.For.iter);
1763 ADDOP(c, GET_ITER);
1764 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001765 /* for expressions must be traced on each iteration,
1766 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001767 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768 ADDOP_JREL(c, FOR_ITER, cleanup);
1769 VISIT(c, expr, s->v.For.target);
1770 VISIT_SEQ(c, stmt, s->v.For.body);
1771 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1772 compiler_use_next_block(c, cleanup);
1773 ADDOP(c, POP_BLOCK);
1774 compiler_pop_fblock(c, LOOP, start);
1775 VISIT_SEQ(c, stmt, s->v.For.orelse);
1776 compiler_use_next_block(c, end);
1777 return 1;
1778}
1779
1780static int
1781compiler_while(struct compiler *c, stmt_ty s)
1782{
1783 basicblock *loop, *orelse, *end, *anchor = NULL;
1784 int constant = expr_constant(s->v.While.test);
1785
Christian Heimes969fe572008-01-25 11:23:10 +00001786 if (constant == 0) {
1787 if (s->v.While.orelse)
1788 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 loop = compiler_new_block(c);
1792 end = compiler_new_block(c);
1793 if (constant == -1) {
1794 anchor = compiler_new_block(c);
1795 if (anchor == NULL)
1796 return 0;
1797 }
1798 if (loop == NULL || end == NULL)
1799 return 0;
1800 if (s->v.While.orelse) {
1801 orelse = compiler_new_block(c);
1802 if (orelse == NULL)
1803 return 0;
1804 }
1805 else
1806 orelse = NULL;
1807
1808 ADDOP_JREL(c, SETUP_LOOP, end);
1809 compiler_use_next_block(c, loop);
1810 if (!compiler_push_fblock(c, LOOP, loop))
1811 return 0;
1812 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001813 /* while expressions must be traced on each iteration,
1814 so we need to set an extra line number. */
1815 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001817 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818 }
1819 VISIT_SEQ(c, stmt, s->v.While.body);
1820 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1821
1822 /* XXX should the two POP instructions be in a separate block
1823 if there is no else clause ?
1824 */
1825
1826 if (constant == -1) {
1827 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828 ADDOP(c, POP_BLOCK);
1829 }
1830 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001831 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 VISIT_SEQ(c, stmt, s->v.While.orelse);
1833 compiler_use_next_block(c, end);
1834
1835 return 1;
1836}
1837
1838static int
1839compiler_continue(struct compiler *c)
1840{
1841 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001842 static const char IN_FINALLY_ERROR_MSG[] =
1843 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 int i;
1845
1846 if (!c->u->u_nfblocks)
1847 return compiler_error(c, LOOP_ERROR_MSG);
1848 i = c->u->u_nfblocks - 1;
1849 switch (c->u->u_fblock[i].fb_type) {
1850 case LOOP:
1851 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1852 break;
1853 case EXCEPT:
1854 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001855 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1856 /* Prevent continue anywhere under a finally
1857 even if hidden in a sub-try or except. */
1858 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1859 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1860 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 if (i == -1)
1862 return compiler_error(c, LOOP_ERROR_MSG);
1863 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1864 break;
1865 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001866 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 }
1868
1869 return 1;
1870}
1871
1872/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1873
1874 SETUP_FINALLY L
1875 <code for body>
1876 POP_BLOCK
1877 LOAD_CONST <None>
1878 L: <code for finalbody>
1879 END_FINALLY
1880
1881 The special instructions use the block stack. Each block
1882 stack entry contains the instruction that created it (here
1883 SETUP_FINALLY), the level of the value stack at the time the
1884 block stack entry was created, and a label (here L).
1885
1886 SETUP_FINALLY:
1887 Pushes the current value stack level and the label
1888 onto the block stack.
1889 POP_BLOCK:
1890 Pops en entry from the block stack, and pops the value
1891 stack until its level is the same as indicated on the
1892 block stack. (The label is ignored.)
1893 END_FINALLY:
1894 Pops a variable number of entries from the *value* stack
1895 and re-raises the exception they specify. The number of
1896 entries popped depends on the (pseudo) exception type.
1897
1898 The block stack is unwound when an exception is raised:
1899 when a SETUP_FINALLY entry is found, the exception is pushed
1900 onto the value stack (and the exception condition is cleared),
1901 and the interpreter jumps to the label gotten from the block
1902 stack.
1903*/
1904
1905static int
1906compiler_try_finally(struct compiler *c, stmt_ty s)
1907{
1908 basicblock *body, *end;
1909 body = compiler_new_block(c);
1910 end = compiler_new_block(c);
1911 if (body == NULL || end == NULL)
1912 return 0;
1913
1914 ADDOP_JREL(c, SETUP_FINALLY, end);
1915 compiler_use_next_block(c, body);
1916 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1917 return 0;
1918 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1919 ADDOP(c, POP_BLOCK);
1920 compiler_pop_fblock(c, FINALLY_TRY, body);
1921
1922 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1923 compiler_use_next_block(c, end);
1924 if (!compiler_push_fblock(c, FINALLY_END, end))
1925 return 0;
1926 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1927 ADDOP(c, END_FINALLY);
1928 compiler_pop_fblock(c, FINALLY_END, end);
1929
1930 return 1;
1931}
1932
1933/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001934 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935 (The contents of the value stack is shown in [], with the top
1936 at the right; 'tb' is trace-back info, 'val' the exception's
1937 associated value, and 'exc' the exception.)
1938
1939 Value stack Label Instruction Argument
1940 [] SETUP_EXCEPT L1
1941 [] <code for S>
1942 [] POP_BLOCK
1943 [] JUMP_FORWARD L0
1944
1945 [tb, val, exc] L1: DUP )
1946 [tb, val, exc, exc] <evaluate E1> )
1947 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001948 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949 [tb, val, exc] POP
1950 [tb, val] <assign to V1> (or POP if no V1)
1951 [tb] POP
1952 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001953 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001955 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 .............................etc.......................
1957
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001958 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959
1960 [] L0: <next statement>
1961
1962 Of course, parts are not generated if Vi or Ei is not present.
1963*/
1964static int
1965compiler_try_except(struct compiler *c, stmt_ty s)
1966{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001967 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968 int i, n;
1969
1970 body = compiler_new_block(c);
1971 except = compiler_new_block(c);
1972 orelse = compiler_new_block(c);
1973 end = compiler_new_block(c);
1974 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1975 return 0;
1976 ADDOP_JREL(c, SETUP_EXCEPT, except);
1977 compiler_use_next_block(c, body);
1978 if (!compiler_push_fblock(c, EXCEPT, body))
1979 return 0;
1980 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1981 ADDOP(c, POP_BLOCK);
1982 compiler_pop_fblock(c, EXCEPT, body);
1983 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1984 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1985 compiler_use_next_block(c, except);
1986 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001987 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001989 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001991 c->u->u_lineno_set = 0;
1992 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 except = compiler_new_block(c);
1994 if (except == NULL)
1995 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001996 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001998 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002000 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 }
2002 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002003 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00002004 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002005
2006 cleanup_end = compiler_new_block(c);
2007 cleanup_body = compiler_new_block(c);
2008 if(!(cleanup_end || cleanup_body))
2009 return 0;
2010
Neal Norwitzad74aa82008-03-31 05:14:30 +00002011 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002012 ADDOP(c, POP_TOP);
2013
2014 /*
2015 try:
2016 # body
2017 except type as name:
2018 try:
2019 # body
2020 finally:
2021 name = None
2022 del name
2023 */
2024
2025 /* second try: */
2026 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2027 compiler_use_next_block(c, cleanup_body);
2028 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2029 return 0;
2030
2031 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002032 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002033 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002034 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002035 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2036
2037 /* finally: */
2038 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2039 compiler_use_next_block(c, cleanup_end);
2040 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2041 return 0;
2042
2043 /* name = None */
2044 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002045 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002046
Guido van Rossum16be03e2007-01-10 18:51:35 +00002047 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002048 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002049
2050 ADDOP(c, END_FINALLY);
2051 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 }
2053 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002054 basicblock *cleanup_body;
2055
2056 cleanup_body = compiler_new_block(c);
2057 if(!cleanup_body)
2058 return 0;
2059
2060 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002061 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002062 compiler_use_next_block(c, cleanup_body);
2063 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2064 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002065 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002066 ADDOP(c, POP_EXCEPT);
2067 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069 ADDOP_JREL(c, JUMP_FORWARD, end);
2070 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 }
2072 ADDOP(c, END_FINALLY);
2073 compiler_use_next_block(c, orelse);
2074 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2075 compiler_use_next_block(c, end);
2076 return 1;
2077}
2078
2079static int
2080compiler_import_as(struct compiler *c, identifier name, identifier asname)
2081{
2082 /* The IMPORT_NAME opcode was already generated. This function
2083 merely needs to bind the result to a name.
2084
2085 If there is a dot in name, we need to split it and emit a
2086 LOAD_ATTR for each name.
2087 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002088 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2089 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 if (dot) {
2091 /* Consume the base module name to get the first attribute */
2092 src = dot + 1;
2093 while (dot) {
2094 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002095 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002096 dot = Py_UNICODE_strchr(src, '.');
2097 attr = PyUnicode_FromUnicode(src,
2098 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002099 if (!attr)
2100 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002102 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 src = dot + 1;
2104 }
2105 }
2106 return compiler_nameop(c, asname, Store);
2107}
2108
2109static int
2110compiler_import(struct compiler *c, stmt_ty s)
2111{
2112 /* The Import node stores a module name like a.b.c as a single
2113 string. This is convenient for all cases except
2114 import a.b.c as d
2115 where we need to parse that string to extract the individual
2116 module names.
2117 XXX Perhaps change the representation to make this case simpler?
2118 */
2119 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002122 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002124 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125
Christian Heimes217cfd12007-12-02 14:31:20 +00002126 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002127 if (level == NULL)
2128 return 0;
2129
2130 ADDOP_O(c, LOAD_CONST, level, consts);
2131 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2133 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2134
2135 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002136 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002137 if (!r)
2138 return r;
2139 }
2140 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002142 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2143 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002145 tmp = PyUnicode_FromUnicode(base,
2146 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002147 r = compiler_nameop(c, tmp, Store);
2148 if (dot) {
2149 Py_DECREF(tmp);
2150 }
2151 if (!r)
2152 return r;
2153 }
2154 }
2155 return 1;
2156}
2157
2158static int
2159compiler_from_import(struct compiler *c, stmt_ty s)
2160{
2161 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162
2163 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002164 PyObject *level;
2165
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166 if (!names)
2167 return 0;
2168
Christian Heimes217cfd12007-12-02 14:31:20 +00002169 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002170 if (!level) {
2171 Py_DECREF(names);
2172 return 0;
2173 }
2174
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175 /* build up the names */
2176 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002177 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 Py_INCREF(alias->name);
2179 PyTuple_SET_ITEM(names, i, alias->name);
2180 }
2181
2182 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002183 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2184 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002185 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 Py_DECREF(names);
2187 return compiler_error(c,
2188 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002189 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190
2191 }
2192 }
2193
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002194 ADDOP_O(c, LOAD_CONST, level, consts);
2195 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002197 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2199 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002200 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201 identifier store_name;
2202
Martin v. Löwis5b222132007-06-10 09:51:05 +00002203 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002204 assert(n == 1);
2205 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002206 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002207 }
2208
2209 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2210 store_name = alias->name;
2211 if (alias->asname)
2212 store_name = alias->asname;
2213
2214 if (!compiler_nameop(c, store_name, Store)) {
2215 Py_DECREF(names);
2216 return 0;
2217 }
2218 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002219 /* remove imported module */
2220 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 return 1;
2222}
2223
2224static int
2225compiler_assert(struct compiler *c, stmt_ty s)
2226{
2227 static PyObject *assertion_error = NULL;
2228 basicblock *end;
2229
2230 if (Py_OptimizeFlag)
2231 return 1;
2232 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002233 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 if (assertion_error == NULL)
2235 return 0;
2236 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002237 if (s->v.Assert.test->kind == Tuple_kind &&
2238 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2239 const char* msg =
2240 "assertion is always true, perhaps remove parentheses?";
2241 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2242 c->u->u_lineno, NULL, NULL) == -1)
2243 return 0;
2244 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 VISIT(c, expr, s->v.Assert.test);
2246 end = compiler_new_block(c);
2247 if (end == NULL)
2248 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002249 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2251 if (s->v.Assert.msg) {
2252 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002253 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 }
Collin Winter828f04a2007-08-31 00:04:24 +00002255 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002256 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257 return 1;
2258}
2259
2260static int
2261compiler_visit_stmt(struct compiler *c, stmt_ty s)
2262{
2263 int i, n;
2264
Thomas Wouters89f507f2006-12-13 04:49:30 +00002265 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002267 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002268
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002270 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002272 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002274 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275 if (c->u->u_ste->ste_type != FunctionBlock)
2276 return compiler_error(c, "'return' outside function");
2277 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 VISIT(c, expr, s->v.Return.value);
2279 }
2280 else
2281 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2282 ADDOP(c, RETURN_VALUE);
2283 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002284 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285 VISIT_SEQ(c, expr, s->v.Delete.targets)
2286 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002287 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 n = asdl_seq_LEN(s->v.Assign.targets);
2289 VISIT(c, expr, s->v.Assign.value);
2290 for (i = 0; i < n; i++) {
2291 if (i < n - 1)
2292 ADDOP(c, DUP_TOP);
2293 VISIT(c, expr,
2294 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2295 }
2296 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002297 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002299 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002301 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002303 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002305 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002307 if (s->v.Raise.exc) {
2308 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002310 if (s->v.Raise.cause) {
2311 VISIT(c, expr, s->v.Raise.cause);
2312 n++;
2313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 }
2315 ADDOP_I(c, RAISE_VARARGS, n);
2316 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002317 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002321 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002323 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002325 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002326 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002327 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002328 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002330 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002332 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 ADDOP(c, PRINT_EXPR);
2334 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002335 else if (s->v.Expr.value->kind != Str_kind &&
2336 s->v.Expr.value->kind != Num_kind) {
2337 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338 ADDOP(c, POP_TOP);
2339 }
2340 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002341 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002343 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002344 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 return compiler_error(c, "'break' outside loop");
2346 ADDOP(c, BREAK_LOOP);
2347 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002348 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002350 case With_kind:
2351 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352 }
2353 return 1;
2354}
2355
2356static int
2357unaryop(unaryop_ty op)
2358{
2359 switch (op) {
2360 case Invert:
2361 return UNARY_INVERT;
2362 case Not:
2363 return UNARY_NOT;
2364 case UAdd:
2365 return UNARY_POSITIVE;
2366 case USub:
2367 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002368 default:
2369 PyErr_Format(PyExc_SystemError,
2370 "unary op %d should not be possible", op);
2371 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002373}
2374
2375static int
2376binop(struct compiler *c, operator_ty op)
2377{
2378 switch (op) {
2379 case Add:
2380 return BINARY_ADD;
2381 case Sub:
2382 return BINARY_SUBTRACT;
2383 case Mult:
2384 return BINARY_MULTIPLY;
2385 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002386 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387 case Mod:
2388 return BINARY_MODULO;
2389 case Pow:
2390 return BINARY_POWER;
2391 case LShift:
2392 return BINARY_LSHIFT;
2393 case RShift:
2394 return BINARY_RSHIFT;
2395 case BitOr:
2396 return BINARY_OR;
2397 case BitXor:
2398 return BINARY_XOR;
2399 case BitAnd:
2400 return BINARY_AND;
2401 case FloorDiv:
2402 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002403 default:
2404 PyErr_Format(PyExc_SystemError,
2405 "binary op %d should not be possible", op);
2406 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408}
2409
2410static int
2411cmpop(cmpop_ty op)
2412{
2413 switch (op) {
2414 case Eq:
2415 return PyCmp_EQ;
2416 case NotEq:
2417 return PyCmp_NE;
2418 case Lt:
2419 return PyCmp_LT;
2420 case LtE:
2421 return PyCmp_LE;
2422 case Gt:
2423 return PyCmp_GT;
2424 case GtE:
2425 return PyCmp_GE;
2426 case Is:
2427 return PyCmp_IS;
2428 case IsNot:
2429 return PyCmp_IS_NOT;
2430 case In:
2431 return PyCmp_IN;
2432 case NotIn:
2433 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002434 default:
2435 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437}
2438
2439static int
2440inplace_binop(struct compiler *c, operator_ty op)
2441{
2442 switch (op) {
2443 case Add:
2444 return INPLACE_ADD;
2445 case Sub:
2446 return INPLACE_SUBTRACT;
2447 case Mult:
2448 return INPLACE_MULTIPLY;
2449 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002450 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451 case Mod:
2452 return INPLACE_MODULO;
2453 case Pow:
2454 return INPLACE_POWER;
2455 case LShift:
2456 return INPLACE_LSHIFT;
2457 case RShift:
2458 return INPLACE_RSHIFT;
2459 case BitOr:
2460 return INPLACE_OR;
2461 case BitXor:
2462 return INPLACE_XOR;
2463 case BitAnd:
2464 return INPLACE_AND;
2465 case FloorDiv:
2466 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002467 default:
2468 PyErr_Format(PyExc_SystemError,
2469 "inplace binary op %d should not be possible", op);
2470 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472}
2473
2474static int
2475compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2476{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002477 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2479
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002480 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002481 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482 /* XXX AugStore isn't used anywhere! */
2483
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002484 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002485 if (!mangled)
2486 return 0;
2487
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 op = 0;
2489 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002490 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 switch (scope) {
2492 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002493 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494 optype = OP_DEREF;
2495 break;
2496 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002497 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498 optype = OP_DEREF;
2499 break;
2500 case LOCAL:
2501 if (c->u->u_ste->ste_type == FunctionBlock)
2502 optype = OP_FAST;
2503 break;
2504 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002505 if (c->u->u_ste->ste_type == FunctionBlock &&
2506 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 optype = OP_GLOBAL;
2508 break;
2509 case GLOBAL_EXPLICIT:
2510 optype = OP_GLOBAL;
2511 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002512 default:
2513 /* scope can be 0 */
2514 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515 }
2516
2517 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002518 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519
2520 switch (optype) {
2521 case OP_DEREF:
2522 switch (ctx) {
2523 case Load: op = LOAD_DEREF; break;
2524 case Store: op = STORE_DEREF; break;
2525 case AugLoad:
2526 case AugStore:
2527 break;
2528 case Del:
2529 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002530 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002532 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002533 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002536 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002537 PyErr_SetString(PyExc_SystemError,
2538 "param invalid for deref variable");
2539 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 }
2541 break;
2542 case OP_FAST:
2543 switch (ctx) {
2544 case Load: op = LOAD_FAST; break;
2545 case Store: op = STORE_FAST; break;
2546 case Del: op = DELETE_FAST; break;
2547 case AugLoad:
2548 case AugStore:
2549 break;
2550 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002551 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002552 PyErr_SetString(PyExc_SystemError,
2553 "param invalid for local variable");
2554 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002555 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002556 ADDOP_O(c, op, mangled, varnames);
2557 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558 return 1;
2559 case OP_GLOBAL:
2560 switch (ctx) {
2561 case Load: op = LOAD_GLOBAL; break;
2562 case Store: op = STORE_GLOBAL; break;
2563 case Del: op = DELETE_GLOBAL; break;
2564 case AugLoad:
2565 case AugStore:
2566 break;
2567 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002568 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002569 PyErr_SetString(PyExc_SystemError,
2570 "param invalid for global variable");
2571 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572 }
2573 break;
2574 case OP_NAME:
2575 switch (ctx) {
2576 case Load: op = LOAD_NAME; break;
2577 case Store: op = STORE_NAME; break;
2578 case Del: op = DELETE_NAME; break;
2579 case AugLoad:
2580 case AugStore:
2581 break;
2582 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002583 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002584 PyErr_SetString(PyExc_SystemError,
2585 "param invalid for name variable");
2586 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587 }
2588 break;
2589 }
2590
2591 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002592 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002593 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002594 if (arg < 0)
2595 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002596 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597}
2598
2599static int
2600compiler_boolop(struct compiler *c, expr_ty e)
2601{
2602 basicblock *end;
2603 int jumpi, i, n;
2604 asdl_seq *s;
2605
2606 assert(e->kind == BoolOp_kind);
2607 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002608 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002610 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002612 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613 return 0;
2614 s = e->v.BoolOp.values;
2615 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002616 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002618 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002619 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002621 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622 compiler_use_next_block(c, end);
2623 return 1;
2624}
2625
2626static int
2627compiler_list(struct compiler *c, expr_ty e)
2628{
2629 int n = asdl_seq_LEN(e->v.List.elts);
2630 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002631 int i, seen_star = 0;
2632 for (i = 0; i < n; i++) {
2633 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2634 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002635 if ((i >= (1 << 8)) ||
2636 (n-i-1 >= (INT_MAX >> 8)))
2637 return compiler_error(c,
2638 "too many expressions in "
2639 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002640 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2641 seen_star = 1;
2642 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2643 } else if (elt->kind == Starred_kind) {
2644 return compiler_error(c,
2645 "two starred expressions in assignment");
2646 }
2647 }
2648 if (!seen_star) {
2649 ADDOP_I(c, UNPACK_SEQUENCE, n);
2650 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651 }
2652 VISIT_SEQ(c, expr, e->v.List.elts);
2653 if (e->v.List.ctx == Load) {
2654 ADDOP_I(c, BUILD_LIST, n);
2655 }
2656 return 1;
2657}
2658
2659static int
2660compiler_tuple(struct compiler *c, expr_ty e)
2661{
2662 int n = asdl_seq_LEN(e->v.Tuple.elts);
2663 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002664 int i, seen_star = 0;
2665 for (i = 0; i < n; i++) {
2666 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2667 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002668 if ((i >= (1 << 8)) ||
2669 (n-i-1 >= (INT_MAX >> 8)))
2670 return compiler_error(c,
2671 "too many expressions in "
2672 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002673 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2674 seen_star = 1;
2675 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2676 } else if (elt->kind == Starred_kind) {
2677 return compiler_error(c,
2678 "two starred expressions in assignment");
2679 }
2680 }
2681 if (!seen_star) {
2682 ADDOP_I(c, UNPACK_SEQUENCE, n);
2683 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 }
2685 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2686 if (e->v.Tuple.ctx == Load) {
2687 ADDOP_I(c, BUILD_TUPLE, n);
2688 }
2689 return 1;
2690}
2691
2692static int
2693compiler_compare(struct compiler *c, expr_ty e)
2694{
2695 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002696 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697
2698 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2699 VISIT(c, expr, e->v.Compare.left);
2700 n = asdl_seq_LEN(e->v.Compare.ops);
2701 assert(n > 0);
2702 if (n > 1) {
2703 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 if (cleanup == NULL)
2705 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002706 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002707 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 }
2709 for (i = 1; i < n; i++) {
2710 ADDOP(c, DUP_TOP);
2711 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002713 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002714 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002715 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002718 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002719 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002721 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002723 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 if (n > 1) {
2725 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002726 if (end == NULL)
2727 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728 ADDOP_JREL(c, JUMP_FORWARD, end);
2729 compiler_use_next_block(c, cleanup);
2730 ADDOP(c, ROT_TWO);
2731 ADDOP(c, POP_TOP);
2732 compiler_use_next_block(c, end);
2733 }
2734 return 1;
2735}
2736
2737static int
2738compiler_call(struct compiler *c, expr_ty e)
2739{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002741 return compiler_call_helper(c, 0,
2742 e->v.Call.args,
2743 e->v.Call.keywords,
2744 e->v.Call.starargs,
2745 e->v.Call.kwargs);
2746}
2747
2748/* shared code between compiler_call and compiler_class */
2749static int
2750compiler_call_helper(struct compiler *c,
2751 int n, /* Args already pushed */
2752 asdl_seq *args,
2753 asdl_seq *keywords,
2754 expr_ty starargs,
2755 expr_ty kwargs)
2756{
2757 int code = 0;
2758
2759 n += asdl_seq_LEN(args);
2760 VISIT_SEQ(c, expr, args);
2761 if (keywords) {
2762 VISIT_SEQ(c, keyword, keywords);
2763 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002764 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002765 if (starargs) {
2766 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767 code |= 1;
2768 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002769 if (kwargs) {
2770 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771 code |= 2;
2772 }
2773 switch (code) {
2774 case 0:
2775 ADDOP_I(c, CALL_FUNCTION, n);
2776 break;
2777 case 1:
2778 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2779 break;
2780 case 2:
2781 ADDOP_I(c, CALL_FUNCTION_KW, n);
2782 break;
2783 case 3:
2784 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2785 break;
2786 }
2787 return 1;
2788}
2789
Nick Coghlan650f0d02007-04-15 12:05:43 +00002790
2791/* List and set comprehensions and generator expressions work by creating a
2792 nested function to perform the actual iteration. This means that the
2793 iteration variables don't leak into the current scope.
2794 The defined function is called immediately following its definition, with the
2795 result of that call being the result of the expression.
2796 The LC/SC version returns the populated container, while the GE version is
2797 flagged in symtable.c as a generator, so it returns the generator object
2798 when the function is called.
2799 This code *knows* that the loop cannot contain break, continue, or return,
2800 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2801
2802 Possible cleanups:
2803 - iterate over the generator sequence instead of using recursion
2804*/
2805
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002806static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002807compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002808 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002809 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002810{
2811 /* generate code for the iterator, then each of the ifs,
2812 and then write to the element */
2813
Nick Coghlan650f0d02007-04-15 12:05:43 +00002814 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817
2818 start = compiler_new_block(c);
2819 skip = compiler_new_block(c);
2820 if_cleanup = compiler_new_block(c);
2821 anchor = compiler_new_block(c);
2822
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002823 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002824 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002826
Nick Coghlan650f0d02007-04-15 12:05:43 +00002827 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829 if (gen_index == 0) {
2830 /* Receive outermost iter as an implicit argument */
2831 c->u->u_argcount = 1;
2832 ADDOP_I(c, LOAD_FAST, 0);
2833 }
2834 else {
2835 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002836 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837 ADDOP(c, GET_ITER);
2838 }
2839 compiler_use_next_block(c, start);
2840 ADDOP_JREL(c, FOR_ITER, anchor);
2841 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002842 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002844 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002845 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002847 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002849 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002850 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002851 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002853 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002854 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002855 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002856 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002857 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858
Nick Coghlan650f0d02007-04-15 12:05:43 +00002859 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002860 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002861 /* comprehension specific code */
2862 switch (type) {
2863 case COMP_GENEXP:
2864 VISIT(c, expr, elt);
2865 ADDOP(c, YIELD_VALUE);
2866 ADDOP(c, POP_TOP);
2867 break;
2868 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002869 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002870 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002871 break;
2872 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002873 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002874 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002876 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002877 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002878 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002879 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002880 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002881 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002882 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002883 default:
2884 return 0;
2885 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886
2887 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002888 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002889 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2891 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892
2893 return 1;
2894}
2895
2896static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002897compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002898 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002899{
2900 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002901 expr_ty outermost_iter;
2902
2903 outermost_iter = ((comprehension_ty)
2904 asdl_seq_GET(generators, 0))->iter;
2905
2906 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2907 goto error;
2908
2909 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002910 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002911 switch (type) {
2912 case COMP_LISTCOMP:
2913 op = BUILD_LIST;
2914 break;
2915 case COMP_SETCOMP:
2916 op = BUILD_SET;
2917 break;
2918 case COMP_DICTCOMP:
2919 op = BUILD_MAP;
2920 break;
2921 default:
2922 PyErr_Format(PyExc_SystemError,
2923 "unknown comprehension type %d", type);
2924 goto error_in_scope;
2925 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002926
Guido van Rossum992d4a32007-07-11 13:09:30 +00002927 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002928 }
2929
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002930 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002931 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002932 goto error_in_scope;
2933
2934 if (type != COMP_GENEXP) {
2935 ADDOP(c, RETURN_VALUE);
2936 }
2937
2938 co = assemble(c, 1);
2939 compiler_exit_scope(c);
2940 if (co == NULL)
2941 goto error;
2942
2943 if (!compiler_make_closure(c, co, 0))
2944 goto error;
2945 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002946
2947 VISIT(c, expr, outermost_iter);
2948 ADDOP(c, GET_ITER);
2949 ADDOP_I(c, CALL_FUNCTION, 1);
2950 return 1;
2951error_in_scope:
2952 compiler_exit_scope(c);
2953error:
2954 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002955 return 0;
2956}
2957
2958static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959compiler_genexp(struct compiler *c, expr_ty e)
2960{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002961 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002962 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002963 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002964 if (!name)
2965 return 0;
2966 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002967 assert(e->kind == GeneratorExp_kind);
2968 return compiler_comprehension(c, e, COMP_GENEXP, name,
2969 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002970 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971}
2972
2973static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002974compiler_listcomp(struct compiler *c, expr_ty e)
2975{
2976 static identifier name;
2977 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002978 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002979 if (!name)
2980 return 0;
2981 }
2982 assert(e->kind == ListComp_kind);
2983 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2984 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002985 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002986}
2987
2988static int
2989compiler_setcomp(struct compiler *c, expr_ty e)
2990{
2991 static identifier name;
2992 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002993 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002994 if (!name)
2995 return 0;
2996 }
2997 assert(e->kind == SetComp_kind);
2998 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2999 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003000 e->v.SetComp.elt, NULL);
3001}
3002
3003
3004static int
3005compiler_dictcomp(struct compiler *c, expr_ty e)
3006{
3007 static identifier name;
3008 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003009 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003010 if (!name)
3011 return 0;
3012 }
3013 assert(e->kind == DictComp_kind);
3014 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3015 e->v.DictComp.generators,
3016 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003017}
3018
3019
3020static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021compiler_visit_keyword(struct compiler *c, keyword_ty k)
3022{
3023 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3024 VISIT(c, expr, k->value);
3025 return 1;
3026}
3027
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003028/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 whether they are true or false.
3030
3031 Return values: 1 for true, 0 for false, -1 for non-constant.
3032 */
3033
3034static int
3035expr_constant(expr_ty e)
3036{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003037 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003039 case Ellipsis_kind:
3040 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041 case Num_kind:
3042 return PyObject_IsTrue(e->v.Num.n);
3043 case Str_kind:
3044 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003045 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003046 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003047 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003048 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003049 if (strcmp(id, "True") == 0) return 1;
3050 if (strcmp(id, "False") == 0) return 0;
3051 if (strcmp(id, "None") == 0) return 0;
3052 if (strcmp(id, "__debug__") == 0)
3053 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003054 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 default:
3056 return -1;
3057 }
3058}
3059
Guido van Rossumc2e20742006-02-27 22:32:47 +00003060/*
3061 Implements the with statement from PEP 343.
3062
3063 The semantics outlined in that PEP are as follows:
3064
3065 with EXPR as VAR:
3066 BLOCK
3067
3068 It is implemented roughly as:
3069
Thomas Wouters477c8d52006-05-27 19:21:47 +00003070 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 exit = context.__exit__ # not calling it
3072 value = context.__enter__()
3073 try:
3074 VAR = value # if VAR present in the syntax
3075 BLOCK
3076 finally:
3077 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003078 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003080 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 exit(*exc)
3082 */
3083static int
3084compiler_with(struct compiler *c, stmt_ty s)
3085{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003086 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003087 basicblock *block, *finally;
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003088 identifier tmpvalue = NULL, tmpexit = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003089
3090 assert(s->kind == With_kind);
3091
Guido van Rossumc2e20742006-02-27 22:32:47 +00003092 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003093 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003094 if (!enter_attr)
3095 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003096 }
3097 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003098 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003099 if (!exit_attr)
3100 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003101 }
3102
3103 block = compiler_new_block(c);
3104 finally = compiler_new_block(c);
3105 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003106 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003107
Guido van Rossumc2e20742006-02-27 22:32:47 +00003108 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003109 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003110 We need to do this rather than preserving it on the stack
3111 because SETUP_FINALLY remembers the stack level.
3112 We need to do the assignment *inside* the try/finally
3113 so that context.__exit__() is called when the assignment
3114 fails. But we need to call context.__enter__() *before*
3115 the try/finally so that if it fails we won't call
3116 context.__exit__().
3117 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003118 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003119 if (tmpvalue == NULL)
3120 return 0;
3121 PyArena_AddPyObject(c->c_arena, tmpvalue);
3122 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003123 tmpexit = compiler_new_tmpname(c);
3124 if (tmpexit == NULL)
3125 return 0;
3126 PyArena_AddPyObject(c->c_arena, tmpexit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003127
Thomas Wouters477c8d52006-05-27 19:21:47 +00003128 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003129 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003130
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003131 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003132 ADDOP(c, DUP_TOP);
3133 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003134 if (!compiler_nameop(c, tmpexit, Store))
3135 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003136
3137 /* Call context.__enter__() */
3138 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3139 ADDOP_I(c, CALL_FUNCTION, 0);
3140
3141 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003142 /* Store it in tmpvalue */
3143 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003144 return 0;
3145 }
3146 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 /* Discard result from context.__enter__() */
3148 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003149 }
3150
3151 /* Start the try block */
3152 ADDOP_JREL(c, SETUP_FINALLY, finally);
3153
3154 compiler_use_next_block(c, block);
3155 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003157 }
3158
3159 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 /* Bind saved result of context.__enter__() to VAR */
3161 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003162 !compiler_nameop(c, tmpvalue, Del))
3163 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003165 }
3166
3167 /* BLOCK code */
3168 VISIT_SEQ(c, stmt, s->v.With.body);
3169
3170 /* End of try block; start the finally block */
3171 ADDOP(c, POP_BLOCK);
3172 compiler_pop_fblock(c, FINALLY_TRY, block);
3173
3174 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3175 compiler_use_next_block(c, finally);
3176 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003178
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003179 /* Finally block starts; context.__exit__ is on the stack under
3180 the exception or return information. Just issue our magic
3181 opcode. */
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003182 if (!compiler_nameop(c, tmpexit, Load) ||
3183 !compiler_nameop(c, tmpexit, Del))
3184 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003185 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003186
3187 /* Finally block ends. */
3188 ADDOP(c, END_FINALLY);
3189 compiler_pop_fblock(c, FINALLY_END, finally);
3190 return 1;
3191}
3192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193static int
3194compiler_visit_expr(struct compiler *c, expr_ty e)
3195{
3196 int i, n;
3197
Thomas Wouters89f507f2006-12-13 04:49:30 +00003198 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003199 set a new line number for the next instruction.
3200 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201 if (e->lineno > c->u->u_lineno) {
3202 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003203 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 }
3205 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003206 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003208 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209 VISIT(c, expr, e->v.BinOp.left);
3210 VISIT(c, expr, e->v.BinOp.right);
3211 ADDOP(c, binop(c, e->v.BinOp.op));
3212 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003213 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214 VISIT(c, expr, e->v.UnaryOp.operand);
3215 ADDOP(c, unaryop(e->v.UnaryOp.op));
3216 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003217 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003219 case IfExp_kind:
3220 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003223 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003225 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003226 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003227 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003228 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003229 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 }
3231 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003232 case Set_kind:
3233 n = asdl_seq_LEN(e->v.Set.elts);
3234 VISIT_SEQ(c, expr, e->v.Set.elts);
3235 ADDOP_I(c, BUILD_SET, n);
3236 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003237 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003239 case ListComp_kind:
3240 return compiler_listcomp(c, e);
3241 case SetComp_kind:
3242 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003243 case DictComp_kind:
3244 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245 case Yield_kind:
3246 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003247 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248 if (e->v.Yield.value) {
3249 VISIT(c, expr, e->v.Yield.value);
3250 }
3251 else {
3252 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3253 }
3254 ADDOP(c, YIELD_VALUE);
3255 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003256 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003258 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003260 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3262 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3265 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003266 case Bytes_kind:
3267 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003268 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003269 case Ellipsis_kind:
3270 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3271 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003273 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274 if (e->v.Attribute.ctx != AugStore)
3275 VISIT(c, expr, e->v.Attribute.value);
3276 switch (e->v.Attribute.ctx) {
3277 case AugLoad:
3278 ADDOP(c, DUP_TOP);
3279 /* Fall through to load */
3280 case Load:
3281 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3282 break;
3283 case AugStore:
3284 ADDOP(c, ROT_TWO);
3285 /* Fall through to save */
3286 case Store:
3287 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3288 break;
3289 case Del:
3290 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3291 break;
3292 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003293 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003294 PyErr_SetString(PyExc_SystemError,
3295 "param invalid in attribute expression");
3296 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297 }
3298 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003299 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 switch (e->v.Subscript.ctx) {
3301 case AugLoad:
3302 VISIT(c, expr, e->v.Subscript.value);
3303 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3304 break;
3305 case Load:
3306 VISIT(c, expr, e->v.Subscript.value);
3307 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3308 break;
3309 case AugStore:
3310 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3311 break;
3312 case Store:
3313 VISIT(c, expr, e->v.Subscript.value);
3314 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3315 break;
3316 case Del:
3317 VISIT(c, expr, e->v.Subscript.value);
3318 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3319 break;
3320 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003321 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003322 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003323 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003324 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 }
3326 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003327 case Starred_kind:
3328 switch (e->v.Starred.ctx) {
3329 case Store:
3330 /* In all legitimate cases, the Starred node was already replaced
3331 * by compiler_list/compiler_tuple. XXX: is that okay? */
3332 return compiler_error(c,
3333 "starred assignment target must be in a list or tuple");
3334 default:
3335 return compiler_error(c,
3336 "can use starred expression only as assignment target");
3337 }
3338 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003339 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3341 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003342 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003344 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345 return compiler_tuple(c, e);
3346 }
3347 return 1;
3348}
3349
3350static int
3351compiler_augassign(struct compiler *c, stmt_ty s)
3352{
3353 expr_ty e = s->v.AugAssign.target;
3354 expr_ty auge;
3355
3356 assert(s->kind == AugAssign_kind);
3357
3358 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003359 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003361 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003362 if (auge == NULL)
3363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364 VISIT(c, expr, auge);
3365 VISIT(c, expr, s->v.AugAssign.value);
3366 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3367 auge->v.Attribute.ctx = AugStore;
3368 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369 break;
3370 case Subscript_kind:
3371 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003372 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003373 if (auge == NULL)
3374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375 VISIT(c, expr, auge);
3376 VISIT(c, expr, s->v.AugAssign.value);
3377 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003378 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003379 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003380 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003382 if (!compiler_nameop(c, e->v.Name.id, Load))
3383 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 VISIT(c, expr, s->v.AugAssign.value);
3385 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3386 return compiler_nameop(c, e->v.Name.id, Store);
3387 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003388 PyErr_Format(PyExc_SystemError,
3389 "invalid node type (%d) for augmented assignment",
3390 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392 }
3393 return 1;
3394}
3395
3396static int
3397compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3398{
3399 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003400 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3401 PyErr_SetString(PyExc_SystemError,
3402 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003404 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405 f = &c->u->u_fblock[c->u->u_nfblocks++];
3406 f->fb_type = t;
3407 f->fb_block = b;
3408 return 1;
3409}
3410
3411static void
3412compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3413{
3414 struct compiler_unit *u = c->u;
3415 assert(u->u_nfblocks > 0);
3416 u->u_nfblocks--;
3417 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3418 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3419}
3420
Thomas Wouters89f507f2006-12-13 04:49:30 +00003421static int
3422compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003423 int i;
3424 struct compiler_unit *u = c->u;
3425 for (i = 0; i < u->u_nfblocks; ++i) {
3426 if (u->u_fblock[i].fb_type == LOOP)
3427 return 1;
3428 }
3429 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003430}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431/* Raises a SyntaxError and returns 0.
3432 If something goes wrong, a different exception may be raised.
3433*/
3434
3435static int
3436compiler_error(struct compiler *c, const char *errstr)
3437{
3438 PyObject *loc;
3439 PyObject *u = NULL, *v = NULL;
3440
3441 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3442 if (!loc) {
3443 Py_INCREF(Py_None);
3444 loc = Py_None;
3445 }
3446 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3447 Py_None, loc);
3448 if (!u)
3449 goto exit;
3450 v = Py_BuildValue("(zO)", errstr, u);
3451 if (!v)
3452 goto exit;
3453 PyErr_SetObject(PyExc_SyntaxError, v);
3454 exit:
3455 Py_DECREF(loc);
3456 Py_XDECREF(u);
3457 Py_XDECREF(v);
3458 return 0;
3459}
3460
3461static int
3462compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003463 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003464{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003465 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003467 /* XXX this code is duplicated */
3468 switch (ctx) {
3469 case AugLoad: /* fall through to Load */
3470 case Load: op = BINARY_SUBSCR; break;
3471 case AugStore:/* fall through to Store */
3472 case Store: op = STORE_SUBSCR; break;
3473 case Del: op = DELETE_SUBSCR; break;
3474 case Param:
3475 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003476 "invalid %s kind %d in subscript\n",
3477 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003478 return 0;
3479 }
3480 if (ctx == AugLoad) {
3481 ADDOP_I(c, DUP_TOPX, 2);
3482 }
3483 else if (ctx == AugStore) {
3484 ADDOP(c, ROT_THREE);
3485 }
3486 ADDOP(c, op);
3487 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488}
3489
3490static int
3491compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3492{
3493 int n = 2;
3494 assert(s->kind == Slice_kind);
3495
3496 /* only handles the cases where BUILD_SLICE is emitted */
3497 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003498 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499 }
3500 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003501 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003503
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003505 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506 }
3507 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003508 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509 }
3510
3511 if (s->v.Slice.step) {
3512 n++;
3513 VISIT(c, expr, s->v.Slice.step);
3514 }
3515 ADDOP_I(c, BUILD_SLICE, n);
3516 return 1;
3517}
3518
3519static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003520compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3521 expr_context_ty ctx)
3522{
3523 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 case Slice_kind:
3525 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526 case Index_kind:
3527 VISIT(c, expr, s->v.Index.value);
3528 break;
3529 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003530 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003531 PyErr_SetString(PyExc_SystemError,
3532 "extended slice invalid in nested slice");
3533 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 }
3535 return 1;
3536}
3537
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538static int
3539compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3540{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003541 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003543 case Index_kind:
3544 kindname = "index";
3545 if (ctx != AugStore) {
3546 VISIT(c, expr, s->v.Index.value);
3547 }
3548 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003550 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003551 if (ctx != AugStore) {
3552 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 return 0;
3554 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003555 break;
3556 case ExtSlice_kind:
3557 kindname = "extended slice";
3558 if (ctx != AugStore) {
3559 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3560 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003561 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003562 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003563 if (!compiler_visit_nested_slice(c, sub, ctx))
3564 return 0;
3565 }
3566 ADDOP_I(c, BUILD_TUPLE, n);
3567 }
3568 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003569 default:
3570 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003571 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003572 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003574 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575}
3576
Thomas Wouters89f507f2006-12-13 04:49:30 +00003577/* End of the compiler section, beginning of the assembler section */
3578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579/* do depth-first search of basic block graph, starting with block.
3580 post records the block indices in post-order.
3581
3582 XXX must handle implicit jumps from one block to next
3583*/
3584
Thomas Wouters89f507f2006-12-13 04:49:30 +00003585struct assembler {
3586 PyObject *a_bytecode; /* string containing bytecode */
3587 int a_offset; /* offset into bytecode */
3588 int a_nblocks; /* number of reachable blocks */
3589 basicblock **a_postorder; /* list of blocks in dfs postorder */
3590 PyObject *a_lnotab; /* string containing lnotab */
3591 int a_lnotab_off; /* offset into lnotab */
3592 int a_lineno; /* last lineno of emitted instruction */
3593 int a_lineno_off; /* bytecode offset of last lineno */
3594};
3595
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596static void
3597dfs(struct compiler *c, basicblock *b, struct assembler *a)
3598{
3599 int i;
3600 struct instr *instr = NULL;
3601
3602 if (b->b_seen)
3603 return;
3604 b->b_seen = 1;
3605 if (b->b_next != NULL)
3606 dfs(c, b->b_next, a);
3607 for (i = 0; i < b->b_iused; i++) {
3608 instr = &b->b_instr[i];
3609 if (instr->i_jrel || instr->i_jabs)
3610 dfs(c, instr->i_target, a);
3611 }
3612 a->a_postorder[a->a_nblocks++] = b;
3613}
3614
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003615static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3617{
3618 int i;
3619 struct instr *instr;
3620 if (b->b_seen || b->b_startdepth >= depth)
3621 return maxdepth;
3622 b->b_seen = 1;
3623 b->b_startdepth = depth;
3624 for (i = 0; i < b->b_iused; i++) {
3625 instr = &b->b_instr[i];
3626 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3627 if (depth > maxdepth)
3628 maxdepth = depth;
3629 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3630 if (instr->i_jrel || instr->i_jabs) {
3631 maxdepth = stackdepth_walk(c, instr->i_target,
3632 depth, maxdepth);
3633 if (instr->i_opcode == JUMP_ABSOLUTE ||
3634 instr->i_opcode == JUMP_FORWARD) {
3635 goto out; /* remaining code is dead */
3636 }
3637 }
3638 }
3639 if (b->b_next)
3640 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3641out:
3642 b->b_seen = 0;
3643 return maxdepth;
3644}
3645
3646/* Find the flow path that needs the largest stack. We assume that
3647 * cycles in the flow graph have no net effect on the stack depth.
3648 */
3649static int
3650stackdepth(struct compiler *c)
3651{
3652 basicblock *b, *entryblock;
3653 entryblock = NULL;
3654 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3655 b->b_seen = 0;
3656 b->b_startdepth = INT_MIN;
3657 entryblock = b;
3658 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003659 if (!entryblock)
3660 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661 return stackdepth_walk(c, entryblock, 0, 0);
3662}
3663
3664static int
3665assemble_init(struct assembler *a, int nblocks, int firstlineno)
3666{
3667 memset(a, 0, sizeof(struct assembler));
3668 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003669 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670 if (!a->a_bytecode)
3671 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003672 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673 if (!a->a_lnotab)
3674 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003675 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3676 PyErr_NoMemory();
3677 return 0;
3678 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003680 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003681 if (!a->a_postorder) {
3682 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003684 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685 return 1;
3686}
3687
3688static void
3689assemble_free(struct assembler *a)
3690{
3691 Py_XDECREF(a->a_bytecode);
3692 Py_XDECREF(a->a_lnotab);
3693 if (a->a_postorder)
3694 PyObject_Free(a->a_postorder);
3695}
3696
3697/* Return the size of a basic block in bytes. */
3698
3699static int
3700instrsize(struct instr *instr)
3701{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003702 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003703 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003704 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003705 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3706 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003707}
3708
3709static int
3710blocksize(basicblock *b)
3711{
3712 int i;
3713 int size = 0;
3714
3715 for (i = 0; i < b->b_iused; i++)
3716 size += instrsize(&b->b_instr[i]);
3717 return size;
3718}
3719
3720/* All about a_lnotab.
3721
3722c_lnotab is an array of unsigned bytes disguised as a Python string.
3723It is used to map bytecode offsets to source code line #s (when needed
3724for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003725
Tim Peters2a7f3842001-06-09 09:26:21 +00003726The array is conceptually a list of
3727 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003728pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003729
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003730 byte code offset source code line number
3731 0 1
3732 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003733 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003734 350 307
3735 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003736
3737The first trick is that these numbers aren't stored, only the increments
3738from one row to the next (this doesn't really work, but it's a start):
3739
3740 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3741
3742The second trick is that an unsigned byte can't hold negative values, or
3743values larger than 255, so (a) there's a deep assumption that byte code
3744offsets and their corresponding line #s both increase monotonically, and (b)
3745if at least one column jumps by more than 255 from one row to the next, more
3746than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003747from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003748part. A user of c_lnotab desiring to find the source line number
3749corresponding to a bytecode address A should do something like this
3750
3751 lineno = addr = 0
3752 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003753 addr += addr_incr
3754 if addr > A:
3755 return lineno
3756 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003757
3758In order for this to work, when the addr field increments by more than 255,
3759the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003760increment is < 256. So, in the example above, assemble_lnotab (it used
3761to be called com_set_lineno) should not (as was actually done until 2.2)
3762expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003763 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003764*/
3765
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003766static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003768{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769 int d_bytecode, d_lineno;
3770 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003771 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772
3773 d_bytecode = a->a_offset - a->a_lineno_off;
3774 d_lineno = i->i_lineno - a->a_lineno;
3775
3776 assert(d_bytecode >= 0);
3777 assert(d_lineno >= 0);
3778
Christian Heimes2202f872008-02-06 14:31:34 +00003779 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003780 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003781
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003782 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003783 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003785 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003787 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003789 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003791 else {
3792 PyErr_NoMemory();
3793 return 0;
3794 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003795 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003797 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003798 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003799 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003800 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801 *lnotab++ = 255;
3802 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003803 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 d_bytecode -= ncodes * 255;
3805 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003806 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807 assert(d_bytecode <= 255);
3808 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003809 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003811 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003813 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003815 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003816 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003817 else {
3818 PyErr_NoMemory();
3819 return 0;
3820 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003821 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003823 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003824 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003825 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003827 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003828 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003829 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003831 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003832 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833 d_lineno -= ncodes * 255;
3834 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003835 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003836
Christian Heimes72b710a2008-05-26 13:28:38 +00003837 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003839 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003840 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003841 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003842 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003843 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003845 a->a_lnotab_off += 2;
3846 if (d_bytecode) {
3847 *lnotab++ = d_bytecode;
3848 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003849 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003850 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851 *lnotab++ = 0;
3852 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003853 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 a->a_lineno = i->i_lineno;
3855 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003856 return 1;
3857}
3858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859/* assemble_emit()
3860 Extend the bytecode with a new instruction.
3861 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003862*/
3863
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003864static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003866{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003867 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003868 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003869 char *code;
3870
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003871 size = instrsize(i);
3872 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003874 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003875 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003877 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003879 if (len > PY_SSIZE_T_MAX / 2)
3880 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003881 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003882 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003883 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003884 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003886 if (size == 6) {
3887 assert(i->i_hasarg);
3888 *code++ = (char)EXTENDED_ARG;
3889 *code++ = ext & 0xff;
3890 *code++ = ext >> 8;
3891 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003892 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003894 if (i->i_hasarg) {
3895 assert(size == 3 || size == 6);
3896 *code++ = arg & 0xff;
3897 *code++ = arg >> 8;
3898 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003900}
3901
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003902static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003904{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003906 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003907 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003908
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 /* Compute the size of each block and fixup jump args.
3910 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003911start:
3912 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003914 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915 bsize = blocksize(b);
3916 b->b_offset = totsize;
3917 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003918 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003919 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3921 bsize = b->b_offset;
3922 for (i = 0; i < b->b_iused; i++) {
3923 struct instr *instr = &b->b_instr[i];
3924 /* Relative jumps are computed relative to
3925 the instruction pointer after fetching
3926 the jump instruction.
3927 */
3928 bsize += instrsize(instr);
3929 if (instr->i_jabs)
3930 instr->i_oparg = instr->i_target->b_offset;
3931 else if (instr->i_jrel) {
3932 int delta = instr->i_target->b_offset - bsize;
3933 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003934 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003935 else
3936 continue;
3937 if (instr->i_oparg > 0xffff)
3938 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003939 }
3940 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003941
3942 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003943 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003944 with a better solution.
3945
3946 In the meantime, should the goto be dropped in favor
3947 of a loop?
3948
3949 The issue is that in the first loop blocksize() is called
3950 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003951 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003952 i_oparg is calculated in the second loop above.
3953
3954 So we loop until we stop seeing new EXTENDED_ARGs.
3955 The only EXTENDED_ARGs that could be popping up are
3956 ones in jump instructions. So this should converge
3957 fairly quickly.
3958 */
3959 if (last_extended_arg_count != extended_arg_count) {
3960 last_extended_arg_count = extended_arg_count;
3961 goto start;
3962 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003963}
3964
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003965static PyObject *
3966dict_keys_inorder(PyObject *dict, int offset)
3967{
3968 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003969 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003970
3971 tuple = PyTuple_New(size);
3972 if (tuple == NULL)
3973 return NULL;
3974 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003975 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003976 /* The keys of the dictionary are tuples. (see compiler_add_o)
3977 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003978 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003979 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003980 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003981 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003982 PyTuple_SET_ITEM(tuple, i - offset, k);
3983 }
3984 return tuple;
3985}
3986
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003987static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003988compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003989{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003990 PySTEntryObject *ste = c->u->u_ste;
3991 int flags = 0, n;
3992 if (ste->ste_type != ModuleBlock)
3993 flags |= CO_NEWLOCALS;
3994 if (ste->ste_type == FunctionBlock) {
3995 if (!ste->ste_unoptimized)
3996 flags |= CO_OPTIMIZED;
3997 if (ste->ste_nested)
3998 flags |= CO_NESTED;
3999 if (ste->ste_generator)
4000 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00004001 if (ste->ste_varargs)
4002 flags |= CO_VARARGS;
4003 if (ste->ste_varkeywords)
4004 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004005 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004006
4007 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004008 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004009
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004010 n = PyDict_Size(c->u->u_freevars);
4011 if (n < 0)
4012 return -1;
4013 if (n == 0) {
4014 n = PyDict_Size(c->u->u_cellvars);
4015 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004016 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017 if (n == 0) {
4018 flags |= CO_NOFREE;
4019 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004020 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004021
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004022 return flags;
4023}
4024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025static PyCodeObject *
4026makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004027{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028 PyObject *tmp;
4029 PyCodeObject *co = NULL;
4030 PyObject *consts = NULL;
4031 PyObject *names = NULL;
4032 PyObject *varnames = NULL;
4033 PyObject *filename = NULL;
4034 PyObject *name = NULL;
4035 PyObject *freevars = NULL;
4036 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004037 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004038 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004039
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004040 tmp = dict_keys_inorder(c->u->u_consts, 0);
4041 if (!tmp)
4042 goto error;
4043 consts = PySequence_List(tmp); /* optimize_code requires a list */
4044 Py_DECREF(tmp);
4045
4046 names = dict_keys_inorder(c->u->u_names, 0);
4047 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4048 if (!consts || !names || !varnames)
4049 goto error;
4050
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004051 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4052 if (!cellvars)
4053 goto error;
4054 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4055 if (!freevars)
4056 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004057 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004058 if (!filename)
4059 goto error;
4060
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004061 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004062 flags = compute_code_flags(c);
4063 if (flags < 0)
4064 goto error;
4065
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004066 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067 if (!bytecode)
4068 goto error;
4069
4070 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4071 if (!tmp)
4072 goto error;
4073 Py_DECREF(consts);
4074 consts = tmp;
4075
Guido van Rossum4f72a782006-10-27 23:31:49 +00004076 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4077 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004078 bytecode, consts, names, varnames,
4079 freevars, cellvars,
4080 filename, c->u->u_name,
4081 c->u->u_firstlineno,
4082 a->a_lnotab);
4083 error:
4084 Py_XDECREF(consts);
4085 Py_XDECREF(names);
4086 Py_XDECREF(varnames);
4087 Py_XDECREF(filename);
4088 Py_XDECREF(name);
4089 Py_XDECREF(freevars);
4090 Py_XDECREF(cellvars);
4091 Py_XDECREF(bytecode);
4092 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004093}
4094
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004095
4096/* For debugging purposes only */
4097#if 0
4098static void
4099dump_instr(const struct instr *i)
4100{
4101 const char *jrel = i->i_jrel ? "jrel " : "";
4102 const char *jabs = i->i_jabs ? "jabs " : "";
4103 char arg[128];
4104
4105 *arg = '\0';
4106 if (i->i_hasarg)
4107 sprintf(arg, "arg: %d ", i->i_oparg);
4108
4109 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4110 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4111}
4112
4113static void
4114dump_basicblock(const basicblock *b)
4115{
4116 const char *seen = b->b_seen ? "seen " : "";
4117 const char *b_return = b->b_return ? "return " : "";
4118 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4119 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4120 if (b->b_instr) {
4121 int i;
4122 for (i = 0; i < b->b_iused; i++) {
4123 fprintf(stderr, " [%02d] ", i);
4124 dump_instr(b->b_instr + i);
4125 }
4126 }
4127}
4128#endif
4129
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130static PyCodeObject *
4131assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004132{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133 basicblock *b, *entryblock;
4134 struct assembler a;
4135 int i, j, nblocks;
4136 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 /* Make sure every block that falls off the end returns None.
4139 XXX NEXT_BLOCK() isn't quite right, because if the last
4140 block ends with a jump or return b_next shouldn't set.
4141 */
4142 if (!c->u->u_curblock->b_return) {
4143 NEXT_BLOCK(c);
4144 if (addNone)
4145 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4146 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004147 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004149 nblocks = 0;
4150 entryblock = NULL;
4151 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4152 nblocks++;
4153 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004154 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004155
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004156 /* Set firstlineno if it wasn't explicitly set. */
4157 if (!c->u->u_firstlineno) {
4158 if (entryblock && entryblock->b_instr)
4159 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4160 else
4161 c->u->u_firstlineno = 1;
4162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004163 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4164 goto error;
4165 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004168 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004169
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170 /* Emit code in reverse postorder from dfs. */
4171 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004172 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173 for (j = 0; j < b->b_iused; j++)
4174 if (!assemble_emit(&a, &b->b_instr[j]))
4175 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004176 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004177
Christian Heimes72b710a2008-05-26 13:28:38 +00004178 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004180 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004182
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183 co = makecode(c, &a);
4184 error:
4185 assemble_free(&a);
4186 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004187}