blob: 4ea2ee9afe3458e7a8d23bbd50574e1f1726ad24 [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.
Neal Norwitzf733a012006-10-29 18:30:10 +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
Jeremy Hylton819de6c2007-02-27 16:13:23 +000011 * this file.
Neal Norwitzf733a012006-10-29 18:30:10 +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
Neal Norwitzf733a012006-10-29 18:30:10 +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
Alexandre Vassalottib6465472010-01-11 22:36:12 +000042#define COMP_GENEXP 0
43#define COMP_SETCOMP 1
44#define COMP_DICTCOMP 2
45
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000047 unsigned i_jabs : 1;
48 unsigned i_jrel : 1;
49 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000057 /* Each basicblock in a compilation unit is linked via b_list in the
58 reverse order that the block are allocated. b_list points to the next
59 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060 struct basicblock_ *b_list;
61 /* number of instructions used */
62 int b_iused;
63 /* length of instruction array (b_instr) */
64 int b_ialloc;
65 /* pointer to an array of instructions, initially NULL */
66 struct instr *b_instr;
67 /* If b_next is non-NULL, it is a pointer to the next
68 block reached by normal control flow. */
69 struct basicblock_ *b_next;
70 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000071 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000072 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000073 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074 /* depth of stack upon entry of block, computed by stackdepth() */
75 int b_startdepth;
76 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000077 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078} basicblock;
79
80/* fblockinfo tracks the current frame block.
81
Jeremy Hyltone9357b22006-03-01 15:47:05 +000082A frame block is used to handle loops, try/except, and try/finally.
83It's called a frame block to distinguish it from a basic block in the
84compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085*/
86
87enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
88
89struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000090 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091 basicblock *fb_block;
92};
93
94/* The following items change on entry and exit of code blocks.
95 They must be saved and restored when returning to a block.
96*/
97struct compiler_unit {
98 PySTEntryObject *u_ste;
99
100 PyObject *u_name;
101 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000102 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103 the argument for opcodes that refer to those collections.
104 */
105 PyObject *u_consts; /* all constants */
106 PyObject *u_names; /* all names */
107 PyObject *u_varnames; /* local variables */
108 PyObject *u_cellvars; /* cell variables */
109 PyObject *u_freevars; /* free variables */
110
111 PyObject *u_private; /* for private name mangling */
112
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000113 int u_argcount; /* number of arguments for block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000114 /* Pointer to the most recently allocated block. By following b_list
115 members, you can reach all early allocated blocks. */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000116 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000117 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
119 int u_nfblocks;
120 struct fblockinfo u_fblock[CO_MAXBLOCKS];
121
122 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000123 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124 bool u_lineno_set; /* boolean to indicate whether instr
125 has been generated with current lineno */
126};
127
128/* This struct captures the global state of a compilation.
129
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000130The u pointer points to the current compilation unit, while units
131for enclosing blocks are stored in c_stack. The u and c_stack are
132managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133*/
134
135struct compiler {
136 const char *c_filename;
137 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000138 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139 PyCompilerFlags *c_flags;
140
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000141 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 struct compiler_unit *u; /* compiler state for current block */
145 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147};
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149static int compiler_enter_scope(struct compiler *, identifier, void *, int);
150static void compiler_free(struct compiler *);
151static basicblock *compiler_new_block(struct compiler *);
152static int compiler_next_instr(struct compiler *, basicblock *);
153static int compiler_addop(struct compiler *, int);
154static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
155static int compiler_addop_i(struct compiler *, int, int);
156static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157static basicblock *compiler_use_new_block(struct compiler *);
158static int compiler_error(struct compiler *, const char *);
159static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
160
161static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
162static int compiler_visit_stmt(struct compiler *, stmt_ty);
163static int compiler_visit_keyword(struct compiler *, keyword_ty);
164static int compiler_visit_expr(struct compiler *, expr_ty);
165static int compiler_augassign(struct compiler *, stmt_ty);
166static int compiler_visit_slice(struct compiler *, slice_ty,
167 expr_context_ty);
168
169static int compiler_push_fblock(struct compiler *, enum fblocktype,
170 basicblock *);
171static void compiler_pop_fblock(struct compiler *, enum fblocktype,
172 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000173/* Returns true if there is a loop on the fblock stack. */
174static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175
176static int inplace_binop(struct compiler *, operator_ty);
177static int expr_constant(expr_ty e);
178
Guido van Rossumc2e20742006-02-27 22:32:47 +0000179static int compiler_with(struct compiler *, stmt_ty);
180
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181static PyCodeObject *assemble(struct compiler *, int addNone);
182static PyObject *__doc__;
183
184PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000185_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000186{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187 /* Name mangling: __private becomes _classname__private.
188 This is independent from how the name is used. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000189 const char *p, *name = PyString_AsString(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000190 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191 size_t nlen, plen;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000192 if (privateobj == NULL || !PyString_Check(privateobj) ||
Neal Norwitz84167d02006-08-12 01:45:47 +0000193 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000194 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000196 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000197 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198 nlen = strlen(name);
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000199 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000200
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000201 The only time a name with a dot can occur is when
202 we are compiling an import statement that has a
203 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000204
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000205 TODO(jhylton): Decide whether we want to support
206 mangling of the module name, e.g. __M.X.
207 */
Jeremy Hylton37075c52007-02-27 01:01:59 +0000208 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000209 || strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000212 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 /* Strip leading underscores from class name */
214 while (*p == '_')
215 p++;
216 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 plen = strlen(p);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000221
222 assert(1 <= PY_SSIZE_T_MAX - nlen);
223 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
224
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000225 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 if (!ident)
227 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000229 buffer = PyString_AS_STRING(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000231 strncpy(buffer+1, p, plen);
232 strcpy(buffer+1+plen, name);
233 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000234}
235
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000236static int
237compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000238{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241 c->c_stack = PyList_New(0);
242 if (!c->c_stack)
243 return 0;
244
245 return 1;
246}
247
248PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000249PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000250 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251{
252 struct compiler c;
253 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000254 PyCompilerFlags local_flags;
255 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000257 if (!__doc__) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000258 __doc__ = PyString_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000259 if (!__doc__)
260 return NULL;
261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000262
263 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000264 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000266 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267 c.c_future = PyFuture_FromAST(mod, filename);
268 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000269 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000271 local_flags.cf_flags = 0;
272 flags = &local_flags;
273 }
274 merged = c.c_future->ff_features | flags->cf_flags;
275 c.c_future->ff_features = merged;
276 flags->cf_flags = merged;
277 c.c_flags = flags;
278 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279
280 c.c_st = PySymtable_Build(mod, filename, c.c_future);
281 if (c.c_st == NULL) {
282 if (!PyErr_Occurred())
283 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000284 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285 }
286
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287 co = compiler_mod(&c, mod);
288
Thomas Wouters1175c432006-02-27 22:49:54 +0000289 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000291 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292 return co;
293}
294
295PyCodeObject *
296PyNode_Compile(struct _node *n, const char *filename)
297{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000298 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000299 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000300 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000301 if (!arena)
302 return NULL;
303 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000304 if (mod)
305 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000306 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000307 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000308}
309
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000310static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000312{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313 if (c->c_st)
314 PySymtable_Free(c->c_st);
315 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000316 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318}
319
Guido van Rossum79f25d91997-04-29 20:08:16 +0000320static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000322{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000323 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000324 PyObject *v, *k;
325 PyObject *dict = PyDict_New();
326 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000328 n = PyList_Size(list);
329 for (i = 0; i < n; i++) {
330 v = PyInt_FromLong(i);
331 if (!v) {
332 Py_DECREF(dict);
333 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000334 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000335 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000336 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
338 Py_XDECREF(k);
339 Py_DECREF(v);
340 Py_DECREF(dict);
341 return NULL;
342 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000343 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000345 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000346 return dict;
347}
348
349/* Return new dict containing names from src that match scope(s).
350
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000351src is a symbol table dictionary. If the scope of a name matches
352either scope_type or flag is set, insert it into the new dict. The
353values are integers, starting at offset and increasing by one for
354each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355*/
356
357static PyObject *
358dictbytype(PyObject *src, int scope_type, int flag, int offset)
359{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000360 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361 PyObject *k, *v, *dest = PyDict_New();
362
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000363 assert(offset >= 0);
364 if (dest == NULL)
365 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000366
367 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 /* XXX this should probably be a macro in symtable.h */
369 assert(PyInt_Check(v));
370 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000372 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
373 PyObject *tuple, *item = PyInt_FromLong(i);
374 if (item == NULL) {
375 Py_DECREF(dest);
376 return NULL;
377 }
378 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000379 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000380 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
381 Py_DECREF(item);
382 Py_DECREF(dest);
383 Py_XDECREF(tuple);
384 return NULL;
385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000386 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000387 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
390 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000391}
392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393static void
394compiler_unit_check(struct compiler_unit *u)
395{
396 basicblock *block;
397 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Brett Cannona6c41bc2008-02-07 07:47:31 +0000398 assert((void *)block != (void *)0xcbcbcbcb);
399 assert((void *)block != (void *)0xfbfbfbfb);
400 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000401 if (block->b_instr != NULL) {
402 assert(block->b_ialloc > 0);
403 assert(block->b_iused > 0);
404 assert(block->b_ialloc >= block->b_iused);
405 }
406 else {
407 assert (block->b_iused == 0);
408 assert (block->b_ialloc == 0);
409 }
410 }
411}
412
413static void
414compiler_unit_free(struct compiler_unit *u)
415{
416 basicblock *b, *next;
417
418 compiler_unit_check(u);
419 b = u->u_blocks;
420 while (b != NULL) {
421 if (b->b_instr)
422 PyObject_Free((void *)b->b_instr);
423 next = b->b_list;
424 PyObject_Free((void *)b);
425 b = next;
426 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000427 Py_CLEAR(u->u_ste);
428 Py_CLEAR(u->u_name);
429 Py_CLEAR(u->u_consts);
430 Py_CLEAR(u->u_names);
431 Py_CLEAR(u->u_varnames);
432 Py_CLEAR(u->u_freevars);
433 Py_CLEAR(u->u_cellvars);
434 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435 PyObject_Free(u);
436}
437
438static int
439compiler_enter_scope(struct compiler *c, identifier name, void *key,
440 int lineno)
441{
442 struct compiler_unit *u;
443
Anthony Baxter7b782b62006-04-11 12:01:56 +0000444 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000445 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000446 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000447 PyErr_NoMemory();
448 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000449 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000450 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451 u->u_argcount = 0;
452 u->u_ste = PySymtable_Lookup(c->c_st, key);
453 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000454 compiler_unit_free(u);
455 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000456 }
457 Py_INCREF(name);
458 u->u_name = name;
459 u->u_varnames = list2dict(u->u_ste->ste_varnames);
460 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000461 if (!u->u_varnames || !u->u_cellvars) {
462 compiler_unit_free(u);
463 return 0;
464 }
465
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000467 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000468 if (!u->u_freevars) {
469 compiler_unit_free(u);
470 return 0;
471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000472
473 u->u_blocks = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474 u->u_nfblocks = 0;
475 u->u_firstlineno = lineno;
476 u->u_lineno = 0;
477 u->u_lineno_set = false;
478 u->u_consts = PyDict_New();
479 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000480 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481 return 0;
482 }
483 u->u_names = PyDict_New();
484 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000485 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000486 return 0;
487 }
488
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000489 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490
491 /* Push the old compiler_unit on the stack. */
492 if (c->u) {
493 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000494 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
495 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000496 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497 return 0;
498 }
499 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000500 u->u_private = c->u->u_private;
501 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502 }
503 c->u = u;
504
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000505 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000506 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507 return 0;
508
509 return 1;
510}
511
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000512static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513compiler_exit_scope(struct compiler *c)
514{
515 int n;
516 PyObject *wrapper;
517
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000518 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519 compiler_unit_free(c->u);
520 /* Restore c->u to the parent unit. */
521 n = PyList_GET_SIZE(c->c_stack) - 1;
522 if (n >= 0) {
523 wrapper = PyList_GET_ITEM(c->c_stack, n);
524 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000525 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000526 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000528 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529 compiler_unit_check(c->u);
530 }
531 else
532 c->u = NULL;
533
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534}
535
536/* Allocate a new block and return a pointer to it.
537 Returns NULL on error.
538*/
539
540static basicblock *
541compiler_new_block(struct compiler *c)
542{
543 basicblock *b;
544 struct compiler_unit *u;
545
546 u = c->u;
547 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000548 if (b == NULL) {
549 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000551 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000553 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554 b->b_list = u->u_blocks;
555 u->u_blocks = b;
556 return b;
557}
558
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559static basicblock *
560compiler_use_new_block(struct compiler *c)
561{
562 basicblock *block = compiler_new_block(c);
563 if (block == NULL)
564 return NULL;
565 c->u->u_curblock = block;
566 return block;
567}
568
569static basicblock *
570compiler_next_block(struct compiler *c)
571{
572 basicblock *block = compiler_new_block(c);
573 if (block == NULL)
574 return NULL;
575 c->u->u_curblock->b_next = block;
576 c->u->u_curblock = block;
577 return block;
578}
579
580static basicblock *
581compiler_use_next_block(struct compiler *c, basicblock *block)
582{
583 assert(block != NULL);
584 c->u->u_curblock->b_next = block;
585 c->u->u_curblock = block;
586 return block;
587}
588
589/* Returns the offset of the next instruction in the current block's
590 b_instr array. Resizes the b_instr as necessary.
591 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000592*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593
594static int
595compiler_next_instr(struct compiler *c, basicblock *b)
596{
597 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000598 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000599 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000600 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000601 if (b->b_instr == NULL) {
602 PyErr_NoMemory();
603 return -1;
604 }
605 b->b_ialloc = DEFAULT_BLOCK_SIZE;
606 memset((char *)b->b_instr, 0,
607 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000610 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 size_t oldsize, newsize;
612 oldsize = b->b_ialloc * sizeof(struct instr);
613 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000614
615 if (oldsize > (PY_SIZE_MAX >> 1)) {
616 PyErr_NoMemory();
617 return -1;
618 }
619
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000620 if (newsize == 0) {
621 PyErr_NoMemory();
622 return -1;
623 }
624 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000625 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000626 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000627 if (tmp == NULL) {
628 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000630 }
631 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
633 }
634 return b->b_iused++;
635}
636
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000637/* Set the i_lineno member of the instruction at offset off if the
638 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000639 already been set. If it has been set, the call has no effect.
640
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000641 The line number is reset in the following cases:
642 - when entering a new scope
643 - on each statement
644 - on each expression that start a new line
645 - before the "except" clause
646 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000647*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000648
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649static void
650compiler_set_lineno(struct compiler *c, int off)
651{
652 basicblock *b;
653 if (c->u->u_lineno_set)
654 return;
655 c->u->u_lineno_set = true;
656 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000657 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658}
659
660static int
661opcode_stack_effect(int opcode, int oparg)
662{
663 switch (opcode) {
664 case POP_TOP:
665 return -1;
666 case ROT_TWO:
667 case ROT_THREE:
668 return 0;
669 case DUP_TOP:
670 return 1;
671 case ROT_FOUR:
672 return 0;
673
674 case UNARY_POSITIVE:
675 case UNARY_NEGATIVE:
676 case UNARY_NOT:
677 case UNARY_CONVERT:
678 case UNARY_INVERT:
679 return 0;
680
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000681 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000682 case LIST_APPEND:
Antoine Pitroud0c35152008-12-17 00:38:28 +0000683 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000684
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000685 case MAP_ADD:
686 return -2;
687
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000688 case BINARY_POWER:
689 case BINARY_MULTIPLY:
690 case BINARY_DIVIDE:
691 case BINARY_MODULO:
692 case BINARY_ADD:
693 case BINARY_SUBTRACT:
694 case BINARY_SUBSCR:
695 case BINARY_FLOOR_DIVIDE:
696 case BINARY_TRUE_DIVIDE:
697 return -1;
698 case INPLACE_FLOOR_DIVIDE:
699 case INPLACE_TRUE_DIVIDE:
700 return -1;
701
702 case SLICE+0:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000703 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704 case SLICE+1:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705 return -1;
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000706 case SLICE+2:
707 return -1;
708 case SLICE+3:
709 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000710
711 case STORE_SLICE+0:
712 return -2;
713 case STORE_SLICE+1:
714 return -3;
715 case STORE_SLICE+2:
716 return -3;
717 case STORE_SLICE+3:
718 return -4;
719
720 case DELETE_SLICE+0:
721 return -1;
722 case DELETE_SLICE+1:
723 return -2;
724 case DELETE_SLICE+2:
725 return -2;
726 case DELETE_SLICE+3:
727 return -3;
728
729 case INPLACE_ADD:
730 case INPLACE_SUBTRACT:
731 case INPLACE_MULTIPLY:
732 case INPLACE_DIVIDE:
733 case INPLACE_MODULO:
734 return -1;
735 case STORE_SUBSCR:
736 return -3;
Raymond Hettingereffde122007-12-18 18:26:18 +0000737 case STORE_MAP:
738 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000739 case DELETE_SUBSCR:
740 return -2;
741
742 case BINARY_LSHIFT:
743 case BINARY_RSHIFT:
744 case BINARY_AND:
745 case BINARY_XOR:
746 case BINARY_OR:
747 return -1;
748 case INPLACE_POWER:
749 return -1;
750 case GET_ITER:
751 return 0;
752
753 case PRINT_EXPR:
754 return -1;
755 case PRINT_ITEM:
756 return -1;
757 case PRINT_NEWLINE:
758 return 0;
759 case PRINT_ITEM_TO:
760 return -2;
761 case PRINT_NEWLINE_TO:
762 return -1;
763 case INPLACE_LSHIFT:
764 case INPLACE_RSHIFT:
765 case INPLACE_AND:
766 case INPLACE_XOR:
767 case INPLACE_OR:
768 return -1;
769 case BREAK_LOOP:
770 return 0;
Benjamin Peterson1880d8b2009-05-25 13:13:44 +0000771 case SETUP_WITH:
Benjamin Peterson49a6b0e2009-05-25 20:12:57 +0000772 return 4;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000773 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000774 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775 case LOAD_LOCALS:
776 return 1;
777 case RETURN_VALUE:
778 return -1;
779 case IMPORT_STAR:
780 return -1;
781 case EXEC_STMT:
782 return -3;
783 case YIELD_VALUE:
784 return 0;
785
786 case POP_BLOCK:
787 return 0;
788 case END_FINALLY:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000789 return -3; /* or -1 or -2 if no exception occurred or
790 return/break/continue */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791 case BUILD_CLASS:
792 return -2;
793
794 case STORE_NAME:
795 return -1;
796 case DELETE_NAME:
797 return 0;
798 case UNPACK_SEQUENCE:
799 return oparg-1;
800 case FOR_ITER:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000801 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000802
803 case STORE_ATTR:
804 return -2;
805 case DELETE_ATTR:
806 return -1;
807 case STORE_GLOBAL:
808 return -1;
809 case DELETE_GLOBAL:
810 return 0;
811 case DUP_TOPX:
812 return oparg;
813 case LOAD_CONST:
814 return 1;
815 case LOAD_NAME:
816 return 1;
817 case BUILD_TUPLE:
818 case BUILD_LIST:
Alexandre Vassalottiee936a22010-01-09 23:35:54 +0000819 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000820 return 1-oparg;
821 case BUILD_MAP:
822 return 1;
823 case LOAD_ATTR:
824 return 0;
825 case COMPARE_OP:
826 return -1;
827 case IMPORT_NAME:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000828 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000829 case IMPORT_FROM:
830 return 1;
831
832 case JUMP_FORWARD:
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000833 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
834 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835 case JUMP_ABSOLUTE:
836 return 0;
837
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000838 case POP_JUMP_IF_FALSE:
839 case POP_JUMP_IF_TRUE:
840 return -1;
841
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842 case LOAD_GLOBAL:
843 return 1;
844
845 case CONTINUE_LOOP:
846 return 0;
847 case SETUP_LOOP:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848 case SETUP_EXCEPT:
849 case SETUP_FINALLY:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000850 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000851
852 case LOAD_FAST:
853 return 1;
854 case STORE_FAST:
855 return -1;
856 case DELETE_FAST:
857 return 0;
858
859 case RAISE_VARARGS:
860 return -oparg;
861#define NARGS(o) (((o) % 256) + 2*((o) / 256))
862 case CALL_FUNCTION:
863 return -NARGS(oparg);
864 case CALL_FUNCTION_VAR:
865 case CALL_FUNCTION_KW:
866 return -NARGS(oparg)-1;
867 case CALL_FUNCTION_VAR_KW:
868 return -NARGS(oparg)-2;
869#undef NARGS
870 case MAKE_FUNCTION:
871 return -oparg;
872 case BUILD_SLICE:
873 if (oparg == 3)
874 return -2;
875 else
876 return -1;
877
878 case MAKE_CLOSURE:
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +0000879 return -oparg-1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000880 case LOAD_CLOSURE:
881 return 1;
882 case LOAD_DEREF:
883 return 1;
884 case STORE_DEREF:
885 return -1;
886 default:
887 fprintf(stderr, "opcode = %d\n", opcode);
888 Py_FatalError("opcode_stack_effect()");
889
890 }
891 return 0; /* not reachable */
892}
893
894/* Add an opcode with no argument.
895 Returns 0 on failure, 1 on success.
896*/
897
898static int
899compiler_addop(struct compiler *c, int opcode)
900{
901 basicblock *b;
902 struct instr *i;
903 int off;
904 off = compiler_next_instr(c, c->u->u_curblock);
905 if (off < 0)
906 return 0;
907 b = c->u->u_curblock;
908 i = &b->b_instr[off];
909 i->i_opcode = opcode;
910 i->i_hasarg = 0;
911 if (opcode == RETURN_VALUE)
912 b->b_return = 1;
913 compiler_set_lineno(c, off);
914 return 1;
915}
916
917static int
918compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
919{
920 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000921 Py_ssize_t arg;
Mark Dickinson105be772008-01-31 22:17:37 +0000922 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000923
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000924 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000925 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
926 if (PyFloat_Check(o)) {
Mark Dickinson105be772008-01-31 22:17:37 +0000927 d = PyFloat_AS_DOUBLE(o);
Mark Dickinson105be772008-01-31 22:17:37 +0000928 /* all we need is to make the tuple different in either the 0.0
929 * or -0.0 case from all others, just to avoid the "coercion".
930 */
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000931 if (d == 0.0 && copysign(1.0, d) < 0.0)
Mark Dickinson105be772008-01-31 22:17:37 +0000932 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
933 else
934 t = PyTuple_Pack(2, o, o->ob_type);
935 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000936#ifndef WITHOUT_COMPLEX
Mark Dickinson105be772008-01-31 22:17:37 +0000937 else if (PyComplex_Check(o)) {
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000938 Py_complex z;
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000939 int real_negzero, imag_negzero;
940 /* For the complex case we must make complex(x, 0.)
941 different from complex(x, -0.) and complex(0., y)
942 different from complex(-0., y), for any x and y.
943 All four complex zeros must be distinguished.*/
Mark Dickinson105be772008-01-31 22:17:37 +0000944 z = PyComplex_AsCComplex(o);
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000945 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
946 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
947 if (real_negzero && imag_negzero) {
948 t = PyTuple_Pack(5, o, o->ob_type,
949 Py_None, Py_None, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000950 }
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000951 else if (imag_negzero) {
952 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000953 }
Mark Dickinsonccc690d2009-11-28 16:32:27 +0000954 else if (real_negzero) {
955 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000956 }
957 else {
958 t = PyTuple_Pack(2, o, o->ob_type);
959 }
960 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000961#endif /* WITHOUT_COMPLEX */
Mark Dickinson105be772008-01-31 22:17:37 +0000962 else {
963 t = PyTuple_Pack(2, o, o->ob_type);
Alex Martellid8672aa2007-08-22 21:14:17 +0000964 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000965 if (t == NULL)
Mark Dickinson105be772008-01-31 22:17:37 +0000966 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000967
968 v = PyDict_GetItem(dict, t);
969 if (!v) {
970 arg = PyDict_Size(dict);
971 v = PyInt_FromLong(arg);
972 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
984 arg = PyInt_AsLong(v);
985 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;
Jeremy Hylton12603c42006-04-01 16:18:02 +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
Neal Norwitzf733a012006-10-29 18:30:10 +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++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001139 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +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++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001149 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +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;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001175 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +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++)
Anthony Baxter7b782b62006-04-11 12:01:56 +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) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001195 module = PyString_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 if (!module)
1197 return NULL;
1198 }
Neal Norwitzed657552006-07-10 00:04:44 +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;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001211 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +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"
Amaury Forgeot d'Arc59ce0422009-01-17 20:18:59 +00001246 "symbols: %s\nlocals: %s\nglobals: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001247 PyString_AS_STRING(name),
1248 PyString_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;
Georg Brandl7784f122006-05-26 20:04:44 +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;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272 return PyInt_AS_LONG(v);
1273}
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) {
1303 printf("lookup %s in %s %d %d\n"
1304 "freevars of %s: %s\n",
1305 PyObject_REPR(name),
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001306 PyString_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307 reftype, arg,
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001308 PyString_AS_STRING(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309 PyObject_REPR(co->co_freevars));
1310 Py_FatalError("compiler_make_closure()");
1311 }
1312 ADDOP_I(c, LOAD_CLOSURE, arg);
1313 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001314 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001316 ADDOP_I(c, MAKE_CLOSURE, args);
1317 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318}
1319
1320static int
1321compiler_decorators(struct compiler *c, asdl_seq* decos)
1322{
1323 int i;
1324
1325 if (!decos)
1326 return 1;
1327
1328 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001329 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330 }
1331 return 1;
1332}
1333
1334static int
1335compiler_arguments(struct compiler *c, arguments_ty args)
1336{
1337 int i;
1338 int n = asdl_seq_LEN(args->args);
1339 /* Correctly handle nested argument lists */
1340 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001341 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 if (arg->kind == Tuple_kind) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001343 PyObject *id = PyString_FromFormat(".%d", i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 if (id == NULL) {
1345 return 0;
1346 }
1347 if (!compiler_nameop(c, id, Load)) {
1348 Py_DECREF(id);
1349 return 0;
1350 }
1351 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001352 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353 }
1354 }
1355 return 1;
1356}
1357
1358static int
1359compiler_function(struct compiler *c, stmt_ty s)
1360{
1361 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001362 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363 arguments_ty args = s->v.FunctionDef.args;
Christian Heimes5224d282008-02-23 15:01:05 +00001364 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001365 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366 int i, n, docstring;
1367
1368 assert(s->kind == FunctionDef_kind);
1369
1370 if (!compiler_decorators(c, decos))
1371 return 0;
1372 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001373 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001374 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1375 s->lineno))
1376 return 0;
1377
Anthony Baxter7b782b62006-04-11 12:01:56 +00001378 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001379 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001380 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001381 first_const = st->v.Expr.value->v.Str.s;
1382 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001383 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001384 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001387 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388 compiler_arguments(c, args);
1389
1390 c->u->u_argcount = asdl_seq_LEN(args->args);
1391 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001392 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001394 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1395 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396 }
1397 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001398 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399 if (co == NULL)
1400 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001402 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001403 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404
1405 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1406 ADDOP_I(c, CALL_FUNCTION, 1);
1407 }
1408
1409 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1410}
1411
1412static int
1413compiler_class(struct compiler *c, stmt_ty s)
1414{
Christian Heimes5224d282008-02-23 15:01:05 +00001415 int n, i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001417 PyObject *str;
Christian Heimes5224d282008-02-23 15:01:05 +00001418 asdl_seq* decos = s->v.ClassDef.decorator_list;
1419
1420 if (!compiler_decorators(c, decos))
1421 return 0;
1422
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423 /* push class name on stack, needed by BUILD_CLASS */
1424 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1425 /* push the tuple of base classes on the stack */
1426 n = asdl_seq_LEN(s->v.ClassDef.bases);
1427 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001428 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429 ADDOP_I(c, BUILD_TUPLE, n);
1430 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1431 s->lineno))
1432 return 0;
Amaury Forgeot d'Arc69b747b2008-03-28 20:30:50 +00001433 Py_XDECREF(c->u->u_private);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001434 c->u->u_private = s->v.ClassDef.name;
1435 Py_INCREF(c->u->u_private);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001436 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437 if (!str || !compiler_nameop(c, str, Load)) {
1438 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001439 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001441 }
1442
1443 Py_DECREF(str);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001444 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445 if (!str || !compiler_nameop(c, str, Store)) {
1446 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001447 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001449 }
1450 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001452 if (!compiler_body(c, s->v.ClassDef.body)) {
1453 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001457 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1458 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001460 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461 if (co == NULL)
1462 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001464 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001465 Py_DECREF(co);
1466
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467 ADDOP_I(c, CALL_FUNCTION, 0);
1468 ADDOP(c, BUILD_CLASS);
Christian Heimes5224d282008-02-23 15:01:05 +00001469 /* apply decorators */
1470 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1471 ADDOP_I(c, CALL_FUNCTION, 1);
1472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1474 return 0;
1475 return 1;
1476}
1477
1478static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001479compiler_ifexp(struct compiler *c, expr_ty e)
1480{
1481 basicblock *end, *next;
1482
1483 assert(e->kind == IfExp_kind);
1484 end = compiler_new_block(c);
1485 if (end == NULL)
1486 return 0;
1487 next = compiler_new_block(c);
1488 if (next == NULL)
1489 return 0;
1490 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001491 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001492 VISIT(c, expr, e->v.IfExp.body);
1493 ADDOP_JREL(c, JUMP_FORWARD, end);
1494 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001495 VISIT(c, expr, e->v.IfExp.orelse);
1496 compiler_use_next_block(c, end);
1497 return 1;
1498}
1499
1500static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501compiler_lambda(struct compiler *c, expr_ty e)
1502{
1503 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001504 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505 arguments_ty args = e->v.Lambda.args;
1506 assert(e->kind == Lambda_kind);
1507
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001508 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001509 name = PyString_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001510 if (!name)
1511 return 0;
1512 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513
1514 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001515 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1517 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001518
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001519 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520 compiler_arguments(c, args);
1521
1522 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001523 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson8d5934b2008-12-27 18:24:11 +00001524 if (c->u->u_ste->ste_generator) {
1525 ADDOP_IN_SCOPE(c, POP_TOP);
1526 }
1527 else {
1528 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1529 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001531 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532 if (co == NULL)
1533 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001535 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001536 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537
1538 return 1;
1539}
1540
1541static int
1542compiler_print(struct compiler *c, stmt_ty s)
1543{
1544 int i, n;
1545 bool dest;
1546
1547 assert(s->kind == Print_kind);
1548 n = asdl_seq_LEN(s->v.Print.values);
1549 dest = false;
1550 if (s->v.Print.dest) {
1551 VISIT(c, expr, s->v.Print.dest);
1552 dest = true;
1553 }
1554 for (i = 0; i < n; i++) {
1555 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1556 if (dest) {
1557 ADDOP(c, DUP_TOP);
1558 VISIT(c, expr, e);
1559 ADDOP(c, ROT_TWO);
1560 ADDOP(c, PRINT_ITEM_TO);
1561 }
1562 else {
1563 VISIT(c, expr, e);
1564 ADDOP(c, PRINT_ITEM);
1565 }
1566 }
1567 if (s->v.Print.nl) {
1568 if (dest)
1569 ADDOP(c, PRINT_NEWLINE_TO)
1570 else
1571 ADDOP(c, PRINT_NEWLINE)
1572 }
1573 else if (dest)
1574 ADDOP(c, POP_TOP);
1575 return 1;
1576}
1577
1578static int
1579compiler_if(struct compiler *c, stmt_ty s)
1580{
1581 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001582 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001583 assert(s->kind == If_kind);
1584 end = compiler_new_block(c);
1585 if (end == NULL)
1586 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001587
1588 constant = expr_constant(s->v.If.test);
1589 /* constant = 0: "if 0"
1590 * constant = 1: "if 1", "if 2", ...
1591 * constant = -1: rest */
1592 if (constant == 0) {
1593 if (s->v.If.orelse)
1594 VISIT_SEQ(c, stmt, s->v.If.orelse);
1595 } else if (constant == 1) {
1596 VISIT_SEQ(c, stmt, s->v.If.body);
1597 } else {
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001598 if (s->v.If.orelse) {
1599 next = compiler_new_block(c);
1600 if (next == NULL)
1601 return 0;
1602 }
1603 else
1604 next = end;
Georg Brandlddbaa662006-06-04 21:56:52 +00001605 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001606 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Georg Brandlddbaa662006-06-04 21:56:52 +00001607 VISIT_SEQ(c, stmt, s->v.If.body);
1608 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001609 if (s->v.If.orelse) {
1610 compiler_use_next_block(c, next);
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001611 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001612 }
Georg Brandlddbaa662006-06-04 21:56:52 +00001613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001614 compiler_use_next_block(c, end);
1615 return 1;
1616}
1617
1618static int
1619compiler_for(struct compiler *c, stmt_ty s)
1620{
1621 basicblock *start, *cleanup, *end;
1622
1623 start = compiler_new_block(c);
1624 cleanup = compiler_new_block(c);
1625 end = compiler_new_block(c);
1626 if (start == NULL || end == NULL || cleanup == NULL)
1627 return 0;
1628 ADDOP_JREL(c, SETUP_LOOP, end);
1629 if (!compiler_push_fblock(c, LOOP, start))
1630 return 0;
1631 VISIT(c, expr, s->v.For.iter);
1632 ADDOP(c, GET_ITER);
1633 compiler_use_next_block(c, start);
1634 ADDOP_JREL(c, FOR_ITER, cleanup);
1635 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001636 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1638 compiler_use_next_block(c, cleanup);
1639 ADDOP(c, POP_BLOCK);
1640 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001641 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001642 compiler_use_next_block(c, end);
1643 return 1;
1644}
1645
1646static int
1647compiler_while(struct compiler *c, stmt_ty s)
1648{
1649 basicblock *loop, *orelse, *end, *anchor = NULL;
1650 int constant = expr_constant(s->v.While.test);
1651
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001652 if (constant == 0) {
1653 if (s->v.While.orelse)
1654 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655 return 1;
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001656 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657 loop = compiler_new_block(c);
1658 end = compiler_new_block(c);
1659 if (constant == -1) {
1660 anchor = compiler_new_block(c);
1661 if (anchor == NULL)
1662 return 0;
1663 }
1664 if (loop == NULL || end == NULL)
1665 return 0;
1666 if (s->v.While.orelse) {
1667 orelse = compiler_new_block(c);
1668 if (orelse == NULL)
1669 return 0;
1670 }
1671 else
1672 orelse = NULL;
1673
1674 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001675 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676 if (!compiler_push_fblock(c, LOOP, loop))
1677 return 0;
1678 if (constant == -1) {
1679 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001680 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001682 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1684
1685 /* XXX should the two POP instructions be in a separate block
1686 if there is no else clause ?
1687 */
1688
1689 if (constant == -1) {
1690 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691 ADDOP(c, POP_BLOCK);
1692 }
1693 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001694 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001695 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 compiler_use_next_block(c, end);
1697
1698 return 1;
1699}
1700
1701static int
1702compiler_continue(struct compiler *c)
1703{
1704 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001705 static const char IN_FINALLY_ERROR_MSG[] =
1706 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001707 int i;
1708
1709 if (!c->u->u_nfblocks)
1710 return compiler_error(c, LOOP_ERROR_MSG);
1711 i = c->u->u_nfblocks - 1;
1712 switch (c->u->u_fblock[i].fb_type) {
1713 case LOOP:
1714 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1715 break;
1716 case EXCEPT:
1717 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001718 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1719 /* Prevent continue anywhere under a finally
1720 even if hidden in a sub-try or except. */
1721 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1722 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1723 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724 if (i == -1)
1725 return compiler_error(c, LOOP_ERROR_MSG);
1726 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1727 break;
1728 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001729 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001730 }
1731
1732 return 1;
1733}
1734
1735/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1736
1737 SETUP_FINALLY L
1738 <code for body>
1739 POP_BLOCK
1740 LOAD_CONST <None>
1741 L: <code for finalbody>
1742 END_FINALLY
1743
1744 The special instructions use the block stack. Each block
1745 stack entry contains the instruction that created it (here
1746 SETUP_FINALLY), the level of the value stack at the time the
1747 block stack entry was created, and a label (here L).
1748
1749 SETUP_FINALLY:
1750 Pushes the current value stack level and the label
1751 onto the block stack.
1752 POP_BLOCK:
1753 Pops en entry from the block stack, and pops the value
1754 stack until its level is the same as indicated on the
1755 block stack. (The label is ignored.)
1756 END_FINALLY:
1757 Pops a variable number of entries from the *value* stack
1758 and re-raises the exception they specify. The number of
1759 entries popped depends on the (pseudo) exception type.
1760
1761 The block stack is unwound when an exception is raised:
1762 when a SETUP_FINALLY entry is found, the exception is pushed
1763 onto the value stack (and the exception condition is cleared),
1764 and the interpreter jumps to the label gotten from the block
1765 stack.
1766*/
1767
1768static int
1769compiler_try_finally(struct compiler *c, stmt_ty s)
1770{
1771 basicblock *body, *end;
1772 body = compiler_new_block(c);
1773 end = compiler_new_block(c);
1774 if (body == NULL || end == NULL)
1775 return 0;
1776
1777 ADDOP_JREL(c, SETUP_FINALLY, end);
1778 compiler_use_next_block(c, body);
1779 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1780 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001781 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 ADDOP(c, POP_BLOCK);
1783 compiler_pop_fblock(c, FINALLY_TRY, body);
1784
1785 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1786 compiler_use_next_block(c, end);
1787 if (!compiler_push_fblock(c, FINALLY_END, end))
1788 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001789 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790 ADDOP(c, END_FINALLY);
1791 compiler_pop_fblock(c, FINALLY_END, end);
1792
1793 return 1;
1794}
1795
1796/*
1797 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1798 (The contents of the value stack is shown in [], with the top
1799 at the right; 'tb' is trace-back info, 'val' the exception's
1800 associated value, and 'exc' the exception.)
1801
1802 Value stack Label Instruction Argument
1803 [] SETUP_EXCEPT L1
1804 [] <code for S>
1805 [] POP_BLOCK
1806 [] JUMP_FORWARD L0
1807
1808 [tb, val, exc] L1: DUP )
1809 [tb, val, exc, exc] <evaluate E1> )
1810 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001811 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812 [tb, val, exc] POP
1813 [tb, val] <assign to V1> (or POP if no V1)
1814 [tb] POP
1815 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001816 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001818 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 .............................etc.......................
1820
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001821 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822
1823 [] L0: <next statement>
1824
1825 Of course, parts are not generated if Vi or Ei is not present.
1826*/
1827static int
1828compiler_try_except(struct compiler *c, stmt_ty s)
1829{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001830 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 int i, n;
1832
1833 body = compiler_new_block(c);
1834 except = compiler_new_block(c);
1835 orelse = compiler_new_block(c);
1836 end = compiler_new_block(c);
1837 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1838 return 0;
1839 ADDOP_JREL(c, SETUP_EXCEPT, except);
1840 compiler_use_next_block(c, body);
1841 if (!compiler_push_fblock(c, EXCEPT, body))
1842 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001843 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 ADDOP(c, POP_BLOCK);
1845 compiler_pop_fblock(c, EXCEPT, body);
1846 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1847 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1848 compiler_use_next_block(c, except);
1849 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001850 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851 s->v.TryExcept.handlers, i);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001852 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +00001854 c->u->u_lineno_set = false;
1855 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856 except = compiler_new_block(c);
1857 if (except == NULL)
1858 return 0;
Georg Brandla48f3ab2008-03-30 06:40:17 +00001859 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860 ADDOP(c, DUP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001861 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001863 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 }
1865 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001866 if (handler->v.ExceptHandler.name) {
1867 VISIT(c, expr, handler->v.ExceptHandler.name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868 }
1869 else {
1870 ADDOP(c, POP_TOP);
1871 }
1872 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001873 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874 ADDOP_JREL(c, JUMP_FORWARD, end);
1875 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876 }
1877 ADDOP(c, END_FINALLY);
1878 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001879 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 compiler_use_next_block(c, end);
1881 return 1;
1882}
1883
1884static int
1885compiler_import_as(struct compiler *c, identifier name, identifier asname)
1886{
1887 /* The IMPORT_NAME opcode was already generated. This function
1888 merely needs to bind the result to a name.
1889
1890 If there is a dot in name, we need to split it and emit a
1891 LOAD_ATTR for each name.
1892 */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001893 const char *src = PyString_AS_STRING(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894 const char *dot = strchr(src, '.');
1895 if (dot) {
1896 /* Consume the base module name to get the first attribute */
1897 src = dot + 1;
1898 while (dot) {
1899 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001900 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901 dot = strchr(src, '.');
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001902 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001904 if (!attr)
1905 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001907 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908 src = dot + 1;
1909 }
1910 }
1911 return compiler_nameop(c, asname, Store);
1912}
1913
1914static int
1915compiler_import(struct compiler *c, stmt_ty s)
1916{
1917 /* The Import node stores a module name like a.b.c as a single
1918 string. This is convenient for all cases except
1919 import a.b.c as d
1920 where we need to parse that string to extract the individual
1921 module names.
1922 XXX Perhaps change the representation to make this case simpler?
1923 */
1924 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001925
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001927 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001929 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930
Neal Norwitzcbce2802006-04-03 06:26:32 +00001931 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001932 level = PyInt_FromLong(0);
1933 else
1934 level = PyInt_FromLong(-1);
1935
1936 if (level == NULL)
1937 return 0;
1938
1939 ADDOP_O(c, LOAD_CONST, level, consts);
1940 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1942 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1943
1944 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001945 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001946 if (!r)
1947 return r;
1948 }
1949 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950 identifier tmp = alias->name;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001951 const char *base = PyString_AS_STRING(alias->name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952 char *dot = strchr(base, '.');
1953 if (dot)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001954 tmp = PyString_FromStringAndSize(base,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955 dot - base);
1956 r = compiler_nameop(c, tmp, Store);
1957 if (dot) {
1958 Py_DECREF(tmp);
1959 }
1960 if (!r)
1961 return r;
1962 }
1963 }
1964 return 1;
1965}
1966
1967static int
1968compiler_from_import(struct compiler *c, stmt_ty s)
1969{
1970 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971
1972 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001973 PyObject *level;
Benjamin Petersona72be3b2009-06-13 20:23:33 +00001974 static PyObject *empty_string;
1975
1976 if (!empty_string) {
1977 empty_string = PyString_FromString("");
1978 if (!empty_string)
1979 return 0;
1980 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001981
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 if (!names)
1983 return 0;
1984
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001985 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001986 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001987 level = PyInt_FromLong(-1);
1988 else
1989 level = PyInt_FromLong(s->v.ImportFrom.level);
1990
1991 if (!level) {
1992 Py_DECREF(names);
1993 return 0;
1994 }
1995
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996 /* build up the names */
1997 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001998 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 Py_INCREF(alias->name);
2000 PyTuple_SET_ITEM(names, i, alias->name);
2001 }
2002
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002003 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2004 !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
2005 Py_DECREF(level);
2006 Py_DECREF(names);
2007 return compiler_error(c, "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002008 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009 }
2010
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002011 ADDOP_O(c, LOAD_CONST, level, consts);
2012 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002014 Py_DECREF(names);
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002015 if (s->v.ImportFrom.module) {
2016 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2017 }
2018 else {
2019 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2020 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002022 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 identifier store_name;
2024
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002025 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026 assert(n == 1);
2027 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029 }
2030
2031 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2032 store_name = alias->name;
2033 if (alias->asname)
2034 store_name = alias->asname;
2035
2036 if (!compiler_nameop(c, store_name, Store)) {
2037 Py_DECREF(names);
2038 return 0;
2039 }
2040 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002041 /* remove imported module */
2042 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002043 return 1;
2044}
2045
2046static int
2047compiler_assert(struct compiler *c, stmt_ty s)
2048{
2049 static PyObject *assertion_error = NULL;
2050 basicblock *end;
2051
2052 if (Py_OptimizeFlag)
2053 return 1;
2054 if (assertion_error == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002055 assertion_error = PyString_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056 if (assertion_error == NULL)
2057 return 0;
2058 }
Neal Norwitz400aeda2008-03-15 22:03:18 +00002059 if (s->v.Assert.test->kind == Tuple_kind &&
2060 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2061 const char* msg =
2062 "assertion is always true, perhaps remove parentheses?";
2063 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2064 c->u->u_lineno, NULL, NULL) == -1)
2065 return 0;
2066 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 VISIT(c, expr, s->v.Assert.test);
2068 end = compiler_new_block(c);
2069 if (end == NULL)
2070 return 0;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002071 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2073 if (s->v.Assert.msg) {
2074 VISIT(c, expr, s->v.Assert.msg);
2075 ADDOP_I(c, RAISE_VARARGS, 2);
2076 }
2077 else {
2078 ADDOP_I(c, RAISE_VARARGS, 1);
2079 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002080 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081 return 1;
2082}
2083
2084static int
2085compiler_visit_stmt(struct compiler *c, stmt_ty s)
2086{
2087 int i, n;
2088
Neal Norwitzf733a012006-10-29 18:30:10 +00002089 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 c->u->u_lineno = s->lineno;
2091 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002092
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002094 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002096 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002098 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 if (c->u->u_ste->ste_type != FunctionBlock)
2100 return compiler_error(c, "'return' outside function");
2101 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 VISIT(c, expr, s->v.Return.value);
2103 }
2104 else
2105 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2106 ADDOP(c, RETURN_VALUE);
2107 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002108 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002109 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002111 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 n = asdl_seq_LEN(s->v.Assign.targets);
2113 VISIT(c, expr, s->v.Assign.value);
2114 for (i = 0; i < n; i++) {
2115 if (i < n - 1)
2116 ADDOP(c, DUP_TOP);
2117 VISIT(c, expr,
2118 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2119 }
2120 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002121 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002123 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002125 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002131 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 n = 0;
2133 if (s->v.Raise.type) {
2134 VISIT(c, expr, s->v.Raise.type);
2135 n++;
2136 if (s->v.Raise.inst) {
2137 VISIT(c, expr, s->v.Raise.inst);
2138 n++;
2139 if (s->v.Raise.tback) {
2140 VISIT(c, expr, s->v.Raise.tback);
2141 n++;
2142 }
2143 }
2144 }
2145 ADDOP_I(c, RAISE_VARARGS, n);
2146 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002147 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002149 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002151 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002153 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002155 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002156 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002157 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 VISIT(c, expr, s->v.Exec.body);
2159 if (s->v.Exec.globals) {
2160 VISIT(c, expr, s->v.Exec.globals);
2161 if (s->v.Exec.locals) {
2162 VISIT(c, expr, s->v.Exec.locals);
2163 } else {
2164 ADDOP(c, DUP_TOP);
2165 }
2166 } else {
2167 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2168 ADDOP(c, DUP_TOP);
2169 }
2170 ADDOP(c, EXEC_STMT);
2171 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002172 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002174 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002176 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177 ADDOP(c, PRINT_EXPR);
2178 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002179 else if (s->v.Expr.value->kind != Str_kind &&
2180 s->v.Expr.value->kind != Num_kind) {
2181 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182 ADDOP(c, POP_TOP);
2183 }
2184 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002185 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002187 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002188 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189 return compiler_error(c, "'break' outside loop");
2190 ADDOP(c, BREAK_LOOP);
2191 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002192 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002194 case With_kind:
2195 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 }
2197 return 1;
2198}
2199
2200static int
2201unaryop(unaryop_ty op)
2202{
2203 switch (op) {
2204 case Invert:
2205 return UNARY_INVERT;
2206 case Not:
2207 return UNARY_NOT;
2208 case UAdd:
2209 return UNARY_POSITIVE;
2210 case USub:
2211 return UNARY_NEGATIVE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002212 default:
2213 PyErr_Format(PyExc_SystemError,
2214 "unary op %d should not be possible", op);
2215 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002216 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217}
2218
2219static int
2220binop(struct compiler *c, operator_ty op)
2221{
2222 switch (op) {
2223 case Add:
2224 return BINARY_ADD;
2225 case Sub:
2226 return BINARY_SUBTRACT;
2227 case Mult:
2228 return BINARY_MULTIPLY;
2229 case Div:
2230 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2231 return BINARY_TRUE_DIVIDE;
2232 else
2233 return BINARY_DIVIDE;
2234 case Mod:
2235 return BINARY_MODULO;
2236 case Pow:
2237 return BINARY_POWER;
2238 case LShift:
2239 return BINARY_LSHIFT;
2240 case RShift:
2241 return BINARY_RSHIFT;
2242 case BitOr:
2243 return BINARY_OR;
2244 case BitXor:
2245 return BINARY_XOR;
2246 case BitAnd:
2247 return BINARY_AND;
2248 case FloorDiv:
2249 return BINARY_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002250 default:
2251 PyErr_Format(PyExc_SystemError,
2252 "binary op %d should not be possible", op);
2253 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255}
2256
2257static int
2258cmpop(cmpop_ty op)
2259{
2260 switch (op) {
2261 case Eq:
2262 return PyCmp_EQ;
2263 case NotEq:
2264 return PyCmp_NE;
2265 case Lt:
2266 return PyCmp_LT;
2267 case LtE:
2268 return PyCmp_LE;
2269 case Gt:
2270 return PyCmp_GT;
2271 case GtE:
2272 return PyCmp_GE;
2273 case Is:
2274 return PyCmp_IS;
2275 case IsNot:
2276 return PyCmp_IS_NOT;
2277 case In:
2278 return PyCmp_IN;
2279 case NotIn:
2280 return PyCmp_NOT_IN;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002281 default:
2282 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284}
2285
2286static int
2287inplace_binop(struct compiler *c, operator_ty op)
2288{
2289 switch (op) {
2290 case Add:
2291 return INPLACE_ADD;
2292 case Sub:
2293 return INPLACE_SUBTRACT;
2294 case Mult:
2295 return INPLACE_MULTIPLY;
2296 case Div:
2297 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2298 return INPLACE_TRUE_DIVIDE;
2299 else
2300 return INPLACE_DIVIDE;
2301 case Mod:
2302 return INPLACE_MODULO;
2303 case Pow:
2304 return INPLACE_POWER;
2305 case LShift:
2306 return INPLACE_LSHIFT;
2307 case RShift:
2308 return INPLACE_RSHIFT;
2309 case BitOr:
2310 return INPLACE_OR;
2311 case BitXor:
2312 return INPLACE_XOR;
2313 case BitAnd:
2314 return INPLACE_AND;
2315 case FloorDiv:
2316 return INPLACE_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002317 default:
2318 PyErr_Format(PyExc_SystemError,
2319 "inplace binary op %d should not be possible", op);
2320 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322}
2323
2324static int
2325compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2326{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002327 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2329
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002330 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002331 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332 /* XXX AugStore isn't used anywhere! */
2333
Neal Norwitz0031ff32008-02-25 01:45:37 +00002334 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002335 if (!mangled)
2336 return 0;
2337
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338 op = 0;
2339 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002340 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 switch (scope) {
2342 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002343 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344 optype = OP_DEREF;
2345 break;
2346 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002347 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348 optype = OP_DEREF;
2349 break;
2350 case LOCAL:
2351 if (c->u->u_ste->ste_type == FunctionBlock)
2352 optype = OP_FAST;
2353 break;
2354 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002355 if (c->u->u_ste->ste_type == FunctionBlock &&
2356 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 optype = OP_GLOBAL;
2358 break;
2359 case GLOBAL_EXPLICIT:
2360 optype = OP_GLOBAL;
2361 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002362 default:
2363 /* scope can be 0 */
2364 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365 }
2366
2367 /* XXX Leave assert here, but handle __doc__ and the like better */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002368 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369
2370 switch (optype) {
2371 case OP_DEREF:
2372 switch (ctx) {
2373 case Load: op = LOAD_DEREF; break;
2374 case Store: op = STORE_DEREF; break;
2375 case AugLoad:
2376 case AugStore:
2377 break;
2378 case Del:
2379 PyErr_Format(PyExc_SyntaxError,
2380 "can not delete variable '%s' referenced "
2381 "in nested scope",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002382 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002383 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002386 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002387 PyErr_SetString(PyExc_SystemError,
2388 "param invalid for deref variable");
2389 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390 }
2391 break;
2392 case OP_FAST:
2393 switch (ctx) {
2394 case Load: op = LOAD_FAST; break;
2395 case Store: op = STORE_FAST; break;
2396 case Del: op = DELETE_FAST; break;
2397 case AugLoad:
2398 case AugStore:
2399 break;
2400 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002401 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002402 PyErr_SetString(PyExc_SystemError,
2403 "param invalid for local variable");
2404 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002406 ADDOP_O(c, op, mangled, varnames);
2407 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408 return 1;
2409 case OP_GLOBAL:
2410 switch (ctx) {
2411 case Load: op = LOAD_GLOBAL; break;
2412 case Store: op = STORE_GLOBAL; break;
2413 case Del: op = DELETE_GLOBAL; break;
2414 case AugLoad:
2415 case AugStore:
2416 break;
2417 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002418 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002419 PyErr_SetString(PyExc_SystemError,
2420 "param invalid for global variable");
2421 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422 }
2423 break;
2424 case OP_NAME:
2425 switch (ctx) {
2426 case Load: op = LOAD_NAME; break;
2427 case Store: op = STORE_NAME; break;
2428 case Del: op = DELETE_NAME; break;
2429 case AugLoad:
2430 case AugStore:
2431 break;
2432 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002433 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002434 PyErr_SetString(PyExc_SystemError,
2435 "param invalid for name variable");
2436 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 }
2438 break;
2439 }
2440
2441 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002442 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002443 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002444 if (arg < 0)
2445 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002446 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447}
2448
2449static int
2450compiler_boolop(struct compiler *c, expr_ty e)
2451{
2452 basicblock *end;
2453 int jumpi, i, n;
2454 asdl_seq *s;
2455
2456 assert(e->kind == BoolOp_kind);
2457 if (e->v.BoolOp.op == And)
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002458 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459 else
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002460 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002462 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 return 0;
2464 s = e->v.BoolOp.values;
2465 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002466 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002468 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002469 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002471 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472 compiler_use_next_block(c, end);
2473 return 1;
2474}
2475
2476static int
2477compiler_list(struct compiler *c, expr_ty e)
2478{
2479 int n = asdl_seq_LEN(e->v.List.elts);
2480 if (e->v.List.ctx == Store) {
2481 ADDOP_I(c, UNPACK_SEQUENCE, n);
2482 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002483 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 if (e->v.List.ctx == Load) {
2485 ADDOP_I(c, BUILD_LIST, n);
2486 }
2487 return 1;
2488}
2489
2490static int
2491compiler_tuple(struct compiler *c, expr_ty e)
2492{
2493 int n = asdl_seq_LEN(e->v.Tuple.elts);
2494 if (e->v.Tuple.ctx == Store) {
2495 ADDOP_I(c, UNPACK_SEQUENCE, n);
2496 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002497 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498 if (e->v.Tuple.ctx == Load) {
2499 ADDOP_I(c, BUILD_TUPLE, n);
2500 }
2501 return 1;
2502}
2503
2504static int
2505compiler_compare(struct compiler *c, expr_ty e)
2506{
2507 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002508 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509
2510 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2511 VISIT(c, expr, e->v.Compare.left);
2512 n = asdl_seq_LEN(e->v.Compare.ops);
2513 assert(n > 0);
2514 if (n > 1) {
2515 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002516 if (cleanup == NULL)
2517 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002518 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002519 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520 }
2521 for (i = 1; i < n; i++) {
2522 ADDOP(c, DUP_TOP);
2523 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002525 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002526 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002527 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002528 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002530 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002531 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002533 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002535 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536 if (n > 1) {
2537 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002538 if (end == NULL)
2539 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 ADDOP_JREL(c, JUMP_FORWARD, end);
2541 compiler_use_next_block(c, cleanup);
2542 ADDOP(c, ROT_TWO);
2543 ADDOP(c, POP_TOP);
2544 compiler_use_next_block(c, end);
2545 }
2546 return 1;
2547}
2548
2549static int
2550compiler_call(struct compiler *c, expr_ty e)
2551{
2552 int n, code = 0;
2553
2554 VISIT(c, expr, e->v.Call.func);
2555 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002556 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002558 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2560 }
2561 if (e->v.Call.starargs) {
2562 VISIT(c, expr, e->v.Call.starargs);
2563 code |= 1;
2564 }
2565 if (e->v.Call.kwargs) {
2566 VISIT(c, expr, e->v.Call.kwargs);
2567 code |= 2;
2568 }
2569 switch (code) {
2570 case 0:
2571 ADDOP_I(c, CALL_FUNCTION, n);
2572 break;
2573 case 1:
2574 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2575 break;
2576 case 2:
2577 ADDOP_I(c, CALL_FUNCTION_KW, n);
2578 break;
2579 case 3:
2580 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2581 break;
2582 }
2583 return 1;
2584}
2585
2586static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002587compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
2588 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589{
2590 /* generate code for the iterator, then each of the ifs,
2591 and then write to the element */
2592
2593 comprehension_ty l;
2594 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002595 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596
2597 start = compiler_new_block(c);
2598 skip = compiler_new_block(c);
2599 if_cleanup = compiler_new_block(c);
2600 anchor = compiler_new_block(c);
2601
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002602 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2603 anchor == NULL)
2604 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002605
Anthony Baxter7b782b62006-04-11 12:01:56 +00002606 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607 VISIT(c, expr, l->iter);
2608 ADDOP(c, GET_ITER);
2609 compiler_use_next_block(c, start);
2610 ADDOP_JREL(c, FOR_ITER, anchor);
2611 NEXT_BLOCK(c);
2612 VISIT(c, expr, l->target);
2613
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 n = asdl_seq_LEN(l->ifs);
2616 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002617 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002619 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 }
2622
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002623 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitroud0c35152008-12-17 00:38:28 +00002624 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002627 /* only append after the last for generator */
2628 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002629 VISIT(c, expr, elt);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002630 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002631
2632 compiler_use_next_block(c, skip);
2633 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002634 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2636 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637
2638 return 1;
2639}
2640
2641static int
2642compiler_listcomp(struct compiler *c, expr_ty e)
2643{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644 assert(e->kind == ListComp_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 ADDOP_I(c, BUILD_LIST, 0);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002646 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2647 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648}
2649
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002650/* Dict and set comprehensions and generator expressions work by creating a
2651 nested function to perform the actual iteration. This means that the
2652 iteration variables don't leak into the current scope.
2653 The defined function is called immediately following its definition, with the
2654 result of that call being the result of the expression.
2655 The LC/SC version returns the populated container, while the GE version is
2656 flagged in symtable.c as a generator, so it returns the generator object
2657 when the function is called.
2658 This code *knows* that the loop cannot contain break, continue, or return,
2659 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2660
2661 Possible cleanups:
2662 - iterate over the generator sequence instead of using recursion
2663*/
2664
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665static int
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002666compiler_comprehension_generator(struct compiler *c,
2667 asdl_seq *generators, int gen_index,
2668 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669{
2670 /* generate code for the iterator, then each of the ifs,
2671 and then write to the element */
2672
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002673 comprehension_ty gen;
2674 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676
2677 start = compiler_new_block(c);
2678 skip = compiler_new_block(c);
2679 if_cleanup = compiler_new_block(c);
2680 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002682 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002683 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 return 0;
2685
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002686 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
2687
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 if (gen_index == 0) {
2689 /* Receive outermost iter as an implicit argument */
2690 c->u->u_argcount = 1;
2691 ADDOP_I(c, LOAD_FAST, 0);
2692 }
2693 else {
2694 /* Sub-iter - calculate on the fly */
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002695 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 ADDOP(c, GET_ITER);
2697 }
2698 compiler_use_next_block(c, start);
2699 ADDOP_JREL(c, FOR_ITER, anchor);
2700 NEXT_BLOCK(c);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002701 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002703 /* XXX this needs to be cleaned up...a lot! */
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002704 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 for (i = 0; i < n; i++) {
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002706 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002708 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 NEXT_BLOCK(c);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002710 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 if (++gen_index < asdl_seq_LEN(generators))
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002713 if (!compiler_comprehension_generator(c,
2714 generators, gen_index,
2715 elt, val, type))
2716 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002718 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 if (gen_index >= asdl_seq_LEN(generators)) {
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002720 /* comprehension specific code */
2721 switch (type) {
2722 case COMP_GENEXP:
2723 VISIT(c, expr, elt);
2724 ADDOP(c, YIELD_VALUE);
2725 ADDOP(c, POP_TOP);
2726 break;
2727 case COMP_SETCOMP:
2728 VISIT(c, expr, elt);
2729 ADDOP_I(c, SET_ADD, gen_index + 1);
2730 break;
2731 case COMP_DICTCOMP:
2732 /* With 'd[k] = v', v is evaluated before k, so we do
2733 the same. */
2734 VISIT(c, expr, val);
2735 VISIT(c, expr, elt);
2736 ADDOP_I(c, MAP_ADD, gen_index + 1);
2737 break;
2738 default:
2739 return 0;
2740 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741
2742 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002743 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002744 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2746 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747
2748 return 1;
2749}
2750
2751static int
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002752compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
2753 asdl_seq *generators, expr_ty elt, expr_ty val)
2754{
2755 PyCodeObject *co = NULL;
2756 expr_ty outermost_iter;
2757
2758 outermost_iter = ((comprehension_ty)
2759 asdl_seq_GET(generators, 0))->iter;
2760
2761 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2762 goto error;
2763
2764 if (type != COMP_GENEXP) {
2765 int op;
2766 switch (type) {
2767 case COMP_SETCOMP:
2768 op = BUILD_SET;
2769 break;
2770 case COMP_DICTCOMP:
2771 op = BUILD_MAP;
2772 break;
2773 default:
2774 PyErr_Format(PyExc_SystemError,
2775 "unknown comprehension type %d", type);
2776 goto error_in_scope;
2777 }
2778
2779 ADDOP_I(c, op, 0);
2780 }
2781
2782 if (!compiler_comprehension_generator(c, generators, 0, elt,
2783 val, type))
2784 goto error_in_scope;
2785
2786 if (type != COMP_GENEXP) {
2787 ADDOP(c, RETURN_VALUE);
2788 }
2789
2790 co = assemble(c, 1);
2791 compiler_exit_scope(c);
2792 if (co == NULL)
2793 goto error;
2794
2795 if (!compiler_make_closure(c, co, 0))
2796 goto error;
2797 Py_DECREF(co);
2798
2799 VISIT(c, expr, outermost_iter);
2800 ADDOP(c, GET_ITER);
2801 ADDOP_I(c, CALL_FUNCTION, 1);
2802 return 1;
2803error_in_scope:
2804 compiler_exit_scope(c);
2805error:
2806 Py_XDECREF(co);
2807 return 0;
2808}
2809
2810static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811compiler_genexp(struct compiler *c, expr_ty e)
2812{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002813 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002814 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002815 name = PyString_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002816 if (!name)
2817 return 0;
2818 }
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002819 assert(e->kind == GeneratorExp_kind);
2820 return compiler_comprehension(c, e, COMP_GENEXP, name,
2821 e->v.GeneratorExp.generators,
2822 e->v.GeneratorExp.elt, NULL);
2823}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002825static int
2826compiler_setcomp(struct compiler *c, expr_ty e)
2827{
2828 static identifier name;
2829 if (!name) {
2830 name = PyString_FromString("<setcomp>");
2831 if (!name)
2832 return 0;
2833 }
2834 assert(e->kind == SetComp_kind);
2835 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2836 e->v.SetComp.generators,
2837 e->v.SetComp.elt, NULL);
2838}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002840static int
2841compiler_dictcomp(struct compiler *c, expr_ty e)
2842{
2843 static identifier name;
2844 if (!name) {
2845 name = PyString_FromString("<dictcomp>");
2846 if (!name)
2847 return 0;
2848 }
2849 assert(e->kind == DictComp_kind);
2850 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2851 e->v.DictComp.generators,
2852 e->v.DictComp.key, e->v.DictComp.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853}
2854
2855static int
2856compiler_visit_keyword(struct compiler *c, keyword_ty k)
2857{
2858 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2859 VISIT(c, expr, k->value);
2860 return 1;
2861}
2862
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 whether they are true or false.
2865
2866 Return values: 1 for true, 0 for false, -1 for non-constant.
2867 */
2868
2869static int
2870expr_constant(expr_ty e)
2871{
2872 switch (e->kind) {
2873 case Num_kind:
2874 return PyObject_IsTrue(e->v.Num.n);
2875 case Str_kind:
2876 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002877 case Name_kind:
2878 /* __debug__ is not assignable, so we can optimize
2879 * it away in if and while statements */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002880 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002881 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002882 return ! Py_OptimizeFlag;
2883 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 default:
2885 return -1;
2886 }
2887}
2888
Guido van Rossumc2e20742006-02-27 22:32:47 +00002889/*
2890 Implements the with statement from PEP 343.
2891
2892 The semantics outlined in that PEP are as follows:
2893
2894 with EXPR as VAR:
2895 BLOCK
2896
2897 It is implemented roughly as:
2898
Guido van Rossumda5b7012006-05-02 19:47:52 +00002899 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002900 exit = context.__exit__ # not calling it
2901 value = context.__enter__()
2902 try:
2903 VAR = value # if VAR present in the syntax
2904 BLOCK
2905 finally:
2906 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002907 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002909 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002910 exit(*exc)
2911 */
2912static int
2913compiler_with(struct compiler *c, stmt_ty s)
2914{
Guido van Rossumc2e20742006-02-27 22:32:47 +00002915 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002916
2917 assert(s->kind == With_kind);
2918
Guido van Rossumc2e20742006-02-27 22:32:47 +00002919 block = compiler_new_block(c);
2920 finally = compiler_new_block(c);
2921 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002922 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002923
Guido van Rossumda5b7012006-05-02 19:47:52 +00002924 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002925 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002926 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002927
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002928 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002929 compiler_use_next_block(c, block);
Benjamin Peterson565d7852010-02-05 02:12:14 +00002930 /* Note that the block is actually called SETUP_WITH in ceval.c, but
2931 functions the same as SETUP_FINALLY except that exceptions are
2932 normalized. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002933 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002934 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002935 }
2936
2937 if (s->v.With.optional_vars) {
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002938 VISIT(c, expr, s->v.With.optional_vars);
2939 }
2940 else {
2941 /* Discard result from context.__enter__() */
2942 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002943 }
2944
2945 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002946 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002947
2948 /* End of try block; start the finally block */
2949 ADDOP(c, POP_BLOCK);
2950 compiler_pop_fblock(c, FINALLY_TRY, block);
2951
2952 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2953 compiler_use_next_block(c, finally);
2954 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002955 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002956
Nick Coghlan7af53be2008-03-07 14:13:28 +00002957 /* Finally block starts; context.__exit__ is on the stack under
2958 the exception or return information. Just issue our magic
2959 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002960 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002961
2962 /* Finally block ends. */
2963 ADDOP(c, END_FINALLY);
2964 compiler_pop_fblock(c, FINALLY_END, finally);
2965 return 1;
2966}
2967
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968static int
2969compiler_visit_expr(struct compiler *c, expr_ty e)
2970{
2971 int i, n;
2972
Neal Norwitzf733a012006-10-29 18:30:10 +00002973 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002974 set a new line number for the next instruction.
2975 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 if (e->lineno > c->u->u_lineno) {
2977 c->u->u_lineno = e->lineno;
2978 c->u->u_lineno_set = false;
2979 }
2980 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002983 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 VISIT(c, expr, e->v.BinOp.left);
2985 VISIT(c, expr, e->v.BinOp.right);
2986 ADDOP(c, binop(c, e->v.BinOp.op));
2987 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002988 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 VISIT(c, expr, e->v.UnaryOp.operand);
2990 ADDOP(c, unaryop(e->v.UnaryOp.op));
2991 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002992 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002994 case IfExp_kind:
2995 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002996 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettinger70fcfd02007-12-19 22:14:34 +00002998 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003000 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003001 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00003002 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003003 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00003004 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 }
3006 break;
Alexandre Vassalottiee936a22010-01-09 23:35:54 +00003007 case Set_kind:
3008 n = asdl_seq_LEN(e->v.Set.elts);
3009 VISIT_SEQ(c, expr, e->v.Set.elts);
3010 ADDOP_I(c, BUILD_SET, n);
3011 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003012 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013 return compiler_listcomp(c, e);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00003014 case SetComp_kind:
3015 return compiler_setcomp(c, e);
3016 case DictComp_kind:
3017 return compiler_dictcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003018 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 return compiler_genexp(c, e);
3020 case Yield_kind:
3021 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003022 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023 if (e->v.Yield.value) {
3024 VISIT(c, expr, e->v.Yield.value);
3025 }
3026 else {
3027 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3028 }
3029 ADDOP(c, YIELD_VALUE);
3030 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003031 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003033 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003035 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036 VISIT(c, expr, e->v.Repr.value);
3037 ADDOP(c, UNARY_CONVERT);
3038 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003039 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3041 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003042 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3044 break;
3045 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003046 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 if (e->v.Attribute.ctx != AugStore)
3048 VISIT(c, expr, e->v.Attribute.value);
3049 switch (e->v.Attribute.ctx) {
3050 case AugLoad:
3051 ADDOP(c, DUP_TOP);
3052 /* Fall through to load */
3053 case Load:
3054 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3055 break;
3056 case AugStore:
3057 ADDOP(c, ROT_TWO);
3058 /* Fall through to save */
3059 case Store:
3060 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3061 break;
3062 case Del:
3063 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3064 break;
3065 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003066 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003067 PyErr_SetString(PyExc_SystemError,
3068 "param invalid in attribute expression");
3069 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003070 }
3071 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 switch (e->v.Subscript.ctx) {
3074 case AugLoad:
3075 VISIT(c, expr, e->v.Subscript.value);
3076 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3077 break;
3078 case Load:
3079 VISIT(c, expr, e->v.Subscript.value);
3080 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3081 break;
3082 case AugStore:
3083 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3084 break;
3085 case Store:
3086 VISIT(c, expr, e->v.Subscript.value);
3087 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3088 break;
3089 case Del:
3090 VISIT(c, expr, e->v.Subscript.value);
3091 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3092 break;
3093 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003094 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003095 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003096 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003098 }
3099 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003100 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3102 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003103 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003105 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106 return compiler_tuple(c, e);
3107 }
3108 return 1;
3109}
3110
3111static int
3112compiler_augassign(struct compiler *c, stmt_ty s)
3113{
3114 expr_ty e = s->v.AugAssign.target;
3115 expr_ty auge;
3116
3117 assert(s->kind == AugAssign_kind);
3118
3119 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003120 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003122 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 if (auge == NULL)
3124 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125 VISIT(c, expr, auge);
3126 VISIT(c, expr, s->v.AugAssign.value);
3127 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3128 auge->v.Attribute.ctx = AugStore;
3129 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130 break;
3131 case Subscript_kind:
3132 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003133 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 if (auge == NULL)
3135 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136 VISIT(c, expr, auge);
3137 VISIT(c, expr, s->v.AugAssign.value);
3138 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003139 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003141 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003143 if (!compiler_nameop(c, e->v.Name.id, Load))
3144 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 VISIT(c, expr, s->v.AugAssign.value);
3146 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3147 return compiler_nameop(c, e->v.Name.id, Store);
3148 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003149 PyErr_Format(PyExc_SystemError,
3150 "invalid node type (%d) for augmented assignment",
3151 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003152 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003153 }
3154 return 1;
3155}
3156
3157static int
3158compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3159{
3160 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003161 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3162 PyErr_SetString(PyExc_SystemError,
3163 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003165 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166 f = &c->u->u_fblock[c->u->u_nfblocks++];
3167 f->fb_type = t;
3168 f->fb_block = b;
3169 return 1;
3170}
3171
3172static void
3173compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3174{
3175 struct compiler_unit *u = c->u;
3176 assert(u->u_nfblocks > 0);
3177 u->u_nfblocks--;
3178 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3179 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3180}
3181
Jeremy Hylton82271f12006-10-04 02:24:52 +00003182static int
3183compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003184 int i;
3185 struct compiler_unit *u = c->u;
3186 for (i = 0; i < u->u_nfblocks; ++i) {
3187 if (u->u_fblock[i].fb_type == LOOP)
3188 return 1;
3189 }
3190 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003191}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192/* Raises a SyntaxError and returns 0.
3193 If something goes wrong, a different exception may be raised.
3194*/
3195
3196static int
3197compiler_error(struct compiler *c, const char *errstr)
3198{
3199 PyObject *loc;
3200 PyObject *u = NULL, *v = NULL;
3201
3202 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3203 if (!loc) {
3204 Py_INCREF(Py_None);
3205 loc = Py_None;
3206 }
3207 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3208 Py_None, loc);
3209 if (!u)
3210 goto exit;
3211 v = Py_BuildValue("(zO)", errstr, u);
3212 if (!v)
3213 goto exit;
3214 PyErr_SetObject(PyExc_SyntaxError, v);
3215 exit:
3216 Py_DECREF(loc);
3217 Py_XDECREF(u);
3218 Py_XDECREF(v);
3219 return 0;
3220}
3221
3222static int
3223compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003224 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003226 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003228 /* XXX this code is duplicated */
3229 switch (ctx) {
3230 case AugLoad: /* fall through to Load */
3231 case Load: op = BINARY_SUBSCR; break;
3232 case AugStore:/* fall through to Store */
3233 case Store: op = STORE_SUBSCR; break;
3234 case Del: op = DELETE_SUBSCR; break;
3235 case Param:
3236 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003237 "invalid %s kind %d in subscript\n",
3238 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003239 return 0;
3240 }
3241 if (ctx == AugLoad) {
3242 ADDOP_I(c, DUP_TOPX, 2);
3243 }
3244 else if (ctx == AugStore) {
3245 ADDOP(c, ROT_THREE);
3246 }
3247 ADDOP(c, op);
3248 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249}
3250
3251static int
3252compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3253{
3254 int n = 2;
3255 assert(s->kind == Slice_kind);
3256
3257 /* only handles the cases where BUILD_SLICE is emitted */
3258 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003259 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 }
3261 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003262 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003264
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003266 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 }
3268 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003269 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270 }
3271
3272 if (s->v.Slice.step) {
3273 n++;
3274 VISIT(c, expr, s->v.Slice.step);
3275 }
3276 ADDOP_I(c, BUILD_SLICE, n);
3277 return 1;
3278}
3279
3280static int
3281compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3282{
3283 int op = 0, slice_offset = 0, stack_count = 0;
3284
3285 assert(s->v.Slice.step == NULL);
3286 if (s->v.Slice.lower) {
3287 slice_offset++;
3288 stack_count++;
3289 if (ctx != AugStore)
3290 VISIT(c, expr, s->v.Slice.lower);
3291 }
3292 if (s->v.Slice.upper) {
3293 slice_offset += 2;
3294 stack_count++;
3295 if (ctx != AugStore)
3296 VISIT(c, expr, s->v.Slice.upper);
3297 }
3298
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003299 if (ctx == AugLoad) {
3300 switch (stack_count) {
3301 case 0: ADDOP(c, DUP_TOP); break;
3302 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3303 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3304 }
3305 }
3306 else if (ctx == AugStore) {
3307 switch (stack_count) {
3308 case 0: ADDOP(c, ROT_TWO); break;
3309 case 1: ADDOP(c, ROT_THREE); break;
3310 case 2: ADDOP(c, ROT_FOUR); break;
3311 }
3312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313
3314 switch (ctx) {
3315 case AugLoad: /* fall through to Load */
3316 case Load: op = SLICE; break;
3317 case AugStore:/* fall through to Store */
3318 case Store: op = STORE_SLICE; break;
3319 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003320 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003321 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003322 PyErr_SetString(PyExc_SystemError,
3323 "param invalid in simple slice");
3324 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 }
3326
3327 ADDOP(c, op + slice_offset);
3328 return 1;
3329}
3330
3331static int
3332compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3333 expr_context_ty ctx)
3334{
3335 switch (s->kind) {
3336 case Ellipsis_kind:
3337 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3338 break;
3339 case Slice_kind:
3340 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003341 case Index_kind:
3342 VISIT(c, expr, s->v.Index.value);
3343 break;
3344 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003345 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003346 PyErr_SetString(PyExc_SystemError,
3347 "extended slice invalid in nested slice");
3348 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349 }
3350 return 1;
3351}
3352
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003353static int
3354compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3355{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003356 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003358 case Index_kind:
3359 kindname = "index";
3360 if (ctx != AugStore) {
3361 VISIT(c, expr, s->v.Index.value);
3362 }
3363 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003365 kindname = "ellipsis";
3366 if (ctx != AugStore) {
3367 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3368 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369 break;
3370 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003371 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003372 if (!s->v.Slice.step)
3373 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003374 if (ctx != AugStore) {
3375 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003376 return 0;
3377 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003378 break;
3379 case ExtSlice_kind:
3380 kindname = "extended slice";
3381 if (ctx != AugStore) {
3382 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3383 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003384 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003385 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003386 if (!compiler_visit_nested_slice(c, sub, ctx))
3387 return 0;
3388 }
3389 ADDOP_I(c, BUILD_TUPLE, n);
3390 }
3391 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003392 default:
3393 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003394 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003395 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003397 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398}
3399
Neal Norwitzf733a012006-10-29 18:30:10 +00003400
3401/* End of the compiler section, beginning of the assembler section */
3402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403/* do depth-first search of basic block graph, starting with block.
3404 post records the block indices in post-order.
3405
3406 XXX must handle implicit jumps from one block to next
3407*/
3408
Neal Norwitzf733a012006-10-29 18:30:10 +00003409struct assembler {
3410 PyObject *a_bytecode; /* string containing bytecode */
3411 int a_offset; /* offset into bytecode */
3412 int a_nblocks; /* number of reachable blocks */
3413 basicblock **a_postorder; /* list of blocks in dfs postorder */
3414 PyObject *a_lnotab; /* string containing lnotab */
3415 int a_lnotab_off; /* offset into lnotab */
3416 int a_lineno; /* last lineno of emitted instruction */
3417 int a_lineno_off; /* bytecode offset of last lineno */
3418};
3419
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420static void
3421dfs(struct compiler *c, basicblock *b, struct assembler *a)
3422{
3423 int i;
3424 struct instr *instr = NULL;
3425
3426 if (b->b_seen)
3427 return;
3428 b->b_seen = 1;
3429 if (b->b_next != NULL)
3430 dfs(c, b->b_next, a);
3431 for (i = 0; i < b->b_iused; i++) {
3432 instr = &b->b_instr[i];
3433 if (instr->i_jrel || instr->i_jabs)
3434 dfs(c, instr->i_target, a);
3435 }
3436 a->a_postorder[a->a_nblocks++] = b;
3437}
3438
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003439static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3441{
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +00003442 int i, target_depth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443 struct instr *instr;
3444 if (b->b_seen || b->b_startdepth >= depth)
3445 return maxdepth;
3446 b->b_seen = 1;
3447 b->b_startdepth = depth;
3448 for (i = 0; i < b->b_iused; i++) {
3449 instr = &b->b_instr[i];
3450 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3451 if (depth > maxdepth)
3452 maxdepth = depth;
3453 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3454 if (instr->i_jrel || instr->i_jabs) {
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +00003455 target_depth = depth;
3456 if (instr->i_opcode == FOR_ITER) {
3457 target_depth = depth-2;
3458 } else if (instr->i_opcode == SETUP_FINALLY ||
3459 instr->i_opcode == SETUP_EXCEPT) {
3460 target_depth = depth+3;
3461 if (target_depth > maxdepth)
3462 maxdepth = target_depth;
3463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003464 maxdepth = stackdepth_walk(c, instr->i_target,
Neil Schemenauer7fdd1cb2009-10-14 17:17:14 +00003465 target_depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466 if (instr->i_opcode == JUMP_ABSOLUTE ||
3467 instr->i_opcode == JUMP_FORWARD) {
3468 goto out; /* remaining code is dead */
3469 }
3470 }
3471 }
3472 if (b->b_next)
3473 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3474out:
3475 b->b_seen = 0;
3476 return maxdepth;
3477}
3478
3479/* Find the flow path that needs the largest stack. We assume that
3480 * cycles in the flow graph have no net effect on the stack depth.
3481 */
3482static int
3483stackdepth(struct compiler *c)
3484{
3485 basicblock *b, *entryblock;
3486 entryblock = NULL;
3487 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3488 b->b_seen = 0;
3489 b->b_startdepth = INT_MIN;
3490 entryblock = b;
3491 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003492 if (!entryblock)
3493 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 return stackdepth_walk(c, entryblock, 0, 0);
3495}
3496
3497static int
3498assemble_init(struct assembler *a, int nblocks, int firstlineno)
3499{
3500 memset(a, 0, sizeof(struct assembler));
3501 a->a_lineno = firstlineno;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003502 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 if (!a->a_bytecode)
3504 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003505 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506 if (!a->a_lnotab)
3507 return 0;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003508 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3509 PyErr_NoMemory();
3510 return 0;
3511 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003513 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003514 if (!a->a_postorder) {
3515 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518 return 1;
3519}
3520
3521static void
3522assemble_free(struct assembler *a)
3523{
3524 Py_XDECREF(a->a_bytecode);
3525 Py_XDECREF(a->a_lnotab);
3526 if (a->a_postorder)
3527 PyObject_Free(a->a_postorder);
3528}
3529
3530/* Return the size of a basic block in bytes. */
3531
3532static int
3533instrsize(struct instr *instr)
3534{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003535 if (!instr->i_hasarg)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003536 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003537 if (instr->i_oparg > 0xffff)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003538 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3539 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540}
3541
3542static int
3543blocksize(basicblock *b)
3544{
3545 int i;
3546 int size = 0;
3547
3548 for (i = 0; i < b->b_iused; i++)
3549 size += instrsize(&b->b_instr[i]);
3550 return size;
3551}
3552
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003553/* Appends a pair to the end of the line number table, a_lnotab, representing
3554 the instruction's bytecode offset and line number. See
3555 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003556
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003557static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003559{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 int d_bytecode, d_lineno;
3561 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003562 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563
3564 d_bytecode = a->a_offset - a->a_lineno_off;
3565 d_lineno = i->i_lineno - a->a_lineno;
3566
3567 assert(d_bytecode >= 0);
3568 assert(d_lineno >= 0);
3569
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003570 if(d_bytecode == 0 && d_lineno == 0)
3571 return 1;
3572
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003574 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003576 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003578 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003580 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003582 else {
3583 PyErr_NoMemory();
3584 return 0;
3585 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003586 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003588 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003589 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003590 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003591 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 *lnotab++ = 255;
3593 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595 d_bytecode -= ncodes * 255;
3596 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003597 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598 assert(d_bytecode <= 255);
3599 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003600 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003602 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003603 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003604 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003606 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003608 else {
3609 PyErr_NoMemory();
3610 return 0;
3611 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003612 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003614 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003615 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003616 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003618 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003620 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003622 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 d_lineno -= ncodes * 255;
3625 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003626 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003627
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003628 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003629 if (a->a_lnotab_off + 2 >= len) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003630 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003631 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003632 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003633 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003634 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003635
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 a->a_lnotab_off += 2;
3637 if (d_bytecode) {
3638 *lnotab++ = d_bytecode;
3639 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003640 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003641 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 *lnotab++ = 0;
3643 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003644 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 a->a_lineno = i->i_lineno;
3646 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003647 return 1;
3648}
3649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650/* assemble_emit()
3651 Extend the bytecode with a new instruction.
3652 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003653*/
3654
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003655static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003657{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003658 int size, arg = 0, ext = 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003659 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 char *code;
3661
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003662 size = instrsize(i);
3663 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003665 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003668 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669 if (a->a_offset + size >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003670 if (len > PY_SSIZE_T_MAX / 2)
3671 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003672 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003673 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003674 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003675 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003677 if (size == 6) {
3678 assert(i->i_hasarg);
3679 *code++ = (char)EXTENDED_ARG;
3680 *code++ = ext & 0xff;
3681 *code++ = ext >> 8;
3682 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003683 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003685 if (i->i_hasarg) {
3686 assert(size == 3 || size == 6);
3687 *code++ = arg & 0xff;
3688 *code++ = arg >> 8;
3689 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003691}
3692
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003693static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003695{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003696 basicblock *b;
Benjamin Petersoncef97822009-11-20 02:15:50 +00003697 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003698 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003699
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700 /* Compute the size of each block and fixup jump args.
3701 Replace block pointer with position in bytecode. */
Benjamin Petersoncef97822009-11-20 02:15:50 +00003702 do {
3703 totsize = 0;
3704 for (i = a->a_nblocks - 1; i >= 0; i--) {
3705 b = a->a_postorder[i];
3706 bsize = blocksize(b);
3707 b->b_offset = totsize;
3708 totsize += bsize;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003709 }
Benjamin Petersoncef97822009-11-20 02:15:50 +00003710 last_extended_arg_count = extended_arg_count;
3711 extended_arg_count = 0;
3712 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3713 bsize = b->b_offset;
3714 for (i = 0; i < b->b_iused; i++) {
3715 struct instr *instr = &b->b_instr[i];
3716 /* Relative jumps are computed relative to
3717 the instruction pointer after fetching
3718 the jump instruction.
3719 */
3720 bsize += instrsize(instr);
3721 if (instr->i_jabs)
3722 instr->i_oparg = instr->i_target->b_offset;
3723 else if (instr->i_jrel) {
3724 int delta = instr->i_target->b_offset - bsize;
3725 instr->i_oparg = delta;
3726 }
3727 else
3728 continue;
3729 if (instr->i_oparg > 0xffff)
3730 extended_arg_count++;
3731 }
3732 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003733
3734 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003735 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003736 with a better solution.
3737
Neal Norwitzf1d50682005-10-23 23:00:41 +00003738 The issue is that in the first loop blocksize() is called
3739 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003740 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003741 i_oparg is calculated in the second loop above.
3742
3743 So we loop until we stop seeing new EXTENDED_ARGs.
3744 The only EXTENDED_ARGs that could be popping up are
3745 ones in jump instructions. So this should converge
3746 fairly quickly.
3747 */
Benjamin Petersoncef97822009-11-20 02:15:50 +00003748 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003749}
3750
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003751static PyObject *
3752dict_keys_inorder(PyObject *dict, int offset)
3753{
3754 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003755 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003756
3757 tuple = PyTuple_New(size);
3758 if (tuple == NULL)
3759 return NULL;
3760 while (PyDict_Next(dict, &pos, &k, &v)) {
3761 i = PyInt_AS_LONG(v);
Benjamin Petersonda9327f2009-01-31 23:43:25 +00003762 /* The keys of the dictionary are tuples. (see compiler_add_o)
3763 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003764 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003765 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003766 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003767 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003768 PyTuple_SET_ITEM(tuple, i - offset, k);
3769 }
3770 return tuple;
3771}
3772
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003773static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003775{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 PySTEntryObject *ste = c->u->u_ste;
3777 int flags = 0, n;
3778 if (ste->ste_type != ModuleBlock)
3779 flags |= CO_NEWLOCALS;
3780 if (ste->ste_type == FunctionBlock) {
3781 if (!ste->ste_unoptimized)
3782 flags |= CO_OPTIMIZED;
3783 if (ste->ste_nested)
3784 flags |= CO_NESTED;
3785 if (ste->ste_generator)
3786 flags |= CO_GENERATOR;
Benjamin Peterson12554cb2009-01-31 23:54:38 +00003787 if (ste->ste_varargs)
3788 flags |= CO_VARARGS;
3789 if (ste->ste_varkeywords)
3790 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003791 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003792
3793 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003794 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 n = PyDict_Size(c->u->u_freevars);
3797 if (n < 0)
3798 return -1;
3799 if (n == 0) {
3800 n = PyDict_Size(c->u->u_cellvars);
3801 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003802 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003803 if (n == 0) {
3804 flags |= CO_NOFREE;
3805 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003806 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003807
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003808 return flags;
3809}
3810
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003811static PyCodeObject *
3812makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003813{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 PyObject *tmp;
3815 PyCodeObject *co = NULL;
3816 PyObject *consts = NULL;
3817 PyObject *names = NULL;
3818 PyObject *varnames = NULL;
3819 PyObject *filename = NULL;
3820 PyObject *name = NULL;
3821 PyObject *freevars = NULL;
3822 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003823 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003825
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826 tmp = dict_keys_inorder(c->u->u_consts, 0);
3827 if (!tmp)
3828 goto error;
3829 consts = PySequence_List(tmp); /* optimize_code requires a list */
3830 Py_DECREF(tmp);
3831
3832 names = dict_keys_inorder(c->u->u_names, 0);
3833 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3834 if (!consts || !names || !varnames)
3835 goto error;
3836
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003837 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3838 if (!cellvars)
3839 goto error;
3840 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3841 if (!freevars)
3842 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003843 filename = PyString_FromString(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844 if (!filename)
3845 goto error;
3846
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003847 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 flags = compute_code_flags(c);
3849 if (flags < 0)
3850 goto error;
3851
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003852 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 if (!bytecode)
3854 goto error;
3855
3856 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3857 if (!tmp)
3858 goto error;
3859 Py_DECREF(consts);
3860 consts = tmp;
3861
3862 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3863 bytecode, consts, names, varnames,
3864 freevars, cellvars,
3865 filename, c->u->u_name,
3866 c->u->u_firstlineno,
3867 a->a_lnotab);
3868 error:
3869 Py_XDECREF(consts);
3870 Py_XDECREF(names);
3871 Py_XDECREF(varnames);
3872 Py_XDECREF(filename);
3873 Py_XDECREF(name);
3874 Py_XDECREF(freevars);
3875 Py_XDECREF(cellvars);
3876 Py_XDECREF(bytecode);
3877 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003878}
3879
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003880
3881/* For debugging purposes only */
3882#if 0
3883static void
3884dump_instr(const struct instr *i)
3885{
3886 const char *jrel = i->i_jrel ? "jrel " : "";
3887 const char *jabs = i->i_jabs ? "jabs " : "";
3888 char arg[128];
3889
3890 *arg = '\0';
3891 if (i->i_hasarg)
3892 sprintf(arg, "arg: %d ", i->i_oparg);
3893
3894 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3895 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3896}
3897
3898static void
3899dump_basicblock(const basicblock *b)
3900{
3901 const char *seen = b->b_seen ? "seen " : "";
3902 const char *b_return = b->b_return ? "return " : "";
3903 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3904 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3905 if (b->b_instr) {
3906 int i;
3907 for (i = 0; i < b->b_iused; i++) {
3908 fprintf(stderr, " [%02d] ", i);
3909 dump_instr(b->b_instr + i);
3910 }
3911 }
3912}
3913#endif
3914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915static PyCodeObject *
3916assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003917{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 basicblock *b, *entryblock;
3919 struct assembler a;
3920 int i, j, nblocks;
3921 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003922
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923 /* Make sure every block that falls off the end returns None.
3924 XXX NEXT_BLOCK() isn't quite right, because if the last
3925 block ends with a jump or return b_next shouldn't set.
3926 */
3927 if (!c->u->u_curblock->b_return) {
3928 NEXT_BLOCK(c);
3929 if (addNone)
3930 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3931 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003932 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934 nblocks = 0;
3935 entryblock = NULL;
3936 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3937 nblocks++;
3938 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003939 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003940
Neal Norwitzed657552006-07-10 00:04:44 +00003941 /* Set firstlineno if it wasn't explicitly set. */
3942 if (!c->u->u_firstlineno) {
3943 if (entryblock && entryblock->b_instr)
3944 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3945 else
3946 c->u->u_firstlineno = 1;
3947 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003948 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3949 goto error;
3950 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003952 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003953 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003954
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003955 /* Emit code in reverse postorder from dfs. */
3956 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003957 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003958 for (j = 0; j < b->b_iused; j++)
3959 if (!assemble_emit(&a, &b->b_instr[j]))
3960 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003961 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003962
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003963 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003965 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003967
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003968 co = makecode(c, &a);
3969 error:
3970 assemble_free(&a);
3971 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003972}