blob: 531bed43c4815c8b31099af57056c450f489d01e [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
Antoine Pitrouc83ea132010-05-09 14:46:46 +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
Antoine Pitrouc83ea132010-05-09 14:46:46 +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 {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000047 unsigned i_jabs : 1;
48 unsigned i_jrel : 1;
49 unsigned i_hasarg : 1;
50 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. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +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. */
71 unsigned b_seen : 1;
72 /* b_return is true if a RETURN_VALUE opcode is inserted. */
73 unsigned b_return : 1;
74 /* depth of stack upon entry of block, computed by stackdepth() */
75 int b_startdepth;
76 /* instruction offset for block, computed by assemble_jump_offsets() */
77 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 {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000090 enum fblocktype fb_type;
91 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092};
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 {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000098 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000100 PyObject *u_name;
101 /* The following fields are dicts that map objects to
102 the index of them in co_XXX. The index is used as
103 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 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000111 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000112
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000113 int u_argcount; /* number of arguments for block */
114 /* Pointer to the most recently allocated block. By following b_list
115 members, you can reach all early allocated blocks. */
116 basicblock *u_blocks;
117 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000119 int u_nfblocks;
120 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000122 int u_firstlineno; /* the first lineno of the block */
123 int u_lineno; /* the lineno for the current stmt */
124 bool u_lineno_set; /* boolean to indicate whether instr
125 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126};
127
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000130The u pointer points to the current compilation unit, while units
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000131for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000132managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133*/
134
135struct compiler {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000136 const char *c_filename;
137 struct symtable *c_st;
138 PyFutureFeatures *c_future; /* pointer to module's __future__ */
139 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 int c_interactive; /* true if in interactive mode */
142 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 struct compiler_unit *u; /* compiler state for current block */
145 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
146 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,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000167 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168
169static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000170 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 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
Larry Hastings402b73f2010-03-25 00:54:54 +0000184#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
185
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000187_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000188{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000189 /* Name mangling: __private becomes _classname__private.
190 This is independent from how the name is used. */
191 const char *p, *name = PyString_AsString(ident);
192 char *buffer;
193 size_t nlen, plen;
194 if (privateobj == NULL || !PyString_Check(privateobj) ||
195 name == NULL || name[0] != '_' || name[1] != '_') {
196 Py_INCREF(ident);
197 return ident;
198 }
199 p = PyString_AsString(privateobj);
200 nlen = strlen(name);
201 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000202
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 The only time a name with a dot can occur is when
204 we are compiling an import statement that has a
205 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000206
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000207 TODO(jhylton): Decide whether we want to support
208 mangling of the module name, e.g. __M.X.
209 */
210 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
211 || strchr(name, '.')) {
212 Py_INCREF(ident);
213 return ident; /* Don't mangle __whatever__ */
214 }
215 /* Strip leading underscores from class name */
216 while (*p == '_')
217 p++;
218 if (*p == '\0') {
219 Py_INCREF(ident);
220 return ident; /* Don't mangle if class is just underscores */
221 }
222 plen = strlen(p);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000223
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000224 assert(1 <= PY_SSIZE_T_MAX - nlen);
225 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000226
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
228 if (!ident)
229 return 0;
230 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
231 buffer = PyString_AS_STRING(ident);
232 buffer[0] = '_';
233 strncpy(buffer+1, p, plen);
234 strcpy(buffer+1+plen, name);
235 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000236}
237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000238static int
239compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000240{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000241 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000242
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000243 c->c_stack = PyList_New(0);
244 if (!c->c_stack)
245 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000246
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000247 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000248}
249
250PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000251PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000252 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 struct compiler c;
255 PyCodeObject *co = NULL;
256 PyCompilerFlags local_flags;
257 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000258
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000259 if (!__doc__) {
260 __doc__ = PyString_InternFromString("__doc__");
261 if (!__doc__)
262 return NULL;
263 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000265 if (!compiler_init(&c))
266 return NULL;
267 c.c_filename = filename;
268 c.c_arena = arena;
269 c.c_future = PyFuture_FromAST(mod, filename);
270 if (c.c_future == NULL)
271 goto finally;
272 if (!flags) {
273 local_flags.cf_flags = 0;
274 flags = &local_flags;
275 }
276 merged = c.c_future->ff_features | flags->cf_flags;
277 c.c_future->ff_features = merged;
278 flags->cf_flags = merged;
279 c.c_flags = flags;
280 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000281
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000282 c.c_st = PySymtable_Build(mod, filename, c.c_future);
283 if (c.c_st == NULL) {
284 if (!PyErr_Occurred())
285 PyErr_SetString(PyExc_SystemError, "no symtable");
286 goto finally;
287 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000289 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
Thomas Wouters1175c432006-02-27 22:49:54 +0000291 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 compiler_free(&c);
293 assert(co || PyErr_Occurred());
294 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295}
296
297PyCodeObject *
298PyNode_Compile(struct _node *n, const char *filename)
299{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000300 PyCodeObject *co = NULL;
301 mod_ty mod;
302 PyArena *arena = PyArena_New();
303 if (!arena)
304 return NULL;
305 mod = PyAST_FromNode(n, NULL, filename, arena);
306 if (mod)
307 co = PyAST_Compile(mod, filename, NULL, arena);
308 PyArena_Free(arena);
309 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000310}
311
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000312static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000314{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 if (c->c_st)
316 PySymtable_Free(c->c_st);
317 if (c->c_future)
318 PyObject_Free(c->c_future);
319 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320}
321
Guido van Rossum79f25d91997-04-29 20:08:16 +0000322static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000324{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 Py_ssize_t i, n;
326 PyObject *v, *k;
327 PyObject *dict = PyDict_New();
328 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000329
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000330 n = PyList_Size(list);
331 for (i = 0; i < n; i++) {
332 v = PyInt_FromLong(i);
333 if (!v) {
334 Py_DECREF(dict);
335 return NULL;
336 }
337 k = PyList_GET_ITEM(list, i);
338 k = PyTuple_Pack(2, k, k->ob_type);
339 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
340 Py_XDECREF(k);
341 Py_DECREF(v);
342 Py_DECREF(dict);
343 return NULL;
344 }
345 Py_DECREF(k);
346 Py_DECREF(v);
347 }
348 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349}
350
351/* Return new dict containing names from src that match scope(s).
352
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000353src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000354either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000355values are integers, starting at offset and increasing by one for
356each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357*/
358
359static PyObject *
360dictbytype(PyObject *src, int scope_type, int flag, int offset)
361{
Meador Inge0e3755e2012-07-18 17:48:34 -0500362 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000363 PyObject *k, *v, *dest = PyDict_New();
Meador Inge6642d1f2012-07-18 14:09:04 -0500364 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000366 assert(offset >= 0);
367 if (dest == NULL)
368 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369
Meador Inge6642d1f2012-07-18 14:09:04 -0500370 /* Sort the keys so that we have a deterministic order on the indexes
371 saved in the returned dictionary. These indexes are used as indexes
372 into the free and cell var storage. Therefore if they aren't
373 deterministic, then the generated bytecode is not deterministic.
374 */
375 sorted_keys = PyDict_Keys(src);
376 if (sorted_keys == NULL)
377 return NULL;
378 if (PyList_Sort(sorted_keys) != 0) {
379 Py_DECREF(sorted_keys);
380 return NULL;
381 }
Meador Ingeb8a56902012-07-18 16:32:37 -0500382 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge6642d1f2012-07-18 14:09:04 -0500383
384 for (key_i = 0; key_i < num_keys; key_i++) {
385 k = PyList_GET_ITEM(sorted_keys, key_i);
386 v = PyDict_GetItem(src, k);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000387 /* XXX this should probably be a macro in symtable.h */
388 assert(PyInt_Check(v));
389 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000391 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
392 PyObject *tuple, *item = PyInt_FromLong(i);
393 if (item == NULL) {
Meador Inge6642d1f2012-07-18 14:09:04 -0500394 Py_DECREF(sorted_keys);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000395 Py_DECREF(dest);
396 return NULL;
397 }
398 i++;
399 tuple = PyTuple_Pack(2, k, k->ob_type);
400 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge6642d1f2012-07-18 14:09:04 -0500401 Py_DECREF(sorted_keys);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 Py_DECREF(item);
403 Py_DECREF(dest);
404 Py_XDECREF(tuple);
405 return NULL;
406 }
407 Py_DECREF(item);
408 Py_DECREF(tuple);
409 }
410 }
Meador Inge6642d1f2012-07-18 14:09:04 -0500411 Py_DECREF(sorted_keys);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000412 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000413}
414
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415static void
416compiler_unit_check(struct compiler_unit *u)
417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 basicblock *block;
419 for (block = u->u_blocks; block != NULL; block = block->b_list) {
420 assert((void *)block != (void *)0xcbcbcbcb);
421 assert((void *)block != (void *)0xfbfbfbfb);
422 assert((void *)block != (void *)0xdbdbdbdb);
423 if (block->b_instr != NULL) {
424 assert(block->b_ialloc > 0);
425 assert(block->b_iused > 0);
426 assert(block->b_ialloc >= block->b_iused);
427 }
428 else {
429 assert (block->b_iused == 0);
430 assert (block->b_ialloc == 0);
431 }
432 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433}
434
435static void
436compiler_unit_free(struct compiler_unit *u)
437{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000438 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 compiler_unit_check(u);
441 b = u->u_blocks;
442 while (b != NULL) {
443 if (b->b_instr)
444 PyObject_Free((void *)b->b_instr);
445 next = b->b_list;
446 PyObject_Free((void *)b);
447 b = next;
448 }
449 Py_CLEAR(u->u_ste);
450 Py_CLEAR(u->u_name);
451 Py_CLEAR(u->u_consts);
452 Py_CLEAR(u->u_names);
453 Py_CLEAR(u->u_varnames);
454 Py_CLEAR(u->u_freevars);
455 Py_CLEAR(u->u_cellvars);
456 Py_CLEAR(u->u_private);
457 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458}
459
460static int
461compiler_enter_scope(struct compiler *c, identifier name, void *key,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000462 int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000464 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000465
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000466 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
467 struct compiler_unit));
468 if (!u) {
469 PyErr_NoMemory();
470 return 0;
471 }
472 memset(u, 0, sizeof(struct compiler_unit));
473 u->u_argcount = 0;
474 u->u_ste = PySymtable_Lookup(c->c_st, key);
475 if (!u->u_ste) {
476 compiler_unit_free(u);
477 return 0;
478 }
479 Py_INCREF(name);
480 u->u_name = name;
481 u->u_varnames = list2dict(u->u_ste->ste_varnames);
482 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
483 if (!u->u_varnames || !u->u_cellvars) {
484 compiler_unit_free(u);
485 return 0;
486 }
Neal Norwitzd12bd012006-07-21 07:59:47 +0000487
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000488 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
489 PyDict_Size(u->u_cellvars));
490 if (!u->u_freevars) {
491 compiler_unit_free(u);
492 return 0;
493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000494
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000495 u->u_blocks = NULL;
496 u->u_nfblocks = 0;
497 u->u_firstlineno = lineno;
498 u->u_lineno = 0;
499 u->u_lineno_set = false;
500 u->u_consts = PyDict_New();
501 if (!u->u_consts) {
502 compiler_unit_free(u);
503 return 0;
504 }
505 u->u_names = PyDict_New();
506 if (!u->u_names) {
507 compiler_unit_free(u);
508 return 0;
509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000510
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000512
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000513 /* Push the old compiler_unit on the stack. */
514 if (c->u) {
515 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
516 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
517 Py_XDECREF(capsule);
518 compiler_unit_free(u);
519 return 0;
520 }
521 Py_DECREF(capsule);
522 u->u_private = c->u->u_private;
523 Py_XINCREF(u->u_private);
524 }
525 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000526
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000527 c->c_nestlevel++;
528 if (compiler_use_new_block(c) == NULL)
529 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000530
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000531 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532}
533
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000534static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535compiler_exit_scope(struct compiler *c)
536{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000537 int n;
538 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000539
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000540 c->c_nestlevel--;
541 compiler_unit_free(c->u);
542 /* Restore c->u to the parent unit. */
543 n = PyList_GET_SIZE(c->c_stack) - 1;
544 if (n >= 0) {
545 capsule = PyList_GET_ITEM(c->c_stack, n);
546 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
547 assert(c->u);
548 /* we are deleting from a list so this really shouldn't fail */
549 if (PySequence_DelItem(c->c_stack, n) < 0)
550 Py_FatalError("compiler_exit_scope()");
551 compiler_unit_check(c->u);
552 }
553 else
554 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556}
557
558/* Allocate a new block and return a pointer to it.
559 Returns NULL on error.
560*/
561
562static basicblock *
563compiler_new_block(struct compiler *c)
564{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565 basicblock *b;
566 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 u = c->u;
569 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
570 if (b == NULL) {
571 PyErr_NoMemory();
572 return NULL;
573 }
574 memset((void *)b, 0, sizeof(basicblock));
575 /* Extend the singly linked list of blocks with new block. */
576 b->b_list = u->u_blocks;
577 u->u_blocks = b;
578 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579}
580
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000581static basicblock *
582compiler_use_new_block(struct compiler *c)
583{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000584 basicblock *block = compiler_new_block(c);
585 if (block == NULL)
586 return NULL;
587 c->u->u_curblock = block;
588 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000589}
590
591static basicblock *
592compiler_next_block(struct compiler *c)
593{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000594 basicblock *block = compiler_new_block(c);
595 if (block == NULL)
596 return NULL;
597 c->u->u_curblock->b_next = block;
598 c->u->u_curblock = block;
599 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000600}
601
602static basicblock *
603compiler_use_next_block(struct compiler *c, basicblock *block)
604{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 assert(block != NULL);
606 c->u->u_curblock->b_next = block;
607 c->u->u_curblock = block;
608 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609}
610
611/* Returns the offset of the next instruction in the current block's
612 b_instr array. Resizes the b_instr as necessary.
613 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000614*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615
616static int
617compiler_next_instr(struct compiler *c, basicblock *b)
618{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000619 assert(b != NULL);
620 if (b->b_instr == NULL) {
621 b->b_instr = (struct instr *)PyObject_Malloc(
622 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
623 if (b->b_instr == NULL) {
624 PyErr_NoMemory();
625 return -1;
626 }
627 b->b_ialloc = DEFAULT_BLOCK_SIZE;
628 memset((char *)b->b_instr, 0,
629 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
630 }
631 else if (b->b_iused == b->b_ialloc) {
632 struct instr *tmp;
633 size_t oldsize, newsize;
634 oldsize = b->b_ialloc * sizeof(struct instr);
635 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000636
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000637 if (oldsize > (PY_SIZE_MAX >> 1)) {
638 PyErr_NoMemory();
639 return -1;
640 }
Gregory P. Smith9d534572008-06-11 07:41:16 +0000641
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000642 if (newsize == 0) {
643 PyErr_NoMemory();
644 return -1;
645 }
646 b->b_ialloc <<= 1;
647 tmp = (struct instr *)PyObject_Realloc(
648 (void *)b->b_instr, newsize);
649 if (tmp == NULL) {
650 PyErr_NoMemory();
651 return -1;
652 }
653 b->b_instr = tmp;
654 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
655 }
656 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657}
658
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000659/* Set the i_lineno member of the instruction at offset off if the
660 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000661 already been set. If it has been set, the call has no effect.
662
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000663 The line number is reset in the following cases:
664 - when entering a new scope
665 - on each statement
666 - on each expression that start a new line
667 - before the "except" clause
668 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000669*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000670
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000671static void
672compiler_set_lineno(struct compiler *c, int off)
673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 basicblock *b;
675 if (c->u->u_lineno_set)
676 return;
677 c->u->u_lineno_set = true;
678 b = c->u->u_curblock;
679 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000680}
681
682static int
683opcode_stack_effect(int opcode, int oparg)
684{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000685 switch (opcode) {
686 case POP_TOP:
687 return -1;
688 case ROT_TWO:
689 case ROT_THREE:
690 return 0;
691 case DUP_TOP:
692 return 1;
693 case ROT_FOUR:
694 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000695
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000696 case UNARY_POSITIVE:
697 case UNARY_NEGATIVE:
698 case UNARY_NOT:
699 case UNARY_CONVERT:
700 case UNARY_INVERT:
701 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000702
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000703 case SET_ADD:
704 case LIST_APPEND:
705 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000706
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000707 case MAP_ADD:
708 return -2;
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000709
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 case BINARY_POWER:
711 case BINARY_MULTIPLY:
712 case BINARY_DIVIDE:
713 case BINARY_MODULO:
714 case BINARY_ADD:
715 case BINARY_SUBTRACT:
716 case BINARY_SUBSCR:
717 case BINARY_FLOOR_DIVIDE:
718 case BINARY_TRUE_DIVIDE:
719 return -1;
720 case INPLACE_FLOOR_DIVIDE:
721 case INPLACE_TRUE_DIVIDE:
722 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000723
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000724 case SLICE+0:
725 return 0;
726 case SLICE+1:
727 return -1;
728 case SLICE+2:
729 return -1;
730 case SLICE+3:
731 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000733 case STORE_SLICE+0:
734 return -2;
735 case STORE_SLICE+1:
736 return -3;
737 case STORE_SLICE+2:
738 return -3;
739 case STORE_SLICE+3:
740 return -4;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000741
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000742 case DELETE_SLICE+0:
743 return -1;
744 case DELETE_SLICE+1:
745 return -2;
746 case DELETE_SLICE+2:
747 return -2;
748 case DELETE_SLICE+3:
749 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000750
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 case INPLACE_ADD:
752 case INPLACE_SUBTRACT:
753 case INPLACE_MULTIPLY:
754 case INPLACE_DIVIDE:
755 case INPLACE_MODULO:
756 return -1;
757 case STORE_SUBSCR:
758 return -3;
759 case STORE_MAP:
760 return -2;
761 case DELETE_SUBSCR:
762 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000764 case BINARY_LSHIFT:
765 case BINARY_RSHIFT:
766 case BINARY_AND:
767 case BINARY_XOR:
768 case BINARY_OR:
769 return -1;
770 case INPLACE_POWER:
771 return -1;
772 case GET_ITER:
773 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000775 case PRINT_EXPR:
776 return -1;
777 case PRINT_ITEM:
778 return -1;
779 case PRINT_NEWLINE:
780 return 0;
781 case PRINT_ITEM_TO:
782 return -2;
783 case PRINT_NEWLINE_TO:
784 return -1;
785 case INPLACE_LSHIFT:
786 case INPLACE_RSHIFT:
787 case INPLACE_AND:
788 case INPLACE_XOR:
789 case INPLACE_OR:
790 return -1;
791 case BREAK_LOOP:
792 return 0;
793 case SETUP_WITH:
794 return 4;
795 case WITH_CLEANUP:
796 return -1; /* XXX Sometimes more */
797 case LOAD_LOCALS:
798 return 1;
799 case RETURN_VALUE:
800 return -1;
801 case IMPORT_STAR:
802 return -1;
803 case EXEC_STMT:
804 return -3;
805 case YIELD_VALUE:
806 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000807
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000808 case POP_BLOCK:
809 return 0;
810 case END_FINALLY:
811 return -3; /* or -1 or -2 if no exception occurred or
812 return/break/continue */
813 case BUILD_CLASS:
814 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000815
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000816 case STORE_NAME:
817 return -1;
818 case DELETE_NAME:
819 return 0;
820 case UNPACK_SEQUENCE:
821 return oparg-1;
822 case FOR_ITER:
823 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000824
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000825 case STORE_ATTR:
826 return -2;
827 case DELETE_ATTR:
828 return -1;
829 case STORE_GLOBAL:
830 return -1;
831 case DELETE_GLOBAL:
832 return 0;
833 case DUP_TOPX:
834 return oparg;
835 case LOAD_CONST:
836 return 1;
837 case LOAD_NAME:
838 return 1;
839 case BUILD_TUPLE:
840 case BUILD_LIST:
841 case BUILD_SET:
842 return 1-oparg;
843 case BUILD_MAP:
844 return 1;
845 case LOAD_ATTR:
846 return 0;
847 case COMPARE_OP:
848 return -1;
849 case IMPORT_NAME:
850 return -1;
851 case IMPORT_FROM:
852 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000853
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000854 case JUMP_FORWARD:
855 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
856 case JUMP_IF_FALSE_OR_POP: /* "" */
857 case JUMP_ABSOLUTE:
858 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000860 case POP_JUMP_IF_FALSE:
861 case POP_JUMP_IF_TRUE:
862 return -1;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000863
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000864 case LOAD_GLOBAL:
865 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000866
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 case CONTINUE_LOOP:
868 return 0;
869 case SETUP_LOOP:
870 case SETUP_EXCEPT:
871 case SETUP_FINALLY:
872 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 case LOAD_FAST:
875 return 1;
876 case STORE_FAST:
877 return -1;
878 case DELETE_FAST:
879 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000880
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000881 case RAISE_VARARGS:
882 return -oparg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000883#define NARGS(o) (((o) % 256) + 2*((o) / 256))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000884 case CALL_FUNCTION:
885 return -NARGS(oparg);
886 case CALL_FUNCTION_VAR:
887 case CALL_FUNCTION_KW:
888 return -NARGS(oparg)-1;
889 case CALL_FUNCTION_VAR_KW:
890 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891#undef NARGS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000892 case MAKE_FUNCTION:
893 return -oparg;
894 case BUILD_SLICE:
895 if (oparg == 3)
896 return -2;
897 else
898 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000900 case MAKE_CLOSURE:
901 return -oparg-1;
902 case LOAD_CLOSURE:
903 return 1;
904 case LOAD_DEREF:
905 return 1;
906 case STORE_DEREF:
907 return -1;
908 default:
909 fprintf(stderr, "opcode = %d\n", opcode);
910 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000911
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000912 }
913 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914}
915
916/* Add an opcode with no argument.
917 Returns 0 on failure, 1 on success.
918*/
919
920static int
921compiler_addop(struct compiler *c, int opcode)
922{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000923 basicblock *b;
924 struct instr *i;
925 int off;
926 off = compiler_next_instr(c, c->u->u_curblock);
927 if (off < 0)
928 return 0;
929 b = c->u->u_curblock;
930 i = &b->b_instr[off];
931 i->i_opcode = opcode;
932 i->i_hasarg = 0;
933 if (opcode == RETURN_VALUE)
934 b->b_return = 1;
935 compiler_set_lineno(c, off);
936 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937}
938
939static int
940compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
941{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000942 PyObject *t, *v;
943 Py_ssize_t arg;
944 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000945
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000946 /* necessary to make sure types aren't coerced (e.g., int and long) */
947 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
948 if (PyFloat_Check(o)) {
949 d = PyFloat_AS_DOUBLE(o);
950 /* all we need is to make the tuple different in either the 0.0
951 * or -0.0 case from all others, just to avoid the "coercion".
952 */
953 if (d == 0.0 && copysign(1.0, d) < 0.0)
954 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
955 else
956 t = PyTuple_Pack(2, o, o->ob_type);
957 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000958#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000959 else if (PyComplex_Check(o)) {
960 Py_complex z;
961 int real_negzero, imag_negzero;
962 /* For the complex case we must make complex(x, 0.)
963 different from complex(x, -0.) and complex(0., y)
964 different from complex(-0., y), for any x and y.
965 All four complex zeros must be distinguished.*/
966 z = PyComplex_AsCComplex(o);
967 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
968 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
969 if (real_negzero && imag_negzero) {
970 t = PyTuple_Pack(5, o, o->ob_type,
971 Py_None, Py_None, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000972 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 else if (imag_negzero) {
974 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
975 }
976 else if (real_negzero) {
977 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
978 }
979 else {
980 t = PyTuple_Pack(2, o, o->ob_type);
981 }
982 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000983#endif /* WITHOUT_COMPLEX */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000984 else {
985 t = PyTuple_Pack(2, o, o->ob_type);
986 }
987 if (t == NULL)
988 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000990 v = PyDict_GetItem(dict, t);
991 if (!v) {
992 arg = PyDict_Size(dict);
993 v = PyInt_FromLong(arg);
994 if (!v) {
995 Py_DECREF(t);
996 return -1;
997 }
998 if (PyDict_SetItem(dict, t, v) < 0) {
999 Py_DECREF(t);
1000 Py_DECREF(v);
1001 return -1;
1002 }
1003 Py_DECREF(v);
1004 }
1005 else
1006 arg = PyInt_AsLong(v);
1007 Py_DECREF(t);
1008 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009}
1010
1011static int
1012compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001013 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001014{
1015 int arg = compiler_add_o(c, dict, o);
1016 if (arg < 0)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001017 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001018 return compiler_addop_i(c, opcode, arg);
1019}
1020
1021static int
1022compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001023 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001024{
1025 int arg;
1026 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1027 if (!mangled)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001028 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029 arg = compiler_add_o(c, dict, mangled);
1030 Py_DECREF(mangled);
1031 if (arg < 0)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001032 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033 return compiler_addop_i(c, opcode, arg);
1034}
1035
1036/* Add an opcode with an integer argument.
1037 Returns 0 on failure, 1 on success.
1038*/
1039
1040static int
1041compiler_addop_i(struct compiler *c, int opcode, int oparg)
1042{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001043 struct instr *i;
1044 int off;
1045 off = compiler_next_instr(c, c->u->u_curblock);
1046 if (off < 0)
1047 return 0;
1048 i = &c->u->u_curblock->b_instr[off];
1049 i->i_opcode = opcode;
1050 i->i_oparg = oparg;
1051 i->i_hasarg = 1;
1052 compiler_set_lineno(c, off);
1053 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054}
1055
1056static int
1057compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1058{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001059 struct instr *i;
1060 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 assert(b != NULL);
1063 off = compiler_next_instr(c, c->u->u_curblock);
1064 if (off < 0)
1065 return 0;
1066 i = &c->u->u_curblock->b_instr[off];
1067 i->i_opcode = opcode;
1068 i->i_target = b;
1069 i->i_hasarg = 1;
1070 if (absolute)
1071 i->i_jabs = 1;
1072 else
1073 i->i_jrel = 1;
1074 compiler_set_lineno(c, off);
1075 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076}
1077
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001078/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1079 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080 it as the current block. NEXT_BLOCK() also creates an implicit jump
1081 from the current block to the new block.
1082*/
1083
Neal Norwitzf733a012006-10-29 18:30:10 +00001084/* The returns inside these macros make it impossible to decref objects
1085 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086*/
1087
1088
1089#define NEW_BLOCK(C) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001090 if (compiler_use_new_block((C)) == NULL) \
1091 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092}
1093
1094#define NEXT_BLOCK(C) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001095 if (compiler_next_block((C)) == NULL) \
1096 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001097}
1098
1099#define ADDOP(C, OP) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001100 if (!compiler_addop((C), (OP))) \
1101 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001102}
1103
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001104#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001105 if (!compiler_addop((C), (OP))) { \
1106 compiler_exit_scope(c); \
1107 return 0; \
1108 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001109}
1110
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001112 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1113 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114}
1115
1116#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001117 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1118 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119}
1120
1121#define ADDOP_I(C, OP, O) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001122 if (!compiler_addop_i((C), (OP), (O))) \
1123 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124}
1125
1126#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 if (!compiler_addop_j((C), (OP), (O), 1)) \
1128 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129}
1130
1131#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001132 if (!compiler_addop_j((C), (OP), (O), 0)) \
1133 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134}
1135
1136/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1137 the ASDL name to synthesize the name of the C type and the visit function.
1138*/
1139
1140#define VISIT(C, TYPE, V) {\
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001141 if (!compiler_visit_ ## TYPE((C), (V))) \
1142 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143}
1144
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001145#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001146 if (!compiler_visit_ ## TYPE((C), (V))) { \
1147 compiler_exit_scope(c); \
1148 return 0; \
1149 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001150}
1151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 if (!compiler_visit_slice((C), (V), (CTX))) \
1154 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155}
1156
1157#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001158 int _i; \
1159 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1160 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1161 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1162 if (!compiler_visit_ ## TYPE((C), elt)) \
1163 return 0; \
1164 } \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001165}
1166
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001167#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001168 int _i; \
1169 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1170 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1171 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1172 if (!compiler_visit_ ## TYPE((C), elt)) { \
1173 compiler_exit_scope(c); \
1174 return 0; \
1175 } \
1176 } \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001177}
1178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179static int
1180compiler_isdocstring(stmt_ty s)
1181{
1182 if (s->kind != Expr_kind)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001183 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 return s->v.Expr.value->kind == Str_kind;
1185}
1186
1187/* Compile a sequence of statements, checking for a docstring. */
1188
1189static int
1190compiler_body(struct compiler *c, asdl_seq *stmts)
1191{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001192 int i = 0;
1193 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001195 if (!asdl_seq_LEN(stmts))
1196 return 1;
1197 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1198 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1199 /* don't generate docstrings if -OO */
1200 i = 1;
1201 VISIT(c, expr, st->v.Expr.value);
1202 if (!compiler_nameop(c, __doc__, Store))
1203 return 0;
1204 }
1205 for (; i < asdl_seq_LEN(stmts); i++)
1206 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1207 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208}
1209
1210static PyCodeObject *
1211compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001212{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001213 PyCodeObject *co;
1214 int addNone = 1;
1215 static PyObject *module;
1216 if (!module) {
1217 module = PyString_InternFromString("<module>");
1218 if (!module)
1219 return NULL;
1220 }
1221 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1222 if (!compiler_enter_scope(c, module, mod, 0))
1223 return NULL;
1224 switch (mod->kind) {
1225 case Module_kind:
1226 if (!compiler_body(c, mod->v.Module.body)) {
1227 compiler_exit_scope(c);
1228 return 0;
1229 }
1230 break;
1231 case Interactive_kind:
1232 c->c_interactive = 1;
1233 VISIT_SEQ_IN_SCOPE(c, stmt,
1234 mod->v.Interactive.body);
1235 break;
1236 case Expression_kind:
1237 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1238 addNone = 0;
1239 break;
1240 case Suite_kind:
1241 PyErr_SetString(PyExc_SystemError,
1242 "suite should not be possible");
1243 return 0;
1244 default:
1245 PyErr_Format(PyExc_SystemError,
1246 "module kind %d should not be possible",
1247 mod->kind);
1248 return 0;
1249 }
1250 co = assemble(c, addNone);
1251 compiler_exit_scope(c);
1252 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001253}
1254
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255/* The test for LOCAL must come before the test for FREE in order to
1256 handle classes where name is both local and free. The local var is
1257 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001258*/
1259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260static int
1261get_ref_type(struct compiler *c, PyObject *name)
1262{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001263 int scope = PyST_GetScope(c->u->u_ste, name);
1264 if (scope == 0) {
1265 char buf[350];
1266 PyOS_snprintf(buf, sizeof(buf),
1267 "unknown scope for %.100s in %.100s(%s) in %s\n"
1268 "symbols: %s\nlocals: %s\nglobals: %s",
1269 PyString_AS_STRING(name),
1270 PyString_AS_STRING(c->u->u_name),
1271 PyObject_REPR(c->u->u_ste->ste_id),
1272 c->c_filename,
1273 PyObject_REPR(c->u->u_ste->ste_symbols),
1274 PyObject_REPR(c->u->u_varnames),
1275 PyObject_REPR(c->u->u_names)
1276 );
1277 Py_FatalError(buf);
1278 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001279
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001280 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
1283static int
1284compiler_lookup_arg(PyObject *dict, PyObject *name)
1285{
1286 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001287 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288 if (k == NULL)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001289 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001291 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 if (v == NULL)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001293 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001294 return PyInt_AS_LONG(v);
1295}
1296
1297static int
1298compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1299{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001300 int i, free = PyCode_GetNumFree(co);
1301 if (free == 0) {
1302 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1303 ADDOP_I(c, MAKE_FUNCTION, args);
1304 return 1;
1305 }
1306 for (i = 0; i < free; ++i) {
1307 /* Bypass com_addop_varname because it will generate
1308 LOAD_DEREF but LOAD_CLOSURE is needed.
1309 */
1310 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1311 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001313 /* Special case: If a class contains a method with a
1314 free variable that has the same name as a method,
1315 the name will be considered free *and* local in the
1316 class. It should be handled by the closure, as
1317 well as by the normal name loookup logic.
1318 */
1319 reftype = get_ref_type(c, name);
1320 if (reftype == CELL)
1321 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1322 else /* (reftype == FREE) */
1323 arg = compiler_lookup_arg(c->u->u_freevars, name);
1324 if (arg == -1) {
1325 printf("lookup %s in %s %d %d\n"
1326 "freevars of %s: %s\n",
1327 PyObject_REPR(name),
1328 PyString_AS_STRING(c->u->u_name),
1329 reftype, arg,
1330 PyString_AS_STRING(co->co_name),
1331 PyObject_REPR(co->co_freevars));
1332 Py_FatalError("compiler_make_closure()");
1333 }
1334 ADDOP_I(c, LOAD_CLOSURE, arg);
1335 }
1336 ADDOP_I(c, BUILD_TUPLE, free);
1337 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1338 ADDOP_I(c, MAKE_CLOSURE, args);
1339 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340}
1341
1342static int
1343compiler_decorators(struct compiler *c, asdl_seq* decos)
1344{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001345 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001347 if (!decos)
1348 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001350 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1351 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1352 }
1353 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354}
1355
1356static int
1357compiler_arguments(struct compiler *c, arguments_ty args)
1358{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001359 int i;
1360 int n = asdl_seq_LEN(args->args);
1361 /* Correctly handle nested argument lists */
1362 for (i = 0; i < n; i++) {
1363 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
1364 if (arg->kind == Tuple_kind) {
1365 PyObject *id = PyString_FromFormat(".%d", i);
1366 if (id == NULL) {
1367 return 0;
1368 }
1369 if (!compiler_nameop(c, id, Load)) {
1370 Py_DECREF(id);
1371 return 0;
1372 }
1373 Py_DECREF(id);
1374 VISIT(c, expr, arg);
1375 }
1376 }
1377 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378}
1379
1380static int
1381compiler_function(struct compiler *c, stmt_ty s)
1382{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001383 PyCodeObject *co;
1384 PyObject *first_const = Py_None;
1385 arguments_ty args = s->v.FunctionDef.args;
1386 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1387 stmt_ty st;
1388 int i, n, docstring;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001390 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001392 if (!compiler_decorators(c, decos))
1393 return 0;
1394 if (args->defaults)
1395 VISIT_SEQ(c, expr, args->defaults);
1396 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1397 s->lineno))
1398 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001400 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1401 docstring = compiler_isdocstring(st);
1402 if (docstring && Py_OptimizeFlag < 2)
1403 first_const = st->v.Expr.value->v.Str.s;
1404 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1405 compiler_exit_scope(c);
1406 return 0;
1407 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001409 /* unpack nested arguments */
1410 compiler_arguments(c, args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 c->u->u_argcount = asdl_seq_LEN(args->args);
1413 n = asdl_seq_LEN(s->v.FunctionDef.body);
1414 /* if there was a docstring, we need to skip the first statement */
1415 for (i = docstring; i < n; i++) {
1416 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1417 VISIT_IN_SCOPE(c, stmt, st);
1418 }
1419 co = assemble(c, 1);
1420 compiler_exit_scope(c);
1421 if (co == NULL)
1422 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001424 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
1425 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001427 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1428 ADDOP_I(c, CALL_FUNCTION, 1);
1429 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001431 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432}
1433
1434static int
1435compiler_class(struct compiler *c, stmt_ty s)
1436{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001437 int n, i;
1438 PyCodeObject *co;
1439 PyObject *str;
1440 asdl_seq* decos = s->v.ClassDef.decorator_list;
Christian Heimes5224d282008-02-23 15:01:05 +00001441
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001442 if (!compiler_decorators(c, decos))
1443 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001445 /* push class name on stack, needed by BUILD_CLASS */
1446 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1447 /* push the tuple of base classes on the stack */
1448 n = asdl_seq_LEN(s->v.ClassDef.bases);
1449 if (n > 0)
1450 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1451 ADDOP_I(c, BUILD_TUPLE, n);
1452 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1453 s->lineno))
1454 return 0;
1455 Py_XDECREF(c->u->u_private);
1456 c->u->u_private = s->v.ClassDef.name;
1457 Py_INCREF(c->u->u_private);
1458 str = PyString_InternFromString("__name__");
1459 if (!str || !compiler_nameop(c, str, Load)) {
1460 Py_XDECREF(str);
1461 compiler_exit_scope(c);
1462 return 0;
1463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001465 Py_DECREF(str);
1466 str = PyString_InternFromString("__module__");
1467 if (!str || !compiler_nameop(c, str, Store)) {
1468 Py_XDECREF(str);
1469 compiler_exit_scope(c);
1470 return 0;
1471 }
1472 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001474 if (!compiler_body(c, s->v.ClassDef.body)) {
1475 compiler_exit_scope(c);
1476 return 0;
1477 }
Neal Norwitz4737b232005-11-19 23:58:29 +00001478
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1480 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1481 co = assemble(c, 1);
1482 compiler_exit_scope(c);
1483 if (co == NULL)
1484 return 0;
1485
1486 compiler_make_closure(c, co, 0);
1487 Py_DECREF(co);
1488
1489 ADDOP_I(c, CALL_FUNCTION, 0);
1490 ADDOP(c, BUILD_CLASS);
1491 /* apply decorators */
1492 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1493 ADDOP_I(c, CALL_FUNCTION, 1);
1494 }
1495 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1496 return 0;
1497 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001501compiler_ifexp(struct compiler *c, expr_ty e)
1502{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001503 basicblock *end, *next;
1504
1505 assert(e->kind == IfExp_kind);
1506 end = compiler_new_block(c);
1507 if (end == NULL)
1508 return 0;
1509 next = compiler_new_block(c);
1510 if (next == NULL)
1511 return 0;
1512 VISIT(c, expr, e->v.IfExp.test);
1513 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1514 VISIT(c, expr, e->v.IfExp.body);
1515 ADDOP_JREL(c, JUMP_FORWARD, end);
1516 compiler_use_next_block(c, next);
1517 VISIT(c, expr, e->v.IfExp.orelse);
1518 compiler_use_next_block(c, end);
1519 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001520}
1521
1522static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523compiler_lambda(struct compiler *c, expr_ty e)
1524{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001525 PyCodeObject *co;
1526 static identifier name;
1527 arguments_ty args = e->v.Lambda.args;
1528 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001530 if (!name) {
1531 name = PyString_InternFromString("<lambda>");
1532 if (!name)
1533 return 0;
1534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001536 if (args->defaults)
1537 VISIT_SEQ(c, expr, args->defaults);
1538 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1539 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001540
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001541 /* unpack nested arguments */
1542 compiler_arguments(c, args);
Benjamin Peterson0dee9c12010-03-17 20:41:42 +00001543
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001544 /* Make None the first constant, so the lambda can't have a
1545 docstring. */
1546 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1547 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001549 c->u->u_argcount = asdl_seq_LEN(args->args);
1550 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1551 if (c->u->u_ste->ste_generator) {
1552 ADDOP_IN_SCOPE(c, POP_TOP);
1553 }
1554 else {
1555 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1556 }
1557 co = assemble(c, 1);
1558 compiler_exit_scope(c);
1559 if (co == NULL)
1560 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001562 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
1563 Py_DECREF(co);
1564
1565 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566}
1567
1568static int
1569compiler_print(struct compiler *c, stmt_ty s)
1570{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001571 int i, n;
1572 bool dest;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001574 assert(s->kind == Print_kind);
1575 n = asdl_seq_LEN(s->v.Print.values);
1576 dest = false;
1577 if (s->v.Print.dest) {
1578 VISIT(c, expr, s->v.Print.dest);
1579 dest = true;
1580 }
1581 for (i = 0; i < n; i++) {
1582 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1583 if (dest) {
1584 ADDOP(c, DUP_TOP);
1585 VISIT(c, expr, e);
1586 ADDOP(c, ROT_TWO);
1587 ADDOP(c, PRINT_ITEM_TO);
1588 }
1589 else {
1590 VISIT(c, expr, e);
1591 ADDOP(c, PRINT_ITEM);
1592 }
1593 }
1594 if (s->v.Print.nl) {
1595 if (dest)
1596 ADDOP(c, PRINT_NEWLINE_TO)
1597 else
1598 ADDOP(c, PRINT_NEWLINE)
1599 }
1600 else if (dest)
1601 ADDOP(c, POP_TOP);
1602 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603}
1604
1605static int
1606compiler_if(struct compiler *c, stmt_ty s)
1607{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001608 basicblock *end, *next;
1609 int constant;
1610 assert(s->kind == If_kind);
1611 end = compiler_new_block(c);
1612 if (end == NULL)
1613 return 0;
1614
1615 constant = expr_constant(s->v.If.test);
1616 /* constant = 0: "if 0"
1617 * constant = 1: "if 1", "if 2", ...
1618 * constant = -1: rest */
1619 if (constant == 0) {
1620 if (s->v.If.orelse)
1621 VISIT_SEQ(c, stmt, s->v.If.orelse);
1622 } else if (constant == 1) {
1623 VISIT_SEQ(c, stmt, s->v.If.body);
1624 } else {
1625 if (s->v.If.orelse) {
1626 next = compiler_new_block(c);
1627 if (next == NULL)
1628 return 0;
1629 }
1630 else
1631 next = end;
1632 VISIT(c, expr, s->v.If.test);
1633 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1634 VISIT_SEQ(c, stmt, s->v.If.body);
1635 ADDOP_JREL(c, JUMP_FORWARD, end);
1636 if (s->v.If.orelse) {
1637 compiler_use_next_block(c, next);
1638 VISIT_SEQ(c, stmt, s->v.If.orelse);
1639 }
1640 }
1641 compiler_use_next_block(c, end);
1642 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643}
1644
1645static int
1646compiler_for(struct compiler *c, stmt_ty s)
1647{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001648 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001650 start = compiler_new_block(c);
1651 cleanup = compiler_new_block(c);
1652 end = compiler_new_block(c);
1653 if (start == NULL || end == NULL || cleanup == NULL)
1654 return 0;
1655 ADDOP_JREL(c, SETUP_LOOP, end);
1656 if (!compiler_push_fblock(c, LOOP, start))
1657 return 0;
1658 VISIT(c, expr, s->v.For.iter);
1659 ADDOP(c, GET_ITER);
1660 compiler_use_next_block(c, start);
1661 ADDOP_JREL(c, FOR_ITER, cleanup);
1662 VISIT(c, expr, s->v.For.target);
1663 VISIT_SEQ(c, stmt, s->v.For.body);
1664 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1665 compiler_use_next_block(c, cleanup);
1666 ADDOP(c, POP_BLOCK);
1667 compiler_pop_fblock(c, LOOP, start);
1668 VISIT_SEQ(c, stmt, s->v.For.orelse);
1669 compiler_use_next_block(c, end);
1670 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001671}
1672
1673static int
1674compiler_while(struct compiler *c, stmt_ty s)
1675{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001676 basicblock *loop, *orelse, *end, *anchor = NULL;
1677 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001679 if (constant == 0) {
1680 if (s->v.While.orelse)
1681 VISIT_SEQ(c, stmt, s->v.While.orelse);
1682 return 1;
1683 }
1684 loop = compiler_new_block(c);
1685 end = compiler_new_block(c);
1686 if (constant == -1) {
1687 anchor = compiler_new_block(c);
1688 if (anchor == NULL)
1689 return 0;
1690 }
1691 if (loop == NULL || end == NULL)
1692 return 0;
1693 if (s->v.While.orelse) {
1694 orelse = compiler_new_block(c);
1695 if (orelse == NULL)
1696 return 0;
1697 }
1698 else
1699 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001701 ADDOP_JREL(c, SETUP_LOOP, end);
1702 compiler_use_next_block(c, loop);
1703 if (!compiler_push_fblock(c, LOOP, loop))
1704 return 0;
1705 if (constant == -1) {
1706 VISIT(c, expr, s->v.While.test);
1707 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1708 }
1709 VISIT_SEQ(c, stmt, s->v.While.body);
1710 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001711
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001712 /* XXX should the two POP instructions be in a separate block
1713 if there is no else clause ?
1714 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001716 if (constant == -1) {
1717 compiler_use_next_block(c, anchor);
1718 ADDOP(c, POP_BLOCK);
1719 }
1720 compiler_pop_fblock(c, LOOP, loop);
1721 if (orelse != NULL) /* what if orelse is just pass? */
1722 VISIT_SEQ(c, stmt, s->v.While.orelse);
1723 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001725 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726}
1727
1728static int
1729compiler_continue(struct compiler *c)
1730{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001731 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1732 static const char IN_FINALLY_ERROR_MSG[] =
1733 "'continue' not supported inside 'finally' clause";
1734 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001736 if (!c->u->u_nfblocks)
1737 return compiler_error(c, LOOP_ERROR_MSG);
1738 i = c->u->u_nfblocks - 1;
1739 switch (c->u->u_fblock[i].fb_type) {
1740 case LOOP:
1741 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1742 break;
1743 case EXCEPT:
1744 case FINALLY_TRY:
1745 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1746 /* Prevent continue anywhere under a finally
1747 even if hidden in a sub-try or except. */
1748 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1749 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1750 }
1751 if (i == -1)
1752 return compiler_error(c, LOOP_ERROR_MSG);
1753 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1754 break;
1755 case FINALLY_END:
1756 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1757 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001759 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760}
1761
1762/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001763
1764 SETUP_FINALLY L
1765 <code for body>
1766 POP_BLOCK
1767 LOAD_CONST <None>
1768 L: <code for finalbody>
1769 END_FINALLY
1770
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001771 The special instructions use the block stack. Each block
1772 stack entry contains the instruction that created it (here
1773 SETUP_FINALLY), the level of the value stack at the time the
1774 block stack entry was created, and a label (here L).
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776 SETUP_FINALLY:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001777 Pushes the current value stack level and the label
1778 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779 POP_BLOCK:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001780 Pops en entry from the block stack, and pops the value
1781 stack until its level is the same as indicated on the
1782 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783 END_FINALLY:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001784 Pops a variable number of entries from the *value* stack
1785 and re-raises the exception they specify. The number of
1786 entries popped depends on the (pseudo) exception type.
1787
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788 The block stack is unwound when an exception is raised:
1789 when a SETUP_FINALLY entry is found, the exception is pushed
1790 onto the value stack (and the exception condition is cleared),
1791 and the interpreter jumps to the label gotten from the block
1792 stack.
1793*/
1794
1795static int
1796compiler_try_finally(struct compiler *c, stmt_ty s)
1797{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001798 basicblock *body, *end;
1799 body = compiler_new_block(c);
1800 end = compiler_new_block(c);
1801 if (body == NULL || end == NULL)
1802 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001804 ADDOP_JREL(c, SETUP_FINALLY, end);
1805 compiler_use_next_block(c, body);
1806 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1807 return 0;
1808 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1809 ADDOP(c, POP_BLOCK);
1810 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001812 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1813 compiler_use_next_block(c, end);
1814 if (!compiler_push_fblock(c, FINALLY_END, end))
1815 return 0;
1816 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1817 ADDOP(c, END_FINALLY);
1818 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001820 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821}
1822
1823/*
1824 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1825 (The contents of the value stack is shown in [], with the top
1826 at the right; 'tb' is trace-back info, 'val' the exception's
1827 associated value, and 'exc' the exception.)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001828
1829 Value stack Label Instruction Argument
1830 [] SETUP_EXCEPT L1
1831 [] <code for S>
1832 [] POP_BLOCK
1833 [] JUMP_FORWARD L0
1834
1835 [tb, val, exc] L1: DUP )
1836 [tb, val, exc, exc] <evaluate E1> )
1837 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1838 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1839 [tb, val, exc] POP
1840 [tb, val] <assign to V1> (or POP if no V1)
1841 [tb] POP
1842 [] <code for S1>
1843 JUMP_FORWARD L0
1844
1845 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846 .............................etc.......................
1847
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001848 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1849
1850 [] L0: <next statement>
1851
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852 Of course, parts are not generated if Vi or Ei is not present.
1853*/
1854static int
1855compiler_try_except(struct compiler *c, stmt_ty s)
1856{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001857 basicblock *body, *orelse, *except, *end;
1858 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001860 body = compiler_new_block(c);
1861 except = compiler_new_block(c);
1862 orelse = compiler_new_block(c);
1863 end = compiler_new_block(c);
1864 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1865 return 0;
1866 ADDOP_JREL(c, SETUP_EXCEPT, except);
1867 compiler_use_next_block(c, body);
1868 if (!compiler_push_fblock(c, EXCEPT, body))
1869 return 0;
1870 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1871 ADDOP(c, POP_BLOCK);
1872 compiler_pop_fblock(c, EXCEPT, body);
1873 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1874 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1875 compiler_use_next_block(c, except);
1876 for (i = 0; i < n; i++) {
1877 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1878 s->v.TryExcept.handlers, i);
1879 if (!handler->v.ExceptHandler.type && i < n-1)
1880 return compiler_error(c, "default 'except:' must be last");
1881 c->u->u_lineno_set = false;
1882 c->u->u_lineno = handler->lineno;
1883 except = compiler_new_block(c);
1884 if (except == NULL)
1885 return 0;
1886 if (handler->v.ExceptHandler.type) {
1887 ADDOP(c, DUP_TOP);
1888 VISIT(c, expr, handler->v.ExceptHandler.type);
1889 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1890 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
1891 }
1892 ADDOP(c, POP_TOP);
1893 if (handler->v.ExceptHandler.name) {
1894 VISIT(c, expr, handler->v.ExceptHandler.name);
1895 }
1896 else {
1897 ADDOP(c, POP_TOP);
1898 }
1899 ADDOP(c, POP_TOP);
1900 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
1901 ADDOP_JREL(c, JUMP_FORWARD, end);
1902 compiler_use_next_block(c, except);
1903 }
1904 ADDOP(c, END_FINALLY);
1905 compiler_use_next_block(c, orelse);
1906 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1907 compiler_use_next_block(c, end);
1908 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909}
1910
1911static int
1912compiler_import_as(struct compiler *c, identifier name, identifier asname)
1913{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001914 /* The IMPORT_NAME opcode was already generated. This function
1915 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001917 If there is a dot in name, we need to split it and emit a
1918 LOAD_ATTR for each name.
1919 */
1920 const char *src = PyString_AS_STRING(name);
1921 const char *dot = strchr(src, '.');
1922 if (dot) {
1923 /* Consume the base module name to get the first attribute */
1924 src = dot + 1;
1925 while (dot) {
1926 /* NB src is only defined when dot != NULL */
1927 PyObject *attr;
1928 dot = strchr(src, '.');
1929 attr = PyString_FromStringAndSize(src,
1930 dot ? dot - src : strlen(src));
1931 if (!attr)
1932 return -1;
1933 ADDOP_O(c, LOAD_ATTR, attr, names);
1934 Py_DECREF(attr);
1935 src = dot + 1;
1936 }
1937 }
1938 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939}
1940
1941static int
1942compiler_import(struct compiler *c, stmt_ty s)
1943{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001944 /* The Import node stores a module name like a.b.c as a single
1945 string. This is convenient for all cases except
1946 import a.b.c as d
1947 where we need to parse that string to extract the individual
1948 module names.
1949 XXX Perhaps change the representation to make this case simpler?
1950 */
1951 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001952
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001953 for (i = 0; i < n; i++) {
1954 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
1955 int r;
1956 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001958 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
1959 level = PyInt_FromLong(0);
1960 else
1961 level = PyInt_FromLong(-1);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001962
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001963 if (level == NULL)
1964 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001965
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001966 ADDOP_O(c, LOAD_CONST, level, consts);
1967 Py_DECREF(level);
1968 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1969 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001971 if (alias->asname) {
1972 r = compiler_import_as(c, alias->name, alias->asname);
1973 if (!r)
1974 return r;
1975 }
1976 else {
1977 identifier tmp = alias->name;
1978 const char *base = PyString_AS_STRING(alias->name);
1979 char *dot = strchr(base, '.');
1980 if (dot)
1981 tmp = PyString_FromStringAndSize(base,
1982 dot - base);
1983 r = compiler_nameop(c, tmp, Store);
1984 if (dot) {
1985 Py_DECREF(tmp);
1986 }
1987 if (!r)
1988 return r;
1989 }
1990 }
1991 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992}
1993
1994static int
1995compiler_from_import(struct compiler *c, stmt_ty s)
1996{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001997 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001999 PyObject *names = PyTuple_New(n);
2000 PyObject *level;
2001 static PyObject *empty_string;
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002002
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002003 if (!empty_string) {
2004 empty_string = PyString_FromString("");
2005 if (!empty_string)
2006 return 0;
2007 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002009 if (!names)
2010 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002011
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002012 if (s->v.ImportFrom.level == 0 && c->c_flags &&
2013 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
2014 level = PyInt_FromLong(-1);
2015 else
2016 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002017
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002018 if (!level) {
2019 Py_DECREF(names);
2020 return 0;
2021 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002023 /* build up the names */
2024 for (i = 0; i < n; i++) {
2025 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2026 Py_INCREF(alias->name);
2027 PyTuple_SET_ITEM(names, i, alias->name);
2028 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002030 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2031 !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
2032 Py_DECREF(level);
2033 Py_DECREF(names);
2034 return compiler_error(c, "from __future__ imports must occur "
2035 "at the beginning of the file");
2036 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002038 ADDOP_O(c, LOAD_CONST, level, consts);
2039 Py_DECREF(level);
2040 ADDOP_O(c, LOAD_CONST, names, consts);
2041 Py_DECREF(names);
2042 if (s->v.ImportFrom.module) {
2043 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2044 }
2045 else {
2046 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2047 }
2048 for (i = 0; i < n; i++) {
2049 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2050 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002052 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2053 assert(n == 1);
2054 ADDOP(c, IMPORT_STAR);
2055 return 1;
2056 }
2057
2058 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2059 store_name = alias->name;
2060 if (alias->asname)
2061 store_name = alias->asname;
2062
2063 if (!compiler_nameop(c, store_name, Store)) {
2064 Py_DECREF(names);
2065 return 0;
2066 }
2067 }
2068 /* remove imported module */
2069 ADDOP(c, POP_TOP);
2070 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071}
2072
2073static int
2074compiler_assert(struct compiler *c, stmt_ty s)
2075{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002076 static PyObject *assertion_error = NULL;
2077 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002079 if (Py_OptimizeFlag)
2080 return 1;
2081 if (assertion_error == NULL) {
2082 assertion_error = PyString_InternFromString("AssertionError");
2083 if (assertion_error == NULL)
2084 return 0;
2085 }
2086 if (s->v.Assert.test->kind == Tuple_kind &&
2087 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2088 const char* msg =
2089 "assertion is always true, perhaps remove parentheses?";
2090 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2091 c->u->u_lineno, NULL, NULL) == -1)
2092 return 0;
2093 }
2094 VISIT(c, expr, s->v.Assert.test);
2095 end = compiler_new_block(c);
2096 if (end == NULL)
2097 return 0;
2098 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2099 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2100 if (s->v.Assert.msg) {
2101 VISIT(c, expr, s->v.Assert.msg);
Benjamin Peterson0c0d7562011-10-27 08:21:59 -04002102 ADDOP_I(c, CALL_FUNCTION, 1);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002103 }
Benjamin Peterson0c0d7562011-10-27 08:21:59 -04002104 ADDOP_I(c, RAISE_VARARGS, 1);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002105 compiler_use_next_block(c, end);
2106 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107}
2108
2109static int
2110compiler_visit_stmt(struct compiler *c, stmt_ty s)
2111{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002112 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002114 /* Always assign a lineno to the next instruction for a stmt. */
2115 c->u->u_lineno = s->lineno;
2116 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 switch (s->kind) {
2119 case FunctionDef_kind:
2120 return compiler_function(c, s);
2121 case ClassDef_kind:
2122 return compiler_class(c, s);
2123 case Return_kind:
2124 if (c->u->u_ste->ste_type != FunctionBlock)
2125 return compiler_error(c, "'return' outside function");
2126 if (s->v.Return.value) {
2127 VISIT(c, expr, s->v.Return.value);
2128 }
2129 else
2130 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2131 ADDOP(c, RETURN_VALUE);
2132 break;
2133 case Delete_kind:
2134 VISIT_SEQ(c, expr, s->v.Delete.targets)
2135 break;
2136 case Assign_kind:
2137 n = asdl_seq_LEN(s->v.Assign.targets);
2138 VISIT(c, expr, s->v.Assign.value);
2139 for (i = 0; i < n; i++) {
2140 if (i < n - 1)
2141 ADDOP(c, DUP_TOP);
2142 VISIT(c, expr,
2143 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2144 }
2145 break;
2146 case AugAssign_kind:
2147 return compiler_augassign(c, s);
2148 case Print_kind:
2149 return compiler_print(c, s);
2150 case For_kind:
2151 return compiler_for(c, s);
2152 case While_kind:
2153 return compiler_while(c, s);
2154 case If_kind:
2155 return compiler_if(c, s);
2156 case Raise_kind:
2157 n = 0;
2158 if (s->v.Raise.type) {
2159 VISIT(c, expr, s->v.Raise.type);
2160 n++;
2161 if (s->v.Raise.inst) {
2162 VISIT(c, expr, s->v.Raise.inst);
2163 n++;
2164 if (s->v.Raise.tback) {
2165 VISIT(c, expr, s->v.Raise.tback);
2166 n++;
2167 }
2168 }
2169 }
2170 ADDOP_I(c, RAISE_VARARGS, n);
2171 break;
2172 case TryExcept_kind:
2173 return compiler_try_except(c, s);
2174 case TryFinally_kind:
2175 return compiler_try_finally(c, s);
2176 case Assert_kind:
2177 return compiler_assert(c, s);
2178 case Import_kind:
2179 return compiler_import(c, s);
2180 case ImportFrom_kind:
2181 return compiler_from_import(c, s);
2182 case Exec_kind:
2183 VISIT(c, expr, s->v.Exec.body);
2184 if (s->v.Exec.globals) {
2185 VISIT(c, expr, s->v.Exec.globals);
2186 if (s->v.Exec.locals) {
2187 VISIT(c, expr, s->v.Exec.locals);
2188 } else {
2189 ADDOP(c, DUP_TOP);
2190 }
2191 } else {
2192 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2193 ADDOP(c, DUP_TOP);
2194 }
2195 ADDOP(c, EXEC_STMT);
2196 break;
2197 case Global_kind:
2198 break;
2199 case Expr_kind:
2200 if (c->c_interactive && c->c_nestlevel <= 1) {
2201 VISIT(c, expr, s->v.Expr.value);
2202 ADDOP(c, PRINT_EXPR);
2203 }
2204 else if (s->v.Expr.value->kind != Str_kind &&
2205 s->v.Expr.value->kind != Num_kind) {
2206 VISIT(c, expr, s->v.Expr.value);
2207 ADDOP(c, POP_TOP);
2208 }
2209 break;
2210 case Pass_kind:
2211 break;
2212 case Break_kind:
2213 if (!compiler_in_loop(c))
2214 return compiler_error(c, "'break' outside loop");
2215 ADDOP(c, BREAK_LOOP);
2216 break;
2217 case Continue_kind:
2218 return compiler_continue(c);
2219 case With_kind:
2220 return compiler_with(c, s);
2221 }
2222 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223}
2224
2225static int
2226unaryop(unaryop_ty op)
2227{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002228 switch (op) {
2229 case Invert:
2230 return UNARY_INVERT;
2231 case Not:
2232 return UNARY_NOT;
2233 case UAdd:
2234 return UNARY_POSITIVE;
2235 case USub:
2236 return UNARY_NEGATIVE;
2237 default:
2238 PyErr_Format(PyExc_SystemError,
2239 "unary op %d should not be possible", op);
2240 return 0;
2241 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242}
2243
2244static int
2245binop(struct compiler *c, operator_ty op)
2246{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002247 switch (op) {
2248 case Add:
2249 return BINARY_ADD;
2250 case Sub:
2251 return BINARY_SUBTRACT;
2252 case Mult:
2253 return BINARY_MULTIPLY;
2254 case Div:
2255 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2256 return BINARY_TRUE_DIVIDE;
2257 else
2258 return BINARY_DIVIDE;
2259 case Mod:
2260 return BINARY_MODULO;
2261 case Pow:
2262 return BINARY_POWER;
2263 case LShift:
2264 return BINARY_LSHIFT;
2265 case RShift:
2266 return BINARY_RSHIFT;
2267 case BitOr:
2268 return BINARY_OR;
2269 case BitXor:
2270 return BINARY_XOR;
2271 case BitAnd:
2272 return BINARY_AND;
2273 case FloorDiv:
2274 return BINARY_FLOOR_DIVIDE;
2275 default:
2276 PyErr_Format(PyExc_SystemError,
2277 "binary op %d should not be possible", op);
2278 return 0;
2279 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280}
2281
2282static int
2283cmpop(cmpop_ty op)
2284{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002285 switch (op) {
2286 case Eq:
2287 return PyCmp_EQ;
2288 case NotEq:
2289 return PyCmp_NE;
2290 case Lt:
2291 return PyCmp_LT;
2292 case LtE:
2293 return PyCmp_LE;
2294 case Gt:
2295 return PyCmp_GT;
2296 case GtE:
2297 return PyCmp_GE;
2298 case Is:
2299 return PyCmp_IS;
2300 case IsNot:
2301 return PyCmp_IS_NOT;
2302 case In:
2303 return PyCmp_IN;
2304 case NotIn:
2305 return PyCmp_NOT_IN;
2306 default:
2307 return PyCmp_BAD;
2308 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309}
2310
2311static int
2312inplace_binop(struct compiler *c, operator_ty op)
2313{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002314 switch (op) {
2315 case Add:
2316 return INPLACE_ADD;
2317 case Sub:
2318 return INPLACE_SUBTRACT;
2319 case Mult:
2320 return INPLACE_MULTIPLY;
2321 case Div:
2322 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2323 return INPLACE_TRUE_DIVIDE;
2324 else
2325 return INPLACE_DIVIDE;
2326 case Mod:
2327 return INPLACE_MODULO;
2328 case Pow:
2329 return INPLACE_POWER;
2330 case LShift:
2331 return INPLACE_LSHIFT;
2332 case RShift:
2333 return INPLACE_RSHIFT;
2334 case BitOr:
2335 return INPLACE_OR;
2336 case BitXor:
2337 return INPLACE_XOR;
2338 case BitAnd:
2339 return INPLACE_AND;
2340 case FloorDiv:
2341 return INPLACE_FLOOR_DIVIDE;
2342 default:
2343 PyErr_Format(PyExc_SystemError,
2344 "inplace binary op %d should not be possible", op);
2345 return 0;
2346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347}
2348
2349static int
2350compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2351{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002352 int op, scope, arg;
2353 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002355 PyObject *dict = c->u->u_names;
2356 PyObject *mangled;
2357 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002359 mangled = _Py_Mangle(c->u->u_private, name);
2360 if (!mangled)
2361 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002363 op = 0;
2364 optype = OP_NAME;
2365 scope = PyST_GetScope(c->u->u_ste, mangled);
2366 switch (scope) {
2367 case FREE:
2368 dict = c->u->u_freevars;
2369 optype = OP_DEREF;
2370 break;
2371 case CELL:
2372 dict = c->u->u_cellvars;
2373 optype = OP_DEREF;
2374 break;
2375 case LOCAL:
2376 if (c->u->u_ste->ste_type == FunctionBlock)
2377 optype = OP_FAST;
2378 break;
2379 case GLOBAL_IMPLICIT:
2380 if (c->u->u_ste->ste_type == FunctionBlock &&
2381 !c->u->u_ste->ste_unoptimized)
2382 optype = OP_GLOBAL;
2383 break;
2384 case GLOBAL_EXPLICIT:
2385 optype = OP_GLOBAL;
2386 break;
2387 default:
2388 /* scope can be 0 */
2389 break;
2390 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002392 /* XXX Leave assert here, but handle __doc__ and the like better */
2393 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002395 switch (optype) {
2396 case OP_DEREF:
2397 switch (ctx) {
2398 case Load: op = LOAD_DEREF; break;
2399 case Store: op = STORE_DEREF; break;
2400 case AugLoad:
2401 case AugStore:
2402 break;
2403 case Del:
2404 PyErr_Format(PyExc_SyntaxError,
2405 "can not delete variable '%s' referenced "
2406 "in nested scope",
2407 PyString_AS_STRING(name));
2408 Py_DECREF(mangled);
2409 return 0;
2410 case Param:
2411 default:
2412 PyErr_SetString(PyExc_SystemError,
2413 "param invalid for deref variable");
2414 return 0;
2415 }
2416 break;
2417 case OP_FAST:
2418 switch (ctx) {
2419 case Load: op = LOAD_FAST; break;
2420 case Store: op = STORE_FAST; break;
2421 case Del: op = DELETE_FAST; break;
2422 case AugLoad:
2423 case AugStore:
2424 break;
2425 case Param:
2426 default:
2427 PyErr_SetString(PyExc_SystemError,
2428 "param invalid for local variable");
2429 return 0;
2430 }
2431 ADDOP_O(c, op, mangled, varnames);
2432 Py_DECREF(mangled);
2433 return 1;
2434 case OP_GLOBAL:
2435 switch (ctx) {
2436 case Load: op = LOAD_GLOBAL; break;
2437 case Store: op = STORE_GLOBAL; break;
2438 case Del: op = DELETE_GLOBAL; break;
2439 case AugLoad:
2440 case AugStore:
2441 break;
2442 case Param:
2443 default:
2444 PyErr_SetString(PyExc_SystemError,
2445 "param invalid for global variable");
2446 return 0;
2447 }
2448 break;
2449 case OP_NAME:
2450 switch (ctx) {
2451 case Load: op = LOAD_NAME; break;
2452 case Store: op = STORE_NAME; break;
2453 case Del: op = DELETE_NAME; break;
2454 case AugLoad:
2455 case AugStore:
2456 break;
2457 case Param:
2458 default:
2459 PyErr_SetString(PyExc_SystemError,
2460 "param invalid for name variable");
2461 return 0;
2462 }
2463 break;
2464 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002466 assert(op);
2467 arg = compiler_add_o(c, dict, mangled);
2468 Py_DECREF(mangled);
2469 if (arg < 0)
2470 return 0;
2471 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472}
2473
2474static int
2475compiler_boolop(struct compiler *c, expr_ty e)
2476{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002477 basicblock *end;
2478 int jumpi, i, n;
2479 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002481 assert(e->kind == BoolOp_kind);
2482 if (e->v.BoolOp.op == And)
2483 jumpi = JUMP_IF_FALSE_OR_POP;
2484 else
2485 jumpi = JUMP_IF_TRUE_OR_POP;
2486 end = compiler_new_block(c);
2487 if (end == NULL)
2488 return 0;
2489 s = e->v.BoolOp.values;
2490 n = asdl_seq_LEN(s) - 1;
2491 assert(n >= 0);
2492 for (i = 0; i < n; ++i) {
2493 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2494 ADDOP_JABS(c, jumpi, end);
2495 }
2496 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2497 compiler_use_next_block(c, end);
2498 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499}
2500
2501static int
2502compiler_list(struct compiler *c, expr_ty e)
2503{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002504 int n = asdl_seq_LEN(e->v.List.elts);
2505 if (e->v.List.ctx == Store) {
2506 ADDOP_I(c, UNPACK_SEQUENCE, n);
2507 }
2508 VISIT_SEQ(c, expr, e->v.List.elts);
2509 if (e->v.List.ctx == Load) {
2510 ADDOP_I(c, BUILD_LIST, n);
2511 }
2512 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513}
2514
2515static int
2516compiler_tuple(struct compiler *c, expr_ty e)
2517{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002518 int n = asdl_seq_LEN(e->v.Tuple.elts);
2519 if (e->v.Tuple.ctx == Store) {
2520 ADDOP_I(c, UNPACK_SEQUENCE, n);
2521 }
2522 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2523 if (e->v.Tuple.ctx == Load) {
2524 ADDOP_I(c, BUILD_TUPLE, n);
2525 }
2526 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527}
2528
2529static int
2530compiler_compare(struct compiler *c, expr_ty e)
2531{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002532 int i, n;
2533 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002535 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2536 VISIT(c, expr, e->v.Compare.left);
2537 n = asdl_seq_LEN(e->v.Compare.ops);
2538 assert(n > 0);
2539 if (n > 1) {
2540 cleanup = compiler_new_block(c);
2541 if (cleanup == NULL)
2542 return 0;
2543 VISIT(c, expr,
2544 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2545 }
2546 for (i = 1; i < n; i++) {
2547 ADDOP(c, DUP_TOP);
2548 ADDOP(c, ROT_THREE);
2549 ADDOP_I(c, COMPARE_OP,
2550 cmpop((cmpop_ty)(asdl_seq_GET(
2551 e->v.Compare.ops, i - 1))));
2552 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2553 NEXT_BLOCK(c);
2554 if (i < (n - 1))
2555 VISIT(c, expr,
2556 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2557 }
2558 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2559 ADDOP_I(c, COMPARE_OP,
2560 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2561 if (n > 1) {
2562 basicblock *end = compiler_new_block(c);
2563 if (end == NULL)
2564 return 0;
2565 ADDOP_JREL(c, JUMP_FORWARD, end);
2566 compiler_use_next_block(c, cleanup);
2567 ADDOP(c, ROT_TWO);
2568 ADDOP(c, POP_TOP);
2569 compiler_use_next_block(c, end);
2570 }
2571 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572}
2573
2574static int
2575compiler_call(struct compiler *c, expr_ty e)
2576{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002577 int n, code = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002579 VISIT(c, expr, e->v.Call.func);
2580 n = asdl_seq_LEN(e->v.Call.args);
2581 VISIT_SEQ(c, expr, e->v.Call.args);
2582 if (e->v.Call.keywords) {
2583 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2584 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2585 }
2586 if (e->v.Call.starargs) {
2587 VISIT(c, expr, e->v.Call.starargs);
2588 code |= 1;
2589 }
2590 if (e->v.Call.kwargs) {
2591 VISIT(c, expr, e->v.Call.kwargs);
2592 code |= 2;
2593 }
2594 switch (code) {
2595 case 0:
2596 ADDOP_I(c, CALL_FUNCTION, n);
2597 break;
2598 case 1:
2599 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2600 break;
2601 case 2:
2602 ADDOP_I(c, CALL_FUNCTION_KW, n);
2603 break;
2604 case 3:
2605 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2606 break;
2607 }
2608 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609}
2610
2611static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002612compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002613 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002615 /* generate code for the iterator, then each of the ifs,
2616 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002618 comprehension_ty l;
2619 basicblock *start, *anchor, *skip, *if_cleanup;
2620 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002622 start = compiler_new_block(c);
2623 skip = compiler_new_block(c);
2624 if_cleanup = compiler_new_block(c);
2625 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002627 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2628 anchor == NULL)
2629 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002631 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
2632 VISIT(c, expr, l->iter);
2633 ADDOP(c, GET_ITER);
2634 compiler_use_next_block(c, start);
2635 ADDOP_JREL(c, FOR_ITER, anchor);
2636 NEXT_BLOCK(c);
2637 VISIT(c, expr, l->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002639 /* XXX this needs to be cleaned up...a lot! */
2640 n = asdl_seq_LEN(l->ifs);
2641 for (i = 0; i < n; i++) {
2642 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
2643 VISIT(c, expr, e);
2644 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2645 NEXT_BLOCK(c);
2646 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002648 if (++gen_index < asdl_seq_LEN(generators))
2649 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
2650 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002652 /* only append after the last for generator */
2653 if (gen_index >= asdl_seq_LEN(generators)) {
2654 VISIT(c, expr, elt);
2655 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002657 compiler_use_next_block(c, skip);
2658 }
2659 compiler_use_next_block(c, if_cleanup);
2660 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2661 compiler_use_next_block(c, anchor);
2662
2663 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664}
2665
2666static int
2667compiler_listcomp(struct compiler *c, expr_ty e)
2668{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002669 assert(e->kind == ListComp_kind);
2670 ADDOP_I(c, BUILD_LIST, 0);
2671 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2672 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673}
2674
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002675/* Dict and set comprehensions and generator expressions work by creating a
2676 nested function to perform the actual iteration. This means that the
2677 iteration variables don't leak into the current scope.
2678 The defined function is called immediately following its definition, with the
2679 result of that call being the result of the expression.
2680 The LC/SC version returns the populated container, while the GE version is
2681 flagged in symtable.c as a generator, so it returns the generator object
2682 when the function is called.
2683 This code *knows* that the loop cannot contain break, continue, or return,
2684 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2685
2686 Possible cleanups:
2687 - iterate over the generator sequence instead of using recursion
2688*/
2689
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690static int
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002691compiler_comprehension_generator(struct compiler *c,
2692 asdl_seq *generators, int gen_index,
2693 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002695 /* generate code for the iterator, then each of the ifs,
2696 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002698 comprehension_ty gen;
2699 basicblock *start, *anchor, *skip, *if_cleanup;
2700 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002702 start = compiler_new_block(c);
2703 skip = compiler_new_block(c);
2704 if_cleanup = compiler_new_block(c);
2705 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002707 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2708 anchor == NULL)
2709 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002711 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002713 if (gen_index == 0) {
2714 /* Receive outermost iter as an implicit argument */
2715 c->u->u_argcount = 1;
2716 ADDOP_I(c, LOAD_FAST, 0);
2717 }
2718 else {
2719 /* Sub-iter - calculate on the fly */
2720 VISIT(c, expr, gen->iter);
2721 ADDOP(c, GET_ITER);
2722 }
2723 compiler_use_next_block(c, start);
2724 ADDOP_JREL(c, FOR_ITER, anchor);
2725 NEXT_BLOCK(c);
2726 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002728 /* XXX this needs to be cleaned up...a lot! */
2729 n = asdl_seq_LEN(gen->ifs);
2730 for (i = 0; i < n; i++) {
2731 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2732 VISIT(c, expr, e);
2733 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2734 NEXT_BLOCK(c);
2735 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002737 if (++gen_index < asdl_seq_LEN(generators))
2738 if (!compiler_comprehension_generator(c,
2739 generators, gen_index,
2740 elt, val, type))
2741 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002743 /* only append after the last for generator */
2744 if (gen_index >= asdl_seq_LEN(generators)) {
2745 /* comprehension specific code */
2746 switch (type) {
2747 case COMP_GENEXP:
2748 VISIT(c, expr, elt);
2749 ADDOP(c, YIELD_VALUE);
2750 ADDOP(c, POP_TOP);
2751 break;
2752 case COMP_SETCOMP:
2753 VISIT(c, expr, elt);
2754 ADDOP_I(c, SET_ADD, gen_index + 1);
2755 break;
2756 case COMP_DICTCOMP:
2757 /* With 'd[k] = v', v is evaluated before k, so we do
2758 the same. */
2759 VISIT(c, expr, val);
2760 VISIT(c, expr, elt);
2761 ADDOP_I(c, MAP_ADD, gen_index + 1);
2762 break;
2763 default:
2764 return 0;
2765 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002767 compiler_use_next_block(c, skip);
2768 }
2769 compiler_use_next_block(c, if_cleanup);
2770 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2771 compiler_use_next_block(c, anchor);
2772
2773 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774}
2775
2776static int
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002777compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002778 asdl_seq *generators, expr_ty elt, expr_ty val)
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002779{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002780 PyCodeObject *co = NULL;
2781 expr_ty outermost_iter;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002782
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002783 outermost_iter = ((comprehension_ty)
2784 asdl_seq_GET(generators, 0))->iter;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002785
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002786 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2787 goto error;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002788
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002789 if (type != COMP_GENEXP) {
2790 int op;
2791 switch (type) {
2792 case COMP_SETCOMP:
2793 op = BUILD_SET;
2794 break;
2795 case COMP_DICTCOMP:
2796 op = BUILD_MAP;
2797 break;
2798 default:
2799 PyErr_Format(PyExc_SystemError,
2800 "unknown comprehension type %d", type);
2801 goto error_in_scope;
2802 }
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002803
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002804 ADDOP_I(c, op, 0);
2805 }
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002806
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002807 if (!compiler_comprehension_generator(c, generators, 0, elt,
2808 val, type))
2809 goto error_in_scope;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002810
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002811 if (type != COMP_GENEXP) {
2812 ADDOP(c, RETURN_VALUE);
2813 }
2814
2815 co = assemble(c, 1);
2816 compiler_exit_scope(c);
2817 if (co == NULL)
2818 goto error;
2819
2820 if (!compiler_make_closure(c, co, 0))
2821 goto error;
2822 Py_DECREF(co);
2823
2824 VISIT(c, expr, outermost_iter);
2825 ADDOP(c, GET_ITER);
2826 ADDOP_I(c, CALL_FUNCTION, 1);
2827 return 1;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002828error_in_scope:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002829 compiler_exit_scope(c);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002830error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002831 Py_XDECREF(co);
2832 return 0;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002833}
2834
2835static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836compiler_genexp(struct compiler *c, expr_ty e)
2837{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002838 static identifier name;
2839 if (!name) {
2840 name = PyString_FromString("<genexpr>");
2841 if (!name)
2842 return 0;
2843 }
2844 assert(e->kind == GeneratorExp_kind);
2845 return compiler_comprehension(c, e, COMP_GENEXP, name,
2846 e->v.GeneratorExp.generators,
2847 e->v.GeneratorExp.elt, NULL);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002848}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002850static int
2851compiler_setcomp(struct compiler *c, expr_ty e)
2852{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002853 static identifier name;
2854 if (!name) {
2855 name = PyString_FromString("<setcomp>");
2856 if (!name)
2857 return 0;
2858 }
2859 assert(e->kind == SetComp_kind);
2860 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2861 e->v.SetComp.generators,
2862 e->v.SetComp.elt, NULL);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002863}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002865static int
2866compiler_dictcomp(struct compiler *c, expr_ty e)
2867{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002868 static identifier name;
2869 if (!name) {
2870 name = PyString_FromString("<dictcomp>");
2871 if (!name)
2872 return 0;
2873 }
2874 assert(e->kind == DictComp_kind);
2875 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2876 e->v.DictComp.generators,
2877 e->v.DictComp.key, e->v.DictComp.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878}
2879
2880static int
2881compiler_visit_keyword(struct compiler *c, keyword_ty k)
2882{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002883 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2884 VISIT(c, expr, k->value);
2885 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886}
2887
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002888/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889 whether they are true or false.
2890
2891 Return values: 1 for true, 0 for false, -1 for non-constant.
2892 */
2893
2894static int
2895expr_constant(expr_ty e)
2896{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002897 switch (e->kind) {
2898 case Num_kind:
2899 return PyObject_IsTrue(e->v.Num.n);
2900 case Str_kind:
2901 return PyObject_IsTrue(e->v.Str.s);
2902 case Name_kind:
2903 /* __debug__ is not assignable, so we can optimize
2904 * it away in if and while statements */
2905 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2906 "__debug__") == 0)
2907 return ! Py_OptimizeFlag;
2908 /* fall through */
2909 default:
2910 return -1;
2911 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912}
2913
Guido van Rossumc2e20742006-02-27 22:32:47 +00002914/*
2915 Implements the with statement from PEP 343.
2916
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002917 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00002918
2919 with EXPR as VAR:
2920 BLOCK
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002921
Guido van Rossumc2e20742006-02-27 22:32:47 +00002922 It is implemented roughly as:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002923
Guido van Rossumda5b7012006-05-02 19:47:52 +00002924 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002925 exit = context.__exit__ # not calling it
2926 value = context.__enter__()
2927 try:
2928 VAR = value # if VAR present in the syntax
2929 BLOCK
2930 finally:
2931 if an exception was raised:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002932 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002933 else:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002934 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002935 exit(*exc)
2936 */
2937static int
2938compiler_with(struct compiler *c, stmt_ty s)
2939{
Guido van Rossumc2e20742006-02-27 22:32:47 +00002940 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002941
2942 assert(s->kind == With_kind);
2943
Guido van Rossumc2e20742006-02-27 22:32:47 +00002944 block = compiler_new_block(c);
2945 finally = compiler_new_block(c);
2946 if (!block || !finally)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002947 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002948
Guido van Rossumda5b7012006-05-02 19:47:52 +00002949 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002950 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002951 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002952
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002953 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002954 compiler_use_next_block(c, block);
Benjamin Peterson565d7852010-02-05 02:12:14 +00002955 /* Note that the block is actually called SETUP_WITH in ceval.c, but
2956 functions the same as SETUP_FINALLY except that exceptions are
2957 normalized. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002958 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002959 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002960 }
2961
2962 if (s->v.With.optional_vars) {
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002963 VISIT(c, expr, s->v.With.optional_vars);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002964 }
2965 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002966 /* Discard result from context.__enter__() */
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002967 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002968 }
2969
2970 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002971 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002972
2973 /* End of try block; start the finally block */
2974 ADDOP(c, POP_BLOCK);
2975 compiler_pop_fblock(c, FINALLY_TRY, block);
2976
2977 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2978 compiler_use_next_block(c, finally);
2979 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002980 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002981
Nick Coghlan7af53be2008-03-07 14:13:28 +00002982 /* Finally block starts; context.__exit__ is on the stack under
2983 the exception or return information. Just issue our magic
2984 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002985 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002986
2987 /* Finally block ends. */
2988 ADDOP(c, END_FINALLY);
2989 compiler_pop_fblock(c, FINALLY_END, finally);
2990 return 1;
2991}
2992
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993static int
2994compiler_visit_expr(struct compiler *c, expr_ty e)
2995{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002996 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002998 /* If expr e has a different line number than the last expr/stmt,
2999 set a new line number for the next instruction.
3000 */
3001 if (e->lineno > c->u->u_lineno) {
3002 c->u->u_lineno = e->lineno;
3003 c->u->u_lineno_set = false;
3004 }
3005 switch (e->kind) {
3006 case BoolOp_kind:
3007 return compiler_boolop(c, e);
3008 case BinOp_kind:
3009 VISIT(c, expr, e->v.BinOp.left);
3010 VISIT(c, expr, e->v.BinOp.right);
3011 ADDOP(c, binop(c, e->v.BinOp.op));
3012 break;
3013 case UnaryOp_kind:
3014 VISIT(c, expr, e->v.UnaryOp.operand);
3015 ADDOP(c, unaryop(e->v.UnaryOp.op));
3016 break;
3017 case Lambda_kind:
3018 return compiler_lambda(c, e);
3019 case IfExp_kind:
3020 return compiler_ifexp(c, e);
3021 case Dict_kind:
3022 n = asdl_seq_LEN(e->v.Dict.values);
3023 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3024 for (i = 0; i < n; i++) {
3025 VISIT(c, expr,
3026 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3027 VISIT(c, expr,
3028 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3029 ADDOP(c, STORE_MAP);
3030 }
3031 break;
3032 case Set_kind:
3033 n = asdl_seq_LEN(e->v.Set.elts);
3034 VISIT_SEQ(c, expr, e->v.Set.elts);
3035 ADDOP_I(c, BUILD_SET, n);
3036 break;
3037 case ListComp_kind:
3038 return compiler_listcomp(c, e);
3039 case SetComp_kind:
3040 return compiler_setcomp(c, e);
3041 case DictComp_kind:
3042 return compiler_dictcomp(c, e);
3043 case GeneratorExp_kind:
3044 return compiler_genexp(c, e);
3045 case Yield_kind:
3046 if (c->u->u_ste->ste_type != FunctionBlock)
3047 return compiler_error(c, "'yield' outside function");
3048 if (e->v.Yield.value) {
3049 VISIT(c, expr, e->v.Yield.value);
3050 }
3051 else {
3052 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3053 }
3054 ADDOP(c, YIELD_VALUE);
3055 break;
3056 case Compare_kind:
3057 return compiler_compare(c, e);
3058 case Call_kind:
3059 return compiler_call(c, e);
3060 case Repr_kind:
3061 VISIT(c, expr, e->v.Repr.value);
3062 ADDOP(c, UNARY_CONVERT);
3063 break;
3064 case Num_kind:
3065 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3066 break;
3067 case Str_kind:
3068 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3069 break;
3070 /* The following exprs can be assignment targets. */
3071 case Attribute_kind:
3072 if (e->v.Attribute.ctx != AugStore)
3073 VISIT(c, expr, e->v.Attribute.value);
3074 switch (e->v.Attribute.ctx) {
3075 case AugLoad:
3076 ADDOP(c, DUP_TOP);
3077 /* Fall through to load */
3078 case Load:
3079 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3080 break;
3081 case AugStore:
3082 ADDOP(c, ROT_TWO);
3083 /* Fall through to save */
3084 case Store:
3085 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3086 break;
3087 case Del:
3088 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3089 break;
3090 case Param:
3091 default:
3092 PyErr_SetString(PyExc_SystemError,
3093 "param invalid in attribute expression");
3094 return 0;
3095 }
3096 break;
3097 case Subscript_kind:
3098 switch (e->v.Subscript.ctx) {
3099 case AugLoad:
3100 VISIT(c, expr, e->v.Subscript.value);
3101 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3102 break;
3103 case Load:
3104 VISIT(c, expr, e->v.Subscript.value);
3105 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3106 break;
3107 case AugStore:
3108 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3109 break;
3110 case Store:
3111 VISIT(c, expr, e->v.Subscript.value);
3112 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3113 break;
3114 case Del:
3115 VISIT(c, expr, e->v.Subscript.value);
3116 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3117 break;
3118 case Param:
3119 default:
3120 PyErr_SetString(PyExc_SystemError,
3121 "param invalid in subscript expression");
3122 return 0;
3123 }
3124 break;
3125 case Name_kind:
3126 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3127 /* child nodes of List and Tuple will have expr_context set */
3128 case List_kind:
3129 return compiler_list(c, e);
3130 case Tuple_kind:
3131 return compiler_tuple(c, e);
3132 }
3133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003134}
3135
3136static int
3137compiler_augassign(struct compiler *c, stmt_ty s)
3138{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003139 expr_ty e = s->v.AugAssign.target;
3140 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003142 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003144 switch (e->kind) {
3145 case Attribute_kind:
3146 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3147 AugLoad, e->lineno, e->col_offset, c->c_arena);
3148 if (auge == NULL)
3149 return 0;
3150 VISIT(c, expr, auge);
3151 VISIT(c, expr, s->v.AugAssign.value);
3152 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3153 auge->v.Attribute.ctx = AugStore;
3154 VISIT(c, expr, auge);
3155 break;
3156 case Subscript_kind:
3157 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3158 AugLoad, e->lineno, e->col_offset, c->c_arena);
3159 if (auge == NULL)
3160 return 0;
3161 VISIT(c, expr, auge);
3162 VISIT(c, expr, s->v.AugAssign.value);
3163 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3164 auge->v.Subscript.ctx = AugStore;
3165 VISIT(c, expr, auge);
3166 break;
3167 case Name_kind:
3168 if (!compiler_nameop(c, e->v.Name.id, Load))
3169 return 0;
3170 VISIT(c, expr, s->v.AugAssign.value);
3171 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3172 return compiler_nameop(c, e->v.Name.id, Store);
3173 default:
3174 PyErr_Format(PyExc_SystemError,
3175 "invalid node type (%d) for augmented assignment",
3176 e->kind);
3177 return 0;
3178 }
3179 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180}
3181
3182static int
3183compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3184{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003185 struct fblockinfo *f;
3186 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3187 PyErr_SetString(PyExc_SystemError,
3188 "too many statically nested blocks");
3189 return 0;
3190 }
3191 f = &c->u->u_fblock[c->u->u_nfblocks++];
3192 f->fb_type = t;
3193 f->fb_block = b;
3194 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195}
3196
3197static void
3198compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3199{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003200 struct compiler_unit *u = c->u;
3201 assert(u->u_nfblocks > 0);
3202 u->u_nfblocks--;
3203 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3204 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003205}
3206
Jeremy Hylton82271f12006-10-04 02:24:52 +00003207static int
3208compiler_in_loop(struct compiler *c) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003209 int i;
3210 struct compiler_unit *u = c->u;
3211 for (i = 0; i < u->u_nfblocks; ++i) {
3212 if (u->u_fblock[i].fb_type == LOOP)
3213 return 1;
3214 }
3215 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003216}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217/* Raises a SyntaxError and returns 0.
3218 If something goes wrong, a different exception may be raised.
3219*/
3220
3221static int
3222compiler_error(struct compiler *c, const char *errstr)
3223{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003224 PyObject *loc;
3225 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003227 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3228 if (!loc) {
3229 Py_INCREF(Py_None);
3230 loc = Py_None;
3231 }
3232 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3233 Py_None, loc);
3234 if (!u)
3235 goto exit;
3236 v = Py_BuildValue("(zO)", errstr, u);
3237 if (!v)
3238 goto exit;
3239 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003241 Py_DECREF(loc);
3242 Py_XDECREF(u);
3243 Py_XDECREF(v);
3244 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245}
3246
3247static int
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003248compiler_handle_subscr(struct compiler *c, const char *kind,
3249 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003251 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003253 /* XXX this code is duplicated */
3254 switch (ctx) {
3255 case AugLoad: /* fall through to Load */
3256 case Load: op = BINARY_SUBSCR; break;
3257 case AugStore:/* fall through to Store */
3258 case Store: op = STORE_SUBSCR; break;
3259 case Del: op = DELETE_SUBSCR; break;
3260 case Param:
3261 PyErr_Format(PyExc_SystemError,
3262 "invalid %s kind %d in subscript\n",
3263 kind, ctx);
3264 return 0;
3265 }
3266 if (ctx == AugLoad) {
3267 ADDOP_I(c, DUP_TOPX, 2);
3268 }
3269 else if (ctx == AugStore) {
3270 ADDOP(c, ROT_THREE);
3271 }
3272 ADDOP(c, op);
3273 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274}
3275
3276static int
3277compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3278{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003279 int n = 2;
3280 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003282 /* only handles the cases where BUILD_SLICE is emitted */
3283 if (s->v.Slice.lower) {
3284 VISIT(c, expr, s->v.Slice.lower);
3285 }
3286 else {
3287 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003290 if (s->v.Slice.upper) {
3291 VISIT(c, expr, s->v.Slice.upper);
3292 }
3293 else {
3294 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3295 }
3296
3297 if (s->v.Slice.step) {
3298 n++;
3299 VISIT(c, expr, s->v.Slice.step);
3300 }
3301 ADDOP_I(c, BUILD_SLICE, n);
3302 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303}
3304
3305static int
3306compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3307{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003308 int op = 0, slice_offset = 0, stack_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003310 assert(s->v.Slice.step == NULL);
3311 if (s->v.Slice.lower) {
3312 slice_offset++;
3313 stack_count++;
3314 if (ctx != AugStore)
3315 VISIT(c, expr, s->v.Slice.lower);
3316 }
3317 if (s->v.Slice.upper) {
3318 slice_offset += 2;
3319 stack_count++;
3320 if (ctx != AugStore)
3321 VISIT(c, expr, s->v.Slice.upper);
3322 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003324 if (ctx == AugLoad) {
3325 switch (stack_count) {
3326 case 0: ADDOP(c, DUP_TOP); break;
3327 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3328 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3329 }
3330 }
3331 else if (ctx == AugStore) {
3332 switch (stack_count) {
3333 case 0: ADDOP(c, ROT_TWO); break;
3334 case 1: ADDOP(c, ROT_THREE); break;
3335 case 2: ADDOP(c, ROT_FOUR); break;
3336 }
3337 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003339 switch (ctx) {
3340 case AugLoad: /* fall through to Load */
3341 case Load: op = SLICE; break;
3342 case AugStore:/* fall through to Store */
3343 case Store: op = STORE_SLICE; break;
3344 case Del: op = DELETE_SLICE; break;
3345 case Param:
3346 default:
3347 PyErr_SetString(PyExc_SystemError,
3348 "param invalid in simple slice");
3349 return 0;
3350 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003351
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003352 ADDOP(c, op + slice_offset);
3353 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003354}
3355
3356static int
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003357compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3358 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003360 switch (s->kind) {
3361 case Ellipsis_kind:
3362 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3363 break;
3364 case Slice_kind:
3365 return compiler_slice(c, s, ctx);
3366 case Index_kind:
3367 VISIT(c, expr, s->v.Index.value);
3368 break;
3369 case ExtSlice_kind:
3370 default:
3371 PyErr_SetString(PyExc_SystemError,
3372 "extended slice invalid in nested slice");
3373 return 0;
3374 }
3375 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003376}
3377
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003378static int
3379compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3380{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003381 char * kindname = NULL;
3382 switch (s->kind) {
3383 case Index_kind:
3384 kindname = "index";
3385 if (ctx != AugStore) {
3386 VISIT(c, expr, s->v.Index.value);
3387 }
3388 break;
3389 case Ellipsis_kind:
3390 kindname = "ellipsis";
3391 if (ctx != AugStore) {
3392 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3393 }
3394 break;
3395 case Slice_kind:
3396 kindname = "slice";
3397 if (!s->v.Slice.step)
3398 return compiler_simple_slice(c, s, ctx);
3399 if (ctx != AugStore) {
3400 if (!compiler_slice(c, s, ctx))
3401 return 0;
3402 }
3403 break;
3404 case ExtSlice_kind:
3405 kindname = "extended slice";
3406 if (ctx != AugStore) {
3407 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3408 for (i = 0; i < n; i++) {
3409 slice_ty sub = (slice_ty)asdl_seq_GET(
3410 s->v.ExtSlice.dims, i);
3411 if (!compiler_visit_nested_slice(c, sub, ctx))
3412 return 0;
3413 }
3414 ADDOP_I(c, BUILD_TUPLE, n);
3415 }
3416 break;
3417 default:
3418 PyErr_Format(PyExc_SystemError,
3419 "invalid subscript kind %d", s->kind);
3420 return 0;
3421 }
3422 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423}
3424
Neal Norwitzf733a012006-10-29 18:30:10 +00003425
3426/* End of the compiler section, beginning of the assembler section */
3427
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003428/* do depth-first search of basic block graph, starting with block.
3429 post records the block indices in post-order.
3430
3431 XXX must handle implicit jumps from one block to next
3432*/
3433
Neal Norwitzf733a012006-10-29 18:30:10 +00003434struct assembler {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003435 PyObject *a_bytecode; /* string containing bytecode */
3436 int a_offset; /* offset into bytecode */
3437 int a_nblocks; /* number of reachable blocks */
3438 basicblock **a_postorder; /* list of blocks in dfs postorder */
3439 PyObject *a_lnotab; /* string containing lnotab */
3440 int a_lnotab_off; /* offset into lnotab */
3441 int a_lineno; /* last lineno of emitted instruction */
3442 int a_lineno_off; /* bytecode offset of last lineno */
Neal Norwitzf733a012006-10-29 18:30:10 +00003443};
3444
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003445static void
3446dfs(struct compiler *c, basicblock *b, struct assembler *a)
3447{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003448 int i;
3449 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003451 if (b->b_seen)
3452 return;
3453 b->b_seen = 1;
3454 if (b->b_next != NULL)
3455 dfs(c, b->b_next, a);
3456 for (i = 0; i < b->b_iused; i++) {
3457 instr = &b->b_instr[i];
3458 if (instr->i_jrel || instr->i_jabs)
3459 dfs(c, instr->i_target, a);
3460 }
3461 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462}
3463
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003464static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003465stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3466{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003467 int i, target_depth;
3468 struct instr *instr;
3469 if (b->b_seen || b->b_startdepth >= depth)
3470 return maxdepth;
3471 b->b_seen = 1;
3472 b->b_startdepth = depth;
3473 for (i = 0; i < b->b_iused; i++) {
3474 instr = &b->b_instr[i];
3475 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3476 if (depth > maxdepth)
3477 maxdepth = depth;
3478 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3479 if (instr->i_jrel || instr->i_jabs) {
3480 target_depth = depth;
3481 if (instr->i_opcode == FOR_ITER) {
3482 target_depth = depth-2;
3483 } else if (instr->i_opcode == SETUP_FINALLY ||
3484 instr->i_opcode == SETUP_EXCEPT) {
3485 target_depth = depth+3;
3486 if (target_depth > maxdepth)
3487 maxdepth = target_depth;
3488 }
3489 maxdepth = stackdepth_walk(c, instr->i_target,
3490 target_depth, maxdepth);
3491 if (instr->i_opcode == JUMP_ABSOLUTE ||
3492 instr->i_opcode == JUMP_FORWARD) {
3493 goto out; /* remaining code is dead */
3494 }
3495 }
3496 }
3497 if (b->b_next)
3498 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499out:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003500 b->b_seen = 0;
3501 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502}
3503
3504/* Find the flow path that needs the largest stack. We assume that
3505 * cycles in the flow graph have no net effect on the stack depth.
3506 */
3507static int
3508stackdepth(struct compiler *c)
3509{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003510 basicblock *b, *entryblock;
3511 entryblock = NULL;
3512 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3513 b->b_seen = 0;
3514 b->b_startdepth = INT_MIN;
3515 entryblock = b;
3516 }
3517 if (!entryblock)
3518 return 0;
3519 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003520}
3521
3522static int
3523assemble_init(struct assembler *a, int nblocks, int firstlineno)
3524{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003525 memset(a, 0, sizeof(struct assembler));
3526 a->a_lineno = firstlineno;
3527 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3528 if (!a->a_bytecode)
3529 return 0;
3530 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3531 if (!a->a_lnotab)
3532 return 0;
3533 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3534 PyErr_NoMemory();
3535 return 0;
3536 }
3537 a->a_postorder = (basicblock **)PyObject_Malloc(
3538 sizeof(basicblock *) * nblocks);
3539 if (!a->a_postorder) {
3540 PyErr_NoMemory();
3541 return 0;
3542 }
3543 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544}
3545
3546static void
3547assemble_free(struct assembler *a)
3548{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003549 Py_XDECREF(a->a_bytecode);
3550 Py_XDECREF(a->a_lnotab);
3551 if (a->a_postorder)
3552 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553}
3554
3555/* Return the size of a basic block in bytes. */
3556
3557static int
3558instrsize(struct instr *instr)
3559{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003560 if (!instr->i_hasarg)
3561 return 1; /* 1 byte for the opcode*/
3562 if (instr->i_oparg > 0xffff)
3563 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3564 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565}
3566
3567static int
3568blocksize(basicblock *b)
3569{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003570 int i;
3571 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003573 for (i = 0; i < b->b_iused; i++)
3574 size += instrsize(&b->b_instr[i]);
3575 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576}
3577
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003578/* Appends a pair to the end of the line number table, a_lnotab, representing
3579 the instruction's bytecode offset and line number. See
3580 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003581
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003582static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003584{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003585 int d_bytecode, d_lineno;
3586 int len;
3587 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003589 d_bytecode = a->a_offset - a->a_lineno_off;
3590 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003592 assert(d_bytecode >= 0);
3593 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003595 if(d_bytecode == 0 && d_lineno == 0)
3596 return 1;
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003597
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003598 if (d_bytecode > 255) {
3599 int j, nbytes, ncodes = d_bytecode / 255;
3600 nbytes = a->a_lnotab_off + 2 * ncodes;
3601 len = PyString_GET_SIZE(a->a_lnotab);
3602 if (nbytes >= len) {
3603 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3604 len = nbytes;
3605 else if (len <= INT_MAX / 2)
3606 len *= 2;
3607 else {
3608 PyErr_NoMemory();
3609 return 0;
3610 }
3611 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3612 return 0;
3613 }
3614 lnotab = (unsigned char *)
3615 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3616 for (j = 0; j < ncodes; j++) {
3617 *lnotab++ = 255;
3618 *lnotab++ = 0;
3619 }
3620 d_bytecode -= ncodes * 255;
3621 a->a_lnotab_off += ncodes * 2;
3622 }
3623 assert(d_bytecode <= 255);
3624 if (d_lineno > 255) {
3625 int j, nbytes, ncodes = d_lineno / 255;
3626 nbytes = a->a_lnotab_off + 2 * ncodes;
3627 len = PyString_GET_SIZE(a->a_lnotab);
3628 if (nbytes >= len) {
3629 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3630 len = nbytes;
3631 else if (len <= INT_MAX / 2)
3632 len *= 2;
3633 else {
3634 PyErr_NoMemory();
3635 return 0;
3636 }
3637 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3638 return 0;
3639 }
3640 lnotab = (unsigned char *)
3641 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3642 *lnotab++ = d_bytecode;
3643 *lnotab++ = 255;
3644 d_bytecode = 0;
3645 for (j = 1; j < ncodes; j++) {
3646 *lnotab++ = 0;
3647 *lnotab++ = 255;
3648 }
3649 d_lineno -= ncodes * 255;
3650 a->a_lnotab_off += ncodes * 2;
3651 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003652
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003653 len = PyString_GET_SIZE(a->a_lnotab);
3654 if (a->a_lnotab_off + 2 >= len) {
3655 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
3656 return 0;
3657 }
3658 lnotab = (unsigned char *)
3659 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003661 a->a_lnotab_off += 2;
3662 if (d_bytecode) {
3663 *lnotab++ = d_bytecode;
3664 *lnotab++ = d_lineno;
3665 }
3666 else { /* First line of a block; def stmt, etc. */
3667 *lnotab++ = 0;
3668 *lnotab++ = d_lineno;
3669 }
3670 a->a_lineno = i->i_lineno;
3671 a->a_lineno_off = a->a_offset;
3672 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003673}
3674
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675/* assemble_emit()
3676 Extend the bytecode with a new instruction.
3677 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003678*/
3679
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003680static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003682{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003683 int size, arg = 0, ext = 0;
3684 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
3685 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003686
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003687 size = instrsize(i);
3688 if (i->i_hasarg) {
3689 arg = i->i_oparg;
3690 ext = arg >> 16;
3691 }
3692 if (i->i_lineno && !assemble_lnotab(a, i))
3693 return 0;
3694 if (a->a_offset + size >= len) {
3695 if (len > PY_SSIZE_T_MAX / 2)
3696 return 0;
3697 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
3698 return 0;
3699 }
3700 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3701 a->a_offset += size;
3702 if (size == 6) {
3703 assert(i->i_hasarg);
3704 *code++ = (char)EXTENDED_ARG;
3705 *code++ = ext & 0xff;
3706 *code++ = ext >> 8;
3707 arg &= 0xffff;
3708 }
3709 *code++ = i->i_opcode;
3710 if (i->i_hasarg) {
3711 assert(size == 3 || size == 6);
3712 *code++ = arg & 0xff;
3713 *code++ = arg >> 8;
3714 }
3715 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003716}
3717
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003718static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003720{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003721 basicblock *b;
3722 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3723 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003724
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003725 /* Compute the size of each block and fixup jump args.
3726 Replace block pointer with position in bytecode. */
3727 do {
3728 totsize = 0;
3729 for (i = a->a_nblocks - 1; i >= 0; i--) {
3730 b = a->a_postorder[i];
3731 bsize = blocksize(b);
3732 b->b_offset = totsize;
3733 totsize += bsize;
3734 }
3735 last_extended_arg_count = extended_arg_count;
3736 extended_arg_count = 0;
3737 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3738 bsize = b->b_offset;
3739 for (i = 0; i < b->b_iused; i++) {
3740 struct instr *instr = &b->b_instr[i];
3741 /* Relative jumps are computed relative to
3742 the instruction pointer after fetching
3743 the jump instruction.
3744 */
3745 bsize += instrsize(instr);
3746 if (instr->i_jabs)
3747 instr->i_oparg = instr->i_target->b_offset;
3748 else if (instr->i_jrel) {
3749 int delta = instr->i_target->b_offset - bsize;
3750 instr->i_oparg = delta;
3751 }
3752 else
3753 continue;
3754 if (instr->i_oparg > 0xffff)
3755 extended_arg_count++;
3756 }
3757 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003759 /* XXX: This is an awful hack that could hurt performance, but
3760 on the bright side it should work until we come up
3761 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003762
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003763 The issue is that in the first loop blocksize() is called
3764 which calls instrsize() which requires i_oparg be set
3765 appropriately. There is a bootstrap problem because
3766 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003767
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003768 So we loop until we stop seeing new EXTENDED_ARGs.
3769 The only EXTENDED_ARGs that could be popping up are
3770 ones in jump instructions. So this should converge
3771 fairly quickly.
3772 */
3773 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003774}
3775
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003776static PyObject *
3777dict_keys_inorder(PyObject *dict, int offset)
3778{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003779 PyObject *tuple, *k, *v;
3780 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003781
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003782 tuple = PyTuple_New(size);
3783 if (tuple == NULL)
3784 return NULL;
3785 while (PyDict_Next(dict, &pos, &k, &v)) {
3786 i = PyInt_AS_LONG(v);
3787 /* The keys of the dictionary are tuples. (see compiler_add_o)
3788 The object we want is always first, though. */
3789 k = PyTuple_GET_ITEM(k, 0);
3790 Py_INCREF(k);
3791 assert((i - offset) < size);
3792 assert((i - offset) >= 0);
3793 PyTuple_SET_ITEM(tuple, i - offset, k);
3794 }
3795 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003796}
3797
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003798static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003800{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003801 PySTEntryObject *ste = c->u->u_ste;
3802 int flags = 0, n;
3803 if (ste->ste_type != ModuleBlock)
3804 flags |= CO_NEWLOCALS;
3805 if (ste->ste_type == FunctionBlock) {
3806 if (!ste->ste_unoptimized)
3807 flags |= CO_OPTIMIZED;
3808 if (ste->ste_nested)
3809 flags |= CO_NESTED;
3810 if (ste->ste_generator)
3811 flags |= CO_GENERATOR;
3812 if (ste->ste_varargs)
3813 flags |= CO_VARARGS;
3814 if (ste->ste_varkeywords)
3815 flags |= CO_VARKEYWORDS;
3816 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003817
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003818 /* (Only) inherit compilerflags in PyCF_MASK */
3819 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003820
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003821 n = PyDict_Size(c->u->u_freevars);
3822 if (n < 0)
3823 return -1;
3824 if (n == 0) {
3825 n = PyDict_Size(c->u->u_cellvars);
3826 if (n < 0)
3827 return -1;
3828 if (n == 0) {
3829 flags |= CO_NOFREE;
3830 }
3831 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003832
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003833 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003834}
3835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836static PyCodeObject *
3837makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003838{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003839 PyObject *tmp;
3840 PyCodeObject *co = NULL;
3841 PyObject *consts = NULL;
3842 PyObject *names = NULL;
3843 PyObject *varnames = NULL;
3844 PyObject *filename = NULL;
3845 PyObject *name = NULL;
3846 PyObject *freevars = NULL;
3847 PyObject *cellvars = NULL;
3848 PyObject *bytecode = NULL;
3849 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003850
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003851 tmp = dict_keys_inorder(c->u->u_consts, 0);
3852 if (!tmp)
3853 goto error;
3854 consts = PySequence_List(tmp); /* optimize_code requires a list */
3855 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003856
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003857 names = dict_keys_inorder(c->u->u_names, 0);
3858 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3859 if (!consts || !names || !varnames)
3860 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003862 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3863 if (!cellvars)
3864 goto error;
3865 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3866 if (!freevars)
3867 goto error;
3868 filename = PyString_FromString(c->c_filename);
3869 if (!filename)
3870 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003872 nlocals = PyDict_Size(c->u->u_varnames);
3873 flags = compute_code_flags(c);
3874 if (flags < 0)
3875 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003877 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3878 if (!bytecode)
3879 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003881 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3882 if (!tmp)
3883 goto error;
3884 Py_DECREF(consts);
3885 consts = tmp;
3886
3887 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3888 bytecode, consts, names, varnames,
3889 freevars, cellvars,
3890 filename, c->u->u_name,
3891 c->u->u_firstlineno,
3892 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003894 Py_XDECREF(consts);
3895 Py_XDECREF(names);
3896 Py_XDECREF(varnames);
3897 Py_XDECREF(filename);
3898 Py_XDECREF(name);
3899 Py_XDECREF(freevars);
3900 Py_XDECREF(cellvars);
3901 Py_XDECREF(bytecode);
3902 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003903}
3904
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003905
3906/* For debugging purposes only */
3907#if 0
3908static void
3909dump_instr(const struct instr *i)
3910{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003911 const char *jrel = i->i_jrel ? "jrel " : "";
3912 const char *jabs = i->i_jabs ? "jabs " : "";
3913 char arg[128];
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003914
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003915 *arg = '\0';
3916 if (i->i_hasarg)
3917 sprintf(arg, "arg: %d ", i->i_oparg);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003918
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003919 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3920 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003921}
3922
3923static void
3924dump_basicblock(const basicblock *b)
3925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003926 const char *seen = b->b_seen ? "seen " : "";
3927 const char *b_return = b->b_return ? "return " : "";
3928 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3929 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3930 if (b->b_instr) {
3931 int i;
3932 for (i = 0; i < b->b_iused; i++) {
3933 fprintf(stderr, " [%02d] ", i);
3934 dump_instr(b->b_instr + i);
3935 }
3936 }
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003937}
3938#endif
3939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940static PyCodeObject *
3941assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003943 basicblock *b, *entryblock;
3944 struct assembler a;
3945 int i, j, nblocks;
3946 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003947
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003948 /* Make sure every block that falls off the end returns None.
3949 XXX NEXT_BLOCK() isn't quite right, because if the last
3950 block ends with a jump or return b_next shouldn't set.
3951 */
3952 if (!c->u->u_curblock->b_return) {
3953 NEXT_BLOCK(c);
3954 if (addNone)
3955 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3956 ADDOP(c, RETURN_VALUE);
3957 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003958
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003959 nblocks = 0;
3960 entryblock = NULL;
3961 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3962 nblocks++;
3963 entryblock = b;
3964 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003965
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003966 /* Set firstlineno if it wasn't explicitly set. */
3967 if (!c->u->u_firstlineno) {
3968 if (entryblock && entryblock->b_instr)
3969 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3970 else
3971 c->u->u_firstlineno = 1;
3972 }
3973 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3974 goto error;
3975 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003976
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003977 /* Can't modify the bytecode after computing jump offsets. */
3978 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003979
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003980 /* Emit code in reverse postorder from dfs. */
3981 for (i = a.a_nblocks - 1; i >= 0; i--) {
3982 b = a.a_postorder[i];
3983 for (j = 0; j < b->b_iused; j++)
3984 if (!assemble_emit(&a, &b->b_instr[j]))
3985 goto error;
3986 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003987
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003988 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3989 goto error;
3990 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3991 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003992
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003993 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003994 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003995 assemble_free(&a);
3996 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003997}