blob: dfb2c9bcf7f5701c402ea62d5e6a68be93085899 [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 Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned i_jabs : 1;
47 unsigned i_jrel : 1;
48 unsigned i_hasarg : 1;
49 unsigned char i_opcode;
50 int i_oparg;
51 struct basicblock_ *i_target; /* target block (if jump instruction) */
52 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000053};
54
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000055typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056 /* Each basicblock in a compilation unit is linked via b_list in the
57 reverse order that the block are allocated. b_list points to the next
58 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 struct basicblock_ *b_list;
60 /* number of instructions used */
61 int b_iused;
62 /* length of instruction array (b_instr) */
63 int b_ialloc;
64 /* pointer to an array of instructions, initially NULL */
65 struct instr *b_instr;
66 /* If b_next is non-NULL, it is a pointer to the next
67 block reached by normal control flow. */
68 struct basicblock_ *b_next;
69 /* b_seen is used to perform a DFS of basicblocks. */
70 unsigned b_seen : 1;
71 /* b_return is true if a RETURN_VALUE opcode is inserted. */
72 unsigned b_return : 1;
73 /* depth of stack upon entry of block, computed by stackdepth() */
74 int b_startdepth;
75 /* instruction offset for block, computed by assemble_jump_offsets() */
76 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077} basicblock;
78
79/* fblockinfo tracks the current frame block.
80
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081A frame block is used to handle loops, try/except, and try/finally.
82It's called a frame block to distinguish it from a basic block in the
83compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084*/
85
86enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
87
88struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 enum fblocktype fb_type;
90 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091};
92
93/* The following items change on entry and exit of code blocks.
94 They must be saved and restored when returning to a block.
95*/
96struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 PyObject *u_name;
100 /* The following fields are dicts that map objects to
101 the index of them in co_XXX. The index is used as
102 the argument for opcodes that refer to those collections.
103 */
104 PyObject *u_consts; /* all constants */
105 PyObject *u_names; /* all names */
106 PyObject *u_varnames; /* local variables */
107 PyObject *u_cellvars; /* cell variables */
108 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 int u_argcount; /* number of arguments for block */
113 int u_kwonlyargcount; /* number of keyword only 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 Pitrouf95a1b32010-05-09 15:52:27 +0000119 int u_nfblocks;
120 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 int u_firstlineno; /* the first lineno of the block */
123 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000124 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 int u_lineno_set; /* boolean to indicate whether instr
126 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127};
128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000131The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134*/
135
136struct compiler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 const char *c_filename;
138 struct symtable *c_st;
139 PyFutureFeatures *c_future; /* pointer to module's __future__ */
140 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 int c_interactive; /* true if in interactive mode */
143 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 struct compiler_unit *u; /* compiler state for current block */
146 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
147 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148};
149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150static int compiler_enter_scope(struct compiler *, identifier, void *, int);
151static void compiler_free(struct compiler *);
152static basicblock *compiler_new_block(struct compiler *);
153static int compiler_next_instr(struct compiler *, basicblock *);
154static int compiler_addop(struct compiler *, int);
155static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
156static int compiler_addop_i(struct compiler *, int, int);
157static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158static basicblock *compiler_use_new_block(struct compiler *);
159static int compiler_error(struct compiler *, const char *);
160static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
161
162static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
163static int compiler_visit_stmt(struct compiler *, stmt_ty);
164static int compiler_visit_keyword(struct compiler *, keyword_ty);
165static int compiler_visit_expr(struct compiler *, expr_ty);
166static int compiler_augassign(struct compiler *, stmt_ty);
167static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
170static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000172static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000174/* Returns true if there is a loop on the fblock stack. */
175static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176
177static int inplace_binop(struct compiler *, operator_ty);
178static int expr_constant(expr_ty e);
179
Guido van Rossumc2e20742006-02-27 22:32:47 +0000180static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000181static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 asdl_seq *args,
183 asdl_seq *keywords,
184 expr_ty starargs,
185 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000186
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static PyCodeObject *assemble(struct compiler *, int addNone);
188static PyObject *__doc__;
189
Benjamin Petersonb173f782009-05-05 22:31:58 +0000190#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* Name mangling: __private becomes _classname__private.
196 This is independent from how the name is used. */
197 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
198 Py_UNICODE *buffer;
199 size_t nlen, plen;
200 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
201 name == NULL || name[0] != '_' || name[1] != '_') {
202 Py_INCREF(ident);
203 return ident;
204 }
205 p = PyUnicode_AS_UNICODE(privateobj);
206 nlen = Py_UNICODE_strlen(name);
207 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 The only time a name with a dot can occur is when
210 we are compiling an import statement that has a
211 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 TODO(jhylton): Decide whether we want to support
214 mangling of the module name, e.g. __M.X.
215 */
216 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
217 || Py_UNICODE_strchr(name, '.')) {
218 Py_INCREF(ident);
219 return ident; /* Don't mangle __whatever__ */
220 }
221 /* Strip leading underscores from class name */
222 while (*p == '_')
223 p++;
224 if (*p == 0) {
225 Py_INCREF(ident);
226 return ident; /* Don't mangle if class is just underscores */
227 }
228 plen = Py_UNICODE_strlen(p);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 assert(1 <= PY_SSIZE_T_MAX - nlen);
231 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
234 if (!ident)
235 return 0;
236 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
237 buffer = PyUnicode_AS_UNICODE(ident);
238 buffer[0] = '_';
239 Py_UNICODE_strncpy(buffer+1, p, plen);
240 Py_UNICODE_strcpy(buffer+1+plen, name);
241 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000242}
243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244static int
245compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 c->c_stack = PyList_New(0);
250 if (!c->c_stack)
251 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254}
255
256PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000257PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 struct compiler c;
261 PyCodeObject *co = NULL;
262 PyCompilerFlags local_flags;
263 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if (!__doc__) {
266 __doc__ = PyUnicode_InternFromString("__doc__");
267 if (!__doc__)
268 return NULL;
269 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (!compiler_init(&c))
272 return NULL;
273 c.c_filename = filename;
274 c.c_arena = arena;
275 c.c_future = PyFuture_FromAST(mod, filename);
276 if (c.c_future == NULL)
277 goto finally;
278 if (!flags) {
279 local_flags.cf_flags = 0;
280 flags = &local_flags;
281 }
282 merged = c.c_future->ff_features | flags->cf_flags;
283 c.c_future->ff_features = merged;
284 flags->cf_flags = merged;
285 c.c_flags = flags;
286 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 c.c_st = PySymtable_Build(mod, filename, c.c_future);
289 if (c.c_st == NULL) {
290 if (!PyErr_Occurred())
291 PyErr_SetString(PyExc_SystemError, "no symtable");
292 goto finally;
293 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Thomas Wouters1175c432006-02-27 22:49:54 +0000297 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 compiler_free(&c);
299 assert(co || PyErr_Occurred());
300 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301}
302
303PyCodeObject *
304PyNode_Compile(struct _node *n, const char *filename)
305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 PyCodeObject *co = NULL;
307 mod_ty mod;
308 PyArena *arena = PyArena_New();
309 if (!arena)
310 return NULL;
311 mod = PyAST_FromNode(n, NULL, filename, arena);
312 if (mod)
313 co = PyAST_Compile(mod, filename, NULL, arena);
314 PyArena_Free(arena);
315 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000316}
317
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c->c_st)
322 PySymtable_Free(c->c_st);
323 if (c->c_future)
324 PyObject_Free(c->c_future);
325 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000326}
327
Guido van Rossum79f25d91997-04-29 20:08:16 +0000328static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 Py_ssize_t i, n;
332 PyObject *v, *k;
333 PyObject *dict = PyDict_New();
334 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 n = PyList_Size(list);
337 for (i = 0; i < n; i++) {
338 v = PyLong_FromLong(i);
339 if (!v) {
340 Py_DECREF(dict);
341 return NULL;
342 }
343 k = PyList_GET_ITEM(list, i);
344 k = PyTuple_Pack(2, k, k->ob_type);
345 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
346 Py_XDECREF(k);
347 Py_DECREF(v);
348 Py_DECREF(dict);
349 return NULL;
350 }
351 Py_DECREF(k);
352 Py_DECREF(v);
353 }
354 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355}
356
357/* Return new dict containing names from src that match scope(s).
358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000361values are integers, starting at offset and increasing by one for
362each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363*/
364
365static PyObject *
366dictbytype(PyObject *src, int scope_type, int flag, int offset)
367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 Py_ssize_t pos = 0, i = offset, scope;
369 PyObject *k, *v, *dest = PyDict_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 assert(offset >= 0);
372 if (dest == NULL)
373 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 while (PyDict_Next(src, &pos, &k, &v)) {
376 /* XXX this should probably be a macro in symtable.h */
377 long vi;
378 assert(PyLong_Check(v));
379 vi = PyLong_AS_LONG(v);
380 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (scope == scope_type || vi & flag) {
383 PyObject *tuple, *item = PyLong_FromLong(i);
384 if (item == NULL) {
385 Py_DECREF(dest);
386 return NULL;
387 }
388 i++;
389 tuple = PyTuple_Pack(2, k, k->ob_type);
390 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
391 Py_DECREF(item);
392 Py_DECREF(dest);
393 Py_XDECREF(tuple);
394 return NULL;
395 }
396 Py_DECREF(item);
397 Py_DECREF(tuple);
398 }
399 }
400 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000401}
402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403static void
404compiler_unit_check(struct compiler_unit *u)
405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 basicblock *block;
407 for (block = u->u_blocks; block != NULL; block = block->b_list) {
408 assert((void *)block != (void *)0xcbcbcbcb);
409 assert((void *)block != (void *)0xfbfbfbfb);
410 assert((void *)block != (void *)0xdbdbdbdb);
411 if (block->b_instr != NULL) {
412 assert(block->b_ialloc > 0);
413 assert(block->b_iused > 0);
414 assert(block->b_ialloc >= block->b_iused);
415 }
416 else {
417 assert (block->b_iused == 0);
418 assert (block->b_ialloc == 0);
419 }
420 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000421}
422
423static void
424compiler_unit_free(struct compiler_unit *u)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 compiler_unit_check(u);
429 b = u->u_blocks;
430 while (b != NULL) {
431 if (b->b_instr)
432 PyObject_Free((void *)b->b_instr);
433 next = b->b_list;
434 PyObject_Free((void *)b);
435 b = next;
436 }
437 Py_CLEAR(u->u_ste);
438 Py_CLEAR(u->u_name);
439 Py_CLEAR(u->u_consts);
440 Py_CLEAR(u->u_names);
441 Py_CLEAR(u->u_varnames);
442 Py_CLEAR(u->u_freevars);
443 Py_CLEAR(u->u_cellvars);
444 Py_CLEAR(u->u_private);
445 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000446}
447
448static int
449compiler_enter_scope(struct compiler *c, identifier name, void *key,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
455 struct compiler_unit));
456 if (!u) {
457 PyErr_NoMemory();
458 return 0;
459 }
460 memset(u, 0, sizeof(struct compiler_unit));
461 u->u_argcount = 0;
462 u->u_kwonlyargcount = 0;
463 u->u_ste = PySymtable_Lookup(c->c_st, key);
464 if (!u->u_ste) {
465 compiler_unit_free(u);
466 return 0;
467 }
468 Py_INCREF(name);
469 u->u_name = name;
470 u->u_varnames = list2dict(u->u_ste->ste_varnames);
471 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
472 if (!u->u_varnames || !u->u_cellvars) {
473 compiler_unit_free(u);
474 return 0;
475 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
478 PyDict_Size(u->u_cellvars));
479 if (!u->u_freevars) {
480 compiler_unit_free(u);
481 return 0;
482 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 u->u_blocks = NULL;
485 u->u_nfblocks = 0;
486 u->u_firstlineno = lineno;
487 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000488 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 u->u_lineno_set = 0;
490 u->u_consts = PyDict_New();
491 if (!u->u_consts) {
492 compiler_unit_free(u);
493 return 0;
494 }
495 u->u_names = PyDict_New();
496 if (!u->u_names) {
497 compiler_unit_free(u);
498 return 0;
499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Push the old compiler_unit on the stack. */
504 if (c->u) {
505 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
506 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
507 Py_XDECREF(capsule);
508 compiler_unit_free(u);
509 return 0;
510 }
511 Py_DECREF(capsule);
512 u->u_private = c->u->u_private;
513 Py_XINCREF(u->u_private);
514 }
515 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 c->c_nestlevel++;
518 if (compiler_use_new_block(c) == NULL)
519 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000522}
523
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525compiler_exit_scope(struct compiler *c)
526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 int n;
528 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 c->c_nestlevel--;
531 compiler_unit_free(c->u);
532 /* Restore c->u to the parent unit. */
533 n = PyList_GET_SIZE(c->c_stack) - 1;
534 if (n >= 0) {
535 capsule = PyList_GET_ITEM(c->c_stack, n);
536 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
537 assert(c->u);
538 /* we are deleting from a list so this really shouldn't fail */
539 if (PySequence_DelItem(c->c_stack, n) < 0)
540 Py_FatalError("compiler_exit_scope()");
541 compiler_unit_check(c->u);
542 }
543 else
544 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546}
547
548/* Allocate a new block and return a pointer to it.
549 Returns NULL on error.
550*/
551
552static basicblock *
553compiler_new_block(struct compiler *c)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 basicblock *b;
556 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 u = c->u;
559 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
560 if (b == NULL) {
561 PyErr_NoMemory();
562 return NULL;
563 }
564 memset((void *)b, 0, sizeof(basicblock));
565 /* Extend the singly linked list of blocks with new block. */
566 b->b_list = u->u_blocks;
567 u->u_blocks = b;
568 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569}
570
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000571static basicblock *
572compiler_use_new_block(struct compiler *c)
573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 basicblock *block = compiler_new_block(c);
575 if (block == NULL)
576 return NULL;
577 c->u->u_curblock = block;
578 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579}
580
581static basicblock *
582compiler_next_block(struct compiler *c)
583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 basicblock *block = compiler_new_block(c);
585 if (block == NULL)
586 return NULL;
587 c->u->u_curblock->b_next = block;
588 c->u->u_curblock = block;
589 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000590}
591
592static basicblock *
593compiler_use_next_block(struct compiler *c, basicblock *block)
594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 assert(block != NULL);
596 c->u->u_curblock->b_next = block;
597 c->u->u_curblock = block;
598 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599}
600
601/* Returns the offset of the next instruction in the current block's
602 b_instr array. Resizes the b_instr as necessary.
603 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
606static int
607compiler_next_instr(struct compiler *c, basicblock *b)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 assert(b != NULL);
610 if (b->b_instr == NULL) {
611 b->b_instr = (struct instr *)PyObject_Malloc(
612 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
613 if (b->b_instr == NULL) {
614 PyErr_NoMemory();
615 return -1;
616 }
617 b->b_ialloc = DEFAULT_BLOCK_SIZE;
618 memset((char *)b->b_instr, 0,
619 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
620 }
621 else if (b->b_iused == b->b_ialloc) {
622 struct instr *tmp;
623 size_t oldsize, newsize;
624 oldsize = b->b_ialloc * sizeof(struct instr);
625 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (oldsize > (PY_SIZE_MAX >> 1)) {
628 PyErr_NoMemory();
629 return -1;
630 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (newsize == 0) {
633 PyErr_NoMemory();
634 return -1;
635 }
636 b->b_ialloc <<= 1;
637 tmp = (struct instr *)PyObject_Realloc(
638 (void *)b->b_instr, newsize);
639 if (tmp == NULL) {
640 PyErr_NoMemory();
641 return -1;
642 }
643 b->b_instr = tmp;
644 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
645 }
646 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647}
648
Christian Heimes2202f872008-02-06 14:31:34 +0000649/* Set the i_lineno member of the instruction at offset off if the
650 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000651 already been set. If it has been set, the call has no effect.
652
Christian Heimes2202f872008-02-06 14:31:34 +0000653 The line number is reset in the following cases:
654 - when entering a new scope
655 - on each statement
656 - on each expression that start a new line
657 - before the "except" clause
658 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000660
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000661static void
662compiler_set_lineno(struct compiler *c, int off)
663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 basicblock *b;
665 if (c->u->u_lineno_set)
666 return;
667 c->u->u_lineno_set = 1;
668 b = c->u->u_curblock;
669 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
672static int
673opcode_stack_effect(int opcode, int oparg)
674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 switch (opcode) {
676 case POP_TOP:
677 return -1;
678 case ROT_TWO:
679 case ROT_THREE:
680 return 0;
681 case DUP_TOP:
682 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000683 case DUP_TOP_TWO:
684 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 case UNARY_POSITIVE:
687 case UNARY_NEGATIVE:
688 case UNARY_NOT:
689 case UNARY_INVERT:
690 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 case SET_ADD:
693 case LIST_APPEND:
694 return -1;
695 case MAP_ADD:
696 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 case BINARY_POWER:
699 case BINARY_MULTIPLY:
700 case BINARY_MODULO:
701 case BINARY_ADD:
702 case BINARY_SUBTRACT:
703 case BINARY_SUBSCR:
704 case BINARY_FLOOR_DIVIDE:
705 case BINARY_TRUE_DIVIDE:
706 return -1;
707 case INPLACE_FLOOR_DIVIDE:
708 case INPLACE_TRUE_DIVIDE:
709 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 case INPLACE_ADD:
712 case INPLACE_SUBTRACT:
713 case INPLACE_MULTIPLY:
714 case INPLACE_MODULO:
715 return -1;
716 case STORE_SUBSCR:
717 return -3;
718 case STORE_MAP:
719 return -2;
720 case DELETE_SUBSCR:
721 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 case BINARY_LSHIFT:
724 case BINARY_RSHIFT:
725 case BINARY_AND:
726 case BINARY_XOR:
727 case BINARY_OR:
728 return -1;
729 case INPLACE_POWER:
730 return -1;
731 case GET_ITER:
732 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 case PRINT_EXPR:
735 return -1;
736 case LOAD_BUILD_CLASS:
737 return 1;
738 case INPLACE_LSHIFT:
739 case INPLACE_RSHIFT:
740 case INPLACE_AND:
741 case INPLACE_XOR:
742 case INPLACE_OR:
743 return -1;
744 case BREAK_LOOP:
745 return 0;
746 case SETUP_WITH:
747 return 7;
748 case WITH_CLEANUP:
749 return -1; /* XXX Sometimes more */
750 case STORE_LOCALS:
751 return -1;
752 case RETURN_VALUE:
753 return -1;
754 case IMPORT_STAR:
755 return -1;
756 case YIELD_VALUE:
757 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 case POP_BLOCK:
760 return 0;
761 case POP_EXCEPT:
762 return 0; /* -3 except if bad bytecode */
763 case END_FINALLY:
764 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 case STORE_NAME:
767 return -1;
768 case DELETE_NAME:
769 return 0;
770 case UNPACK_SEQUENCE:
771 return oparg-1;
772 case UNPACK_EX:
773 return (oparg&0xFF) + (oparg>>8);
774 case FOR_ITER:
775 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 case STORE_ATTR:
778 return -2;
779 case DELETE_ATTR:
780 return -1;
781 case STORE_GLOBAL:
782 return -1;
783 case DELETE_GLOBAL:
784 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 case LOAD_CONST:
786 return 1;
787 case LOAD_NAME:
788 return 1;
789 case BUILD_TUPLE:
790 case BUILD_LIST:
791 case BUILD_SET:
792 return 1-oparg;
793 case BUILD_MAP:
794 return 1;
795 case LOAD_ATTR:
796 return 0;
797 case COMPARE_OP:
798 return -1;
799 case IMPORT_NAME:
800 return -1;
801 case IMPORT_FROM:
802 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 case JUMP_FORWARD:
805 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
806 case JUMP_IF_FALSE_OR_POP: /* "" */
807 case JUMP_ABSOLUTE:
808 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 case POP_JUMP_IF_FALSE:
811 case POP_JUMP_IF_TRUE:
812 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 case LOAD_GLOBAL:
815 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 case CONTINUE_LOOP:
818 return 0;
819 case SETUP_LOOP:
820 return 0;
821 case SETUP_EXCEPT:
822 case SETUP_FINALLY:
823 return 6; /* can push 3 values for the new exception
824 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 case LOAD_FAST:
827 return 1;
828 case STORE_FAST:
829 return -1;
830 case DELETE_FAST:
831 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 case RAISE_VARARGS:
834 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000835#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 case CALL_FUNCTION:
837 return -NARGS(oparg);
838 case CALL_FUNCTION_VAR:
839 case CALL_FUNCTION_KW:
840 return -NARGS(oparg)-1;
841 case CALL_FUNCTION_VAR_KW:
842 return -NARGS(oparg)-2;
843 case MAKE_FUNCTION:
844 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
845 case MAKE_CLOSURE:
846 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000847#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 case BUILD_SLICE:
849 if (oparg == 3)
850 return -2;
851 else
852 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 case LOAD_CLOSURE:
855 return 1;
856 case LOAD_DEREF:
857 return 1;
858 case STORE_DEREF:
859 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000860 case DELETE_DEREF:
861 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 default:
863 fprintf(stderr, "opcode = %d\n", opcode);
864 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 }
867 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000868}
869
870/* Add an opcode with no argument.
871 Returns 0 on failure, 1 on success.
872*/
873
874static int
875compiler_addop(struct compiler *c, int opcode)
876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 basicblock *b;
878 struct instr *i;
879 int off;
880 off = compiler_next_instr(c, c->u->u_curblock);
881 if (off < 0)
882 return 0;
883 b = c->u->u_curblock;
884 i = &b->b_instr[off];
885 i->i_opcode = opcode;
886 i->i_hasarg = 0;
887 if (opcode == RETURN_VALUE)
888 b->b_return = 1;
889 compiler_set_lineno(c, off);
890 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891}
892
893static int
894compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyObject *t, *v;
897 Py_ssize_t arg;
898 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* necessary to make sure types aren't coerced (e.g., int and long) */
901 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
902 if (PyFloat_Check(o)) {
903 d = PyFloat_AS_DOUBLE(o);
904 /* all we need is to make the tuple different in either the 0.0
905 * or -0.0 case from all others, just to avoid the "coercion".
906 */
907 if (d == 0.0 && copysign(1.0, d) < 0.0)
908 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
909 else
910 t = PyTuple_Pack(2, o, o->ob_type);
911 }
912 else if (PyComplex_Check(o)) {
913 Py_complex z;
914 int real_negzero, imag_negzero;
915 /* For the complex case we must make complex(x, 0.)
916 different from complex(x, -0.) and complex(0., y)
917 different from complex(-0., y), for any x and y.
918 All four complex zeros must be distinguished.*/
919 z = PyComplex_AsCComplex(o);
920 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
921 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
922 if (real_negzero && imag_negzero) {
923 t = PyTuple_Pack(5, o, o->ob_type,
924 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000925 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 else if (imag_negzero) {
927 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000928 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 else if (real_negzero) {
930 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
931 }
932 else {
933 t = PyTuple_Pack(2, o, o->ob_type);
934 }
935 }
936 else {
937 t = PyTuple_Pack(2, o, o->ob_type);
938 }
939 if (t == NULL)
940 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 v = PyDict_GetItem(dict, t);
943 if (!v) {
944 if (PyErr_Occurred())
945 return -1;
946 arg = PyDict_Size(dict);
947 v = PyLong_FromLong(arg);
948 if (!v) {
949 Py_DECREF(t);
950 return -1;
951 }
952 if (PyDict_SetItem(dict, t, v) < 0) {
953 Py_DECREF(t);
954 Py_DECREF(v);
955 return -1;
956 }
957 Py_DECREF(v);
958 }
959 else
960 arg = PyLong_AsLong(v);
961 Py_DECREF(t);
962 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963}
964
965static int
966compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968{
969 int arg = compiler_add_o(c, dict, o);
970 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000971 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 return compiler_addop_i(c, opcode, arg);
973}
974
975static int
976compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978{
979 int arg;
980 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
981 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000982 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983 arg = compiler_add_o(c, dict, mangled);
984 Py_DECREF(mangled);
985 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000986 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987 return compiler_addop_i(c, opcode, arg);
988}
989
990/* Add an opcode with an integer argument.
991 Returns 0 on failure, 1 on success.
992*/
993
994static int
995compiler_addop_i(struct compiler *c, int opcode, int oparg)
996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 struct instr *i;
998 int off;
999 off = compiler_next_instr(c, c->u->u_curblock);
1000 if (off < 0)
1001 return 0;
1002 i = &c->u->u_curblock->b_instr[off];
1003 i->i_opcode = opcode;
1004 i->i_oparg = oparg;
1005 i->i_hasarg = 1;
1006 compiler_set_lineno(c, off);
1007 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008}
1009
1010static int
1011compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 struct instr *i;
1014 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 assert(b != NULL);
1017 off = compiler_next_instr(c, c->u->u_curblock);
1018 if (off < 0)
1019 return 0;
1020 i = &c->u->u_curblock->b_instr[off];
1021 i->i_opcode = opcode;
1022 i->i_target = b;
1023 i->i_hasarg = 1;
1024 if (absolute)
1025 i->i_jabs = 1;
1026 else
1027 i->i_jrel = 1;
1028 compiler_set_lineno(c, off);
1029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030}
1031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1033 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034 it as the current block. NEXT_BLOCK() also creates an implicit jump
1035 from the current block to the new block.
1036*/
1037
Thomas Wouters89f507f2006-12-13 04:49:30 +00001038/* The returns inside these macros make it impossible to decref objects
1039 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001040*/
1041
1042
1043#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (compiler_use_new_block((C)) == NULL) \
1045 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046}
1047
1048#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (compiler_next_block((C)) == NULL) \
1050 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051}
1052
1053#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (!compiler_addop((C), (OP))) \
1055 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056}
1057
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001058#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (!compiler_addop((C), (OP))) { \
1060 compiler_exit_scope(c); \
1061 return 0; \
1062 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001063}
1064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1067 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068}
1069
1070#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1072 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
1075#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (!compiler_addop_i((C), (OP), (O))) \
1077 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078}
1079
1080#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (!compiler_addop_j((C), (OP), (O), 1)) \
1082 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083}
1084
1085#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 if (!compiler_addop_j((C), (OP), (O), 0)) \
1087 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088}
1089
1090/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1091 the ASDL name to synthesize the name of the C type and the visit function.
1092*/
1093
1094#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (!compiler_visit_ ## TYPE((C), (V))) \
1096 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001097}
1098
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001099#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 if (!compiler_visit_ ## TYPE((C), (V))) { \
1101 compiler_exit_scope(c); \
1102 return 0; \
1103 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001104}
1105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (!compiler_visit_slice((C), (V), (CTX))) \
1108 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109}
1110
1111#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 int _i; \
1113 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1114 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1115 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1116 if (!compiler_visit_ ## TYPE((C), elt)) \
1117 return 0; \
1118 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119}
1120
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001121#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 int _i; \
1123 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1124 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1125 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1126 if (!compiler_visit_ ## TYPE((C), elt)) { \
1127 compiler_exit_scope(c); \
1128 return 0; \
1129 } \
1130 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001131}
1132
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133static int
1134compiler_isdocstring(stmt_ty s)
1135{
1136 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001137 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 return s->v.Expr.value->kind == Str_kind;
1139}
1140
1141/* Compile a sequence of statements, checking for a docstring. */
1142
1143static int
1144compiler_body(struct compiler *c, asdl_seq *stmts)
1145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 int i = 0;
1147 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (!asdl_seq_LEN(stmts))
1150 return 1;
1151 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1152 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1153 /* don't generate docstrings if -OO */
1154 i = 1;
1155 VISIT(c, expr, st->v.Expr.value);
1156 if (!compiler_nameop(c, __doc__, Store))
1157 return 0;
1158 }
1159 for (; i < asdl_seq_LEN(stmts); i++)
1160 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162}
1163
1164static PyCodeObject *
1165compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyCodeObject *co;
1168 int addNone = 1;
1169 static PyObject *module;
1170 if (!module) {
1171 module = PyUnicode_InternFromString("<module>");
1172 if (!module)
1173 return NULL;
1174 }
1175 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1176 if (!compiler_enter_scope(c, module, mod, 0))
1177 return NULL;
1178 switch (mod->kind) {
1179 case Module_kind:
1180 if (!compiler_body(c, mod->v.Module.body)) {
1181 compiler_exit_scope(c);
1182 return 0;
1183 }
1184 break;
1185 case Interactive_kind:
1186 c->c_interactive = 1;
1187 VISIT_SEQ_IN_SCOPE(c, stmt,
1188 mod->v.Interactive.body);
1189 break;
1190 case Expression_kind:
1191 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1192 addNone = 0;
1193 break;
1194 case Suite_kind:
1195 PyErr_SetString(PyExc_SystemError,
1196 "suite should not be possible");
1197 return 0;
1198 default:
1199 PyErr_Format(PyExc_SystemError,
1200 "module kind %d should not be possible",
1201 mod->kind);
1202 return 0;
1203 }
1204 co = assemble(c, addNone);
1205 compiler_exit_scope(c);
1206 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001207}
1208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209/* The test for LOCAL must come before the test for FREE in order to
1210 handle classes where name is both local and free. The local var is
1211 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001212*/
1213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214static int
1215get_ref_type(struct compiler *c, PyObject *name)
1216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 int scope = PyST_GetScope(c->u->u_ste, name);
1218 if (scope == 0) {
1219 char buf[350];
1220 PyOS_snprintf(buf, sizeof(buf),
1221 "unknown scope for %.100s in %.100s(%s) in %s\n"
1222 "symbols: %s\nlocals: %s\nglobals: %s",
1223 PyBytes_AS_STRING(name),
1224 PyBytes_AS_STRING(c->u->u_name),
1225 PyObject_REPR(c->u->u_ste->ste_id),
1226 c->c_filename,
1227 PyObject_REPR(c->u->u_ste->ste_symbols),
1228 PyObject_REPR(c->u->u_varnames),
1229 PyObject_REPR(c->u->u_names)
1230 );
1231 Py_FatalError(buf);
1232 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
1237static int
1238compiler_lookup_arg(PyObject *dict, PyObject *name)
1239{
1240 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001243 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001245 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001247 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001248 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
1251static int
1252compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 int i, free = PyCode_GetNumFree(co);
1255 if (free == 0) {
1256 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1257 ADDOP_I(c, MAKE_FUNCTION, args);
1258 return 1;
1259 }
1260 for (i = 0; i < free; ++i) {
1261 /* Bypass com_addop_varname because it will generate
1262 LOAD_DEREF but LOAD_CLOSURE is needed.
1263 */
1264 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1265 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 /* Special case: If a class contains a method with a
1268 free variable that has the same name as a method,
1269 the name will be considered free *and* local in the
1270 class. It should be handled by the closure, as
1271 well as by the normal name loookup logic.
1272 */
1273 reftype = get_ref_type(c, name);
1274 if (reftype == CELL)
1275 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1276 else /* (reftype == FREE) */
1277 arg = compiler_lookup_arg(c->u->u_freevars, name);
1278 if (arg == -1) {
1279 fprintf(stderr,
1280 "lookup %s in %s %d %d\n"
1281 "freevars of %s: %s\n",
1282 PyObject_REPR(name),
1283 PyBytes_AS_STRING(c->u->u_name),
1284 reftype, arg,
1285 _PyUnicode_AsString(co->co_name),
1286 PyObject_REPR(co->co_freevars));
1287 Py_FatalError("compiler_make_closure()");
1288 }
1289 ADDOP_I(c, LOAD_CLOSURE, arg);
1290 }
1291 ADDOP_I(c, BUILD_TUPLE, free);
1292 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1293 ADDOP_I(c, MAKE_CLOSURE, args);
1294 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295}
1296
1297static int
1298compiler_decorators(struct compiler *c, asdl_seq* decos)
1299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (!decos)
1303 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1306 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1307 }
1308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
1311static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001312compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 int i, default_count = 0;
1316 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1317 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1318 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1319 if (default_) {
1320 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
1321 if (!compiler_visit_expr(c, default_)) {
1322 return -1;
1323 }
1324 default_count++;
1325 }
1326 }
1327 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001328}
1329
1330static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001331compiler_visit_argannotation(struct compiler *c, identifier id,
1332 expr_ty annotation, PyObject *names)
1333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (annotation) {
1335 VISIT(c, expr, annotation);
1336 if (PyList_Append(names, id))
1337 return -1;
1338 }
1339 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001340}
1341
1342static int
1343compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1344 PyObject *names)
1345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 int i, error;
1347 for (i = 0; i < asdl_seq_LEN(args); i++) {
1348 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1349 error = compiler_visit_argannotation(
1350 c,
1351 arg->arg,
1352 arg->annotation,
1353 names);
1354 if (error)
1355 return error;
1356 }
1357 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001358}
1359
1360static int
1361compiler_visit_annotations(struct compiler *c, arguments_ty args,
1362 expr_ty returns)
1363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 /* Push arg annotations and a list of the argument names. Return the #
1365 of items pushed. The expressions are evaluated out-of-order wrt the
1366 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1369 */
1370 static identifier return_str;
1371 PyObject *names;
1372 int len;
1373 names = PyList_New(0);
1374 if (!names)
1375 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 if (compiler_visit_argannotations(c, args->args, names))
1378 goto error;
1379 if (args->varargannotation &&
1380 compiler_visit_argannotation(c, args->vararg,
1381 args->varargannotation, names))
1382 goto error;
1383 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1384 goto error;
1385 if (args->kwargannotation &&
1386 compiler_visit_argannotation(c, args->kwarg,
1387 args->kwargannotation, names))
1388 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (!return_str) {
1391 return_str = PyUnicode_InternFromString("return");
1392 if (!return_str)
1393 goto error;
1394 }
1395 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1396 goto error;
1397 }
1398
1399 len = PyList_GET_SIZE(names);
1400 if (len > 65534) {
1401 /* len must fit in 16 bits, and len is incremented below */
1402 PyErr_SetString(PyExc_SyntaxError,
1403 "too many annotations");
1404 goto error;
1405 }
1406 if (len) {
1407 /* convert names to a tuple and place on stack */
1408 PyObject *elt;
1409 int i;
1410 PyObject *s = PyTuple_New(len);
1411 if (!s)
1412 goto error;
1413 for (i = 0; i < len; i++) {
1414 elt = PyList_GET_ITEM(names, i);
1415 Py_INCREF(elt);
1416 PyTuple_SET_ITEM(s, i, elt);
1417 }
1418 ADDOP_O(c, LOAD_CONST, s, consts);
1419 Py_DECREF(s);
1420 len++; /* include the just-pushed tuple */
1421 }
1422 Py_DECREF(names);
1423 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001424
1425error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 Py_DECREF(names);
1427 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001428}
1429
1430static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431compiler_function(struct compiler *c, stmt_ty s)
1432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 PyCodeObject *co;
1434 PyObject *first_const = Py_None;
1435 arguments_ty args = s->v.FunctionDef.args;
1436 expr_ty returns = s->v.FunctionDef.returns;
1437 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1438 stmt_ty st;
1439 int i, n, docstring, kw_default_count = 0, arglength;
1440 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (!compiler_decorators(c, decos))
1445 return 0;
1446 if (args->kwonlyargs) {
1447 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1448 args->kw_defaults);
1449 if (res < 0)
1450 return 0;
1451 kw_default_count = res;
1452 }
1453 if (args->defaults)
1454 VISIT_SEQ(c, expr, args->defaults);
1455 num_annotations = compiler_visit_annotations(c, args, returns);
1456 if (num_annotations < 0)
1457 return 0;
1458 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1461 s->lineno))
1462 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1465 docstring = compiler_isdocstring(st);
1466 if (docstring && Py_OptimizeFlag < 2)
1467 first_const = st->v.Expr.value->v.Str.s;
1468 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1469 compiler_exit_scope(c);
1470 return 0;
1471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 c->u->u_argcount = asdl_seq_LEN(args->args);
1474 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1475 n = asdl_seq_LEN(s->v.FunctionDef.body);
1476 /* if there was a docstring, we need to skip the first statement */
1477 for (i = docstring; i < n; i++) {
1478 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1479 VISIT_IN_SCOPE(c, stmt, st);
1480 }
1481 co = assemble(c, 1);
1482 compiler_exit_scope(c);
1483 if (co == NULL)
1484 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 arglength = asdl_seq_LEN(args->defaults);
1487 arglength |= kw_default_count << 8;
1488 arglength |= num_annotations << 16;
1489 compiler_make_closure(c, co, arglength);
1490 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 /* decorators */
1493 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1494 ADDOP_I(c, CALL_FUNCTION, 1);
1495 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500static int
1501compiler_class(struct compiler *c, stmt_ty s)
1502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyCodeObject *co;
1504 PyObject *str;
1505 int i;
1506 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 if (!compiler_decorators(c, decos))
1509 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 /* ultimately generate code for:
1512 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1513 where:
1514 <func> is a function/closure created from the class body;
1515 it has a single argument (__locals__) where the dict
1516 (or MutableSequence) representing the locals is passed
1517 <name> is the class name
1518 <bases> is the positional arguments and *varargs argument
1519 <keywords> is the keyword arguments and **kwds argument
1520 This borrows from compiler_call.
1521 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 /* 1. compile the class body into a code object */
1524 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1525 return 0;
1526 /* this block represents what we do in the new scope */
1527 {
1528 /* use the class name for name mangling */
1529 Py_INCREF(s->v.ClassDef.name);
1530 Py_XDECREF(c->u->u_private);
1531 c->u->u_private = s->v.ClassDef.name;
1532 /* force it to have one mandatory argument */
1533 c->u->u_argcount = 1;
1534 /* load the first argument (__locals__) ... */
1535 ADDOP_I(c, LOAD_FAST, 0);
1536 /* ... and store it into f_locals */
1537 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1538 /* load (global) __name__ ... */
1539 str = PyUnicode_InternFromString("__name__");
1540 if (!str || !compiler_nameop(c, str, Load)) {
1541 Py_XDECREF(str);
1542 compiler_exit_scope(c);
1543 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001544 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 Py_DECREF(str);
1546 /* ... and store it as __module__ */
1547 str = PyUnicode_InternFromString("__module__");
1548 if (!str || !compiler_nameop(c, str, Store)) {
1549 Py_XDECREF(str);
1550 compiler_exit_scope(c);
1551 return 0;
1552 }
1553 Py_DECREF(str);
1554 /* compile the body proper */
1555 if (!compiler_body(c, s->v.ClassDef.body)) {
1556 compiler_exit_scope(c);
1557 return 0;
1558 }
1559 /* return the (empty) __class__ cell */
1560 str = PyUnicode_InternFromString("__class__");
1561 if (str == NULL) {
1562 compiler_exit_scope(c);
1563 return 0;
1564 }
1565 i = compiler_lookup_arg(c->u->u_cellvars, str);
1566 Py_DECREF(str);
1567 if (i == -1) {
1568 /* This happens when nobody references the cell */
1569 PyErr_Clear();
1570 /* Return None */
1571 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1572 }
1573 else {
1574 /* Return the cell where to store __class__ */
1575 ADDOP_I(c, LOAD_CLOSURE, i);
1576 }
1577 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1578 /* create the code object */
1579 co = assemble(c, 1);
1580 }
1581 /* leave the new scope */
1582 compiler_exit_scope(c);
1583 if (co == NULL)
1584 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 /* 2. load the 'build_class' function */
1587 ADDOP(c, LOAD_BUILD_CLASS);
1588
1589 /* 3. load a function (or closure) made from the code object */
1590 compiler_make_closure(c, co, 0);
1591 Py_DECREF(co);
1592
1593 /* 4. load class name */
1594 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1595
1596 /* 5. generate the rest of the code for the call */
1597 if (!compiler_call_helper(c, 2,
1598 s->v.ClassDef.bases,
1599 s->v.ClassDef.keywords,
1600 s->v.ClassDef.starargs,
1601 s->v.ClassDef.kwargs))
1602 return 0;
1603
1604 /* 6. apply decorators */
1605 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1606 ADDOP_I(c, CALL_FUNCTION, 1);
1607 }
1608
1609 /* 7. store into <name> */
1610 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1611 return 0;
1612 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001613}
1614
1615static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001616compiler_ifexp(struct compiler *c, expr_ty e)
1617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 basicblock *end, *next;
1619
1620 assert(e->kind == IfExp_kind);
1621 end = compiler_new_block(c);
1622 if (end == NULL)
1623 return 0;
1624 next = compiler_new_block(c);
1625 if (next == NULL)
1626 return 0;
1627 VISIT(c, expr, e->v.IfExp.test);
1628 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1629 VISIT(c, expr, e->v.IfExp.body);
1630 ADDOP_JREL(c, JUMP_FORWARD, end);
1631 compiler_use_next_block(c, next);
1632 VISIT(c, expr, e->v.IfExp.orelse);
1633 compiler_use_next_block(c, end);
1634 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001635}
1636
1637static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638compiler_lambda(struct compiler *c, expr_ty e)
1639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyCodeObject *co;
1641 static identifier name;
1642 int kw_default_count = 0, arglength;
1643 arguments_ty args = e->v.Lambda.args;
1644 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (!name) {
1647 name = PyUnicode_InternFromString("<lambda>");
1648 if (!name)
1649 return 0;
1650 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (args->kwonlyargs) {
1653 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1654 args->kw_defaults);
1655 if (res < 0) return 0;
1656 kw_default_count = res;
1657 }
1658 if (args->defaults)
1659 VISIT_SEQ(c, expr, args->defaults);
1660 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1661 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 /* Make None the first constant, so the lambda can't have a
1664 docstring. */
1665 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1666 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 c->u->u_argcount = asdl_seq_LEN(args->args);
1669 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1670 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1671 if (c->u->u_ste->ste_generator) {
1672 ADDOP_IN_SCOPE(c, POP_TOP);
1673 }
1674 else {
1675 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1676 }
1677 co = assemble(c, 1);
1678 compiler_exit_scope(c);
1679 if (co == NULL)
1680 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 arglength = asdl_seq_LEN(args->defaults);
1683 arglength |= kw_default_count << 8;
1684 compiler_make_closure(c, co, arglength);
1685 Py_DECREF(co);
1686
1687 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688}
1689
1690static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691compiler_if(struct compiler *c, stmt_ty s)
1692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 basicblock *end, *next;
1694 int constant;
1695 assert(s->kind == If_kind);
1696 end = compiler_new_block(c);
1697 if (end == NULL)
1698 return 0;
1699
1700 constant = expr_constant(s->v.If.test);
1701 /* constant = 0: "if 0"
1702 * constant = 1: "if 1", "if 2", ...
1703 * constant = -1: rest */
1704 if (constant == 0) {
1705 if (s->v.If.orelse)
1706 VISIT_SEQ(c, stmt, s->v.If.orelse);
1707 } else if (constant == 1) {
1708 VISIT_SEQ(c, stmt, s->v.If.body);
1709 } else {
1710 if (s->v.If.orelse) {
1711 next = compiler_new_block(c);
1712 if (next == NULL)
1713 return 0;
1714 }
1715 else
1716 next = end;
1717 VISIT(c, expr, s->v.If.test);
1718 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1719 VISIT_SEQ(c, stmt, s->v.If.body);
1720 ADDOP_JREL(c, JUMP_FORWARD, end);
1721 if (s->v.If.orelse) {
1722 compiler_use_next_block(c, next);
1723 VISIT_SEQ(c, stmt, s->v.If.orelse);
1724 }
1725 }
1726 compiler_use_next_block(c, end);
1727 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001728}
1729
1730static int
1731compiler_for(struct compiler *c, stmt_ty s)
1732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 start = compiler_new_block(c);
1736 cleanup = compiler_new_block(c);
1737 end = compiler_new_block(c);
1738 if (start == NULL || end == NULL || cleanup == NULL)
1739 return 0;
1740 ADDOP_JREL(c, SETUP_LOOP, end);
1741 if (!compiler_push_fblock(c, LOOP, start))
1742 return 0;
1743 VISIT(c, expr, s->v.For.iter);
1744 ADDOP(c, GET_ITER);
1745 compiler_use_next_block(c, start);
1746 ADDOP_JREL(c, FOR_ITER, cleanup);
1747 VISIT(c, expr, s->v.For.target);
1748 VISIT_SEQ(c, stmt, s->v.For.body);
1749 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1750 compiler_use_next_block(c, cleanup);
1751 ADDOP(c, POP_BLOCK);
1752 compiler_pop_fblock(c, LOOP, start);
1753 VISIT_SEQ(c, stmt, s->v.For.orelse);
1754 compiler_use_next_block(c, end);
1755 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001756}
1757
1758static int
1759compiler_while(struct compiler *c, stmt_ty s)
1760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 basicblock *loop, *orelse, *end, *anchor = NULL;
1762 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 if (constant == 0) {
1765 if (s->v.While.orelse)
1766 VISIT_SEQ(c, stmt, s->v.While.orelse);
1767 return 1;
1768 }
1769 loop = compiler_new_block(c);
1770 end = compiler_new_block(c);
1771 if (constant == -1) {
1772 anchor = compiler_new_block(c);
1773 if (anchor == NULL)
1774 return 0;
1775 }
1776 if (loop == NULL || end == NULL)
1777 return 0;
1778 if (s->v.While.orelse) {
1779 orelse = compiler_new_block(c);
1780 if (orelse == NULL)
1781 return 0;
1782 }
1783 else
1784 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 ADDOP_JREL(c, SETUP_LOOP, end);
1787 compiler_use_next_block(c, loop);
1788 if (!compiler_push_fblock(c, LOOP, loop))
1789 return 0;
1790 if (constant == -1) {
1791 VISIT(c, expr, s->v.While.test);
1792 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1793 }
1794 VISIT_SEQ(c, stmt, s->v.While.body);
1795 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 /* XXX should the two POP instructions be in a separate block
1798 if there is no else clause ?
1799 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (constant == -1) {
1802 compiler_use_next_block(c, anchor);
1803 ADDOP(c, POP_BLOCK);
1804 }
1805 compiler_pop_fblock(c, LOOP, loop);
1806 if (orelse != NULL) /* what if orelse is just pass? */
1807 VISIT_SEQ(c, stmt, s->v.While.orelse);
1808 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811}
1812
1813static int
1814compiler_continue(struct compiler *c)
1815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1817 static const char IN_FINALLY_ERROR_MSG[] =
1818 "'continue' not supported inside 'finally' clause";
1819 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (!c->u->u_nfblocks)
1822 return compiler_error(c, LOOP_ERROR_MSG);
1823 i = c->u->u_nfblocks - 1;
1824 switch (c->u->u_fblock[i].fb_type) {
1825 case LOOP:
1826 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1827 break;
1828 case EXCEPT:
1829 case FINALLY_TRY:
1830 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1831 /* Prevent continue anywhere under a finally
1832 even if hidden in a sub-try or except. */
1833 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1834 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1835 }
1836 if (i == -1)
1837 return compiler_error(c, LOOP_ERROR_MSG);
1838 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1839 break;
1840 case FINALLY_END:
1841 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1842 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845}
1846
1847/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848
1849 SETUP_FINALLY L
1850 <code for body>
1851 POP_BLOCK
1852 LOAD_CONST <None>
1853 L: <code for finalbody>
1854 END_FINALLY
1855
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856 The special instructions use the block stack. Each block
1857 stack entry contains the instruction that created it (here
1858 SETUP_FINALLY), the level of the value stack at the time the
1859 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 Pushes the current value stack level and the label
1863 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 Pops en entry from the block stack, and pops the value
1866 stack until its level is the same as indicated on the
1867 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 Pops a variable number of entries from the *value* stack
1870 and re-raises the exception they specify. The number of
1871 entries popped depends on the (pseudo) exception type.
1872
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873 The block stack is unwound when an exception is raised:
1874 when a SETUP_FINALLY entry is found, the exception is pushed
1875 onto the value stack (and the exception condition is cleared),
1876 and the interpreter jumps to the label gotten from the block
1877 stack.
1878*/
1879
1880static int
1881compiler_try_finally(struct compiler *c, stmt_ty s)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 basicblock *body, *end;
1884 body = compiler_new_block(c);
1885 end = compiler_new_block(c);
1886 if (body == NULL || end == NULL)
1887 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 ADDOP_JREL(c, SETUP_FINALLY, end);
1890 compiler_use_next_block(c, body);
1891 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1892 return 0;
1893 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1894 ADDOP(c, POP_BLOCK);
1895 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1898 compiler_use_next_block(c, end);
1899 if (!compiler_push_fblock(c, FINALLY_END, end))
1900 return 0;
1901 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1902 ADDOP(c, END_FINALLY);
1903 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906}
1907
1908/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001909 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910 (The contents of the value stack is shown in [], with the top
1911 at the right; 'tb' is trace-back info, 'val' the exception's
1912 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913
1914 Value stack Label Instruction Argument
1915 [] SETUP_EXCEPT L1
1916 [] <code for S>
1917 [] POP_BLOCK
1918 [] JUMP_FORWARD L0
1919
1920 [tb, val, exc] L1: DUP )
1921 [tb, val, exc, exc] <evaluate E1> )
1922 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1923 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1924 [tb, val, exc] POP
1925 [tb, val] <assign to V1> (or POP if no V1)
1926 [tb] POP
1927 [] <code for S1>
1928 JUMP_FORWARD L0
1929
1930 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 .............................etc.......................
1932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1934
1935 [] L0: <next statement>
1936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937 Of course, parts are not generated if Vi or Ei is not present.
1938*/
1939static int
1940compiler_try_except(struct compiler *c, stmt_ty s)
1941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 basicblock *body, *orelse, *except, *end;
1943 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 body = compiler_new_block(c);
1946 except = compiler_new_block(c);
1947 orelse = compiler_new_block(c);
1948 end = compiler_new_block(c);
1949 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1950 return 0;
1951 ADDOP_JREL(c, SETUP_EXCEPT, except);
1952 compiler_use_next_block(c, body);
1953 if (!compiler_push_fblock(c, EXCEPT, body))
1954 return 0;
1955 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1956 ADDOP(c, POP_BLOCK);
1957 compiler_pop_fblock(c, EXCEPT, body);
1958 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1959 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1960 compiler_use_next_block(c, except);
1961 for (i = 0; i < n; i++) {
1962 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1963 s->v.TryExcept.handlers, i);
1964 if (!handler->v.ExceptHandler.type && i < n-1)
1965 return compiler_error(c, "default 'except:' must be last");
1966 c->u->u_lineno_set = 0;
1967 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00001968 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 except = compiler_new_block(c);
1970 if (except == NULL)
1971 return 0;
1972 if (handler->v.ExceptHandler.type) {
1973 ADDOP(c, DUP_TOP);
1974 VISIT(c, expr, handler->v.ExceptHandler.type);
1975 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1976 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
1977 }
1978 ADDOP(c, POP_TOP);
1979 if (handler->v.ExceptHandler.name) {
1980 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 cleanup_end = compiler_new_block(c);
1983 cleanup_body = compiler_new_block(c);
1984 if(!(cleanup_end || cleanup_body))
1985 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
1988 ADDOP(c, POP_TOP);
1989
1990 /*
1991 try:
1992 # body
1993 except type as name:
1994 try:
1995 # body
1996 finally:
1997 name = None
1998 del name
1999 */
2000
2001 /* second try: */
2002 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2003 compiler_use_next_block(c, cleanup_body);
2004 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2005 return 0;
2006
2007 /* second # body */
2008 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2009 ADDOP(c, POP_BLOCK);
2010 ADDOP(c, POP_EXCEPT);
2011 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2012
2013 /* finally: */
2014 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2015 compiler_use_next_block(c, cleanup_end);
2016 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2017 return 0;
2018
2019 /* name = None */
2020 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2021 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2022
2023 /* del name */
2024 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
2025
2026 ADDOP(c, END_FINALLY);
2027 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
2028 }
2029 else {
2030 basicblock *cleanup_body;
2031
2032 cleanup_body = compiler_new_block(c);
2033 if(!cleanup_body)
2034 return 0;
2035
Guido van Rossumb940e112007-01-10 16:19:56 +00002036 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 ADDOP(c, POP_TOP);
2038 compiler_use_next_block(c, cleanup_body);
2039 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2040 return 0;
2041 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2042 ADDOP(c, POP_EXCEPT);
2043 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2044 }
2045 ADDOP_JREL(c, JUMP_FORWARD, end);
2046 compiler_use_next_block(c, except);
2047 }
2048 ADDOP(c, END_FINALLY);
2049 compiler_use_next_block(c, orelse);
2050 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2051 compiler_use_next_block(c, end);
2052 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053}
2054
2055static int
2056compiler_import_as(struct compiler *c, identifier name, identifier asname)
2057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 /* The IMPORT_NAME opcode was already generated. This function
2059 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 If there is a dot in name, we need to split it and emit a
2062 LOAD_ATTR for each name.
2063 */
2064 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2065 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
2066 if (dot) {
2067 /* Consume the base module name to get the first attribute */
2068 src = dot + 1;
2069 while (dot) {
2070 /* NB src is only defined when dot != NULL */
2071 PyObject *attr;
2072 dot = Py_UNICODE_strchr(src, '.');
2073 attr = PyUnicode_FromUnicode(src,
2074 dot ? dot - src : Py_UNICODE_strlen(src));
2075 if (!attr)
2076 return -1;
2077 ADDOP_O(c, LOAD_ATTR, attr, names);
2078 Py_DECREF(attr);
2079 src = dot + 1;
2080 }
2081 }
2082 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083}
2084
2085static int
2086compiler_import(struct compiler *c, stmt_ty s)
2087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* The Import node stores a module name like a.b.c as a single
2089 string. This is convenient for all cases except
2090 import a.b.c as d
2091 where we need to parse that string to extract the individual
2092 module names.
2093 XXX Perhaps change the representation to make this case simpler?
2094 */
2095 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 for (i = 0; i < n; i++) {
2098 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2099 int r;
2100 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 level = PyLong_FromLong(0);
2103 if (level == NULL)
2104 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 ADDOP_O(c, LOAD_CONST, level, consts);
2107 Py_DECREF(level);
2108 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2109 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (alias->asname) {
2112 r = compiler_import_as(c, alias->name, alias->asname);
2113 if (!r)
2114 return r;
2115 }
2116 else {
2117 identifier tmp = alias->name;
2118 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2119 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
2120 if (dot)
2121 tmp = PyUnicode_FromUnicode(base,
2122 dot - base);
2123 r = compiler_nameop(c, tmp, Store);
2124 if (dot) {
2125 Py_DECREF(tmp);
2126 }
2127 if (!r)
2128 return r;
2129 }
2130 }
2131 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132}
2133
2134static int
2135compiler_from_import(struct compiler *c, stmt_ty s)
2136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 PyObject *names = PyTuple_New(n);
2140 PyObject *level;
2141 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (!empty_string) {
2144 empty_string = PyUnicode_FromString("");
2145 if (!empty_string)
2146 return 0;
2147 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (!names)
2150 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 level = PyLong_FromLong(s->v.ImportFrom.level);
2153 if (!level) {
2154 Py_DECREF(names);
2155 return 0;
2156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 /* build up the names */
2159 for (i = 0; i < n; i++) {
2160 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2161 Py_INCREF(alias->name);
2162 PyTuple_SET_ITEM(names, i, alias->name);
2163 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2166 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2167 Py_DECREF(level);
2168 Py_DECREF(names);
2169 return compiler_error(c, "from __future__ imports must occur "
2170 "at the beginning of the file");
2171 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 ADDOP_O(c, LOAD_CONST, level, consts);
2174 Py_DECREF(level);
2175 ADDOP_O(c, LOAD_CONST, names, consts);
2176 Py_DECREF(names);
2177 if (s->v.ImportFrom.module) {
2178 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2179 }
2180 else {
2181 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2182 }
2183 for (i = 0; i < n; i++) {
2184 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2185 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
2188 assert(n == 1);
2189 ADDOP(c, IMPORT_STAR);
2190 return 1;
2191 }
2192
2193 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2194 store_name = alias->name;
2195 if (alias->asname)
2196 store_name = alias->asname;
2197
2198 if (!compiler_nameop(c, store_name, Store)) {
2199 Py_DECREF(names);
2200 return 0;
2201 }
2202 }
2203 /* remove imported module */
2204 ADDOP(c, POP_TOP);
2205 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002206}
2207
2208static int
2209compiler_assert(struct compiler *c, stmt_ty s)
2210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 static PyObject *assertion_error = NULL;
2212 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (Py_OptimizeFlag)
2215 return 1;
2216 if (assertion_error == NULL) {
2217 assertion_error = PyUnicode_InternFromString("AssertionError");
2218 if (assertion_error == NULL)
2219 return 0;
2220 }
2221 if (s->v.Assert.test->kind == Tuple_kind &&
2222 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2223 const char* msg =
2224 "assertion is always true, perhaps remove parentheses?";
2225 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2226 c->u->u_lineno, NULL, NULL) == -1)
2227 return 0;
2228 }
2229 VISIT(c, expr, s->v.Assert.test);
2230 end = compiler_new_block(c);
2231 if (end == NULL)
2232 return 0;
2233 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2234 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2235 if (s->v.Assert.msg) {
2236 VISIT(c, expr, s->v.Assert.msg);
2237 ADDOP_I(c, CALL_FUNCTION, 1);
2238 }
2239 ADDOP_I(c, RAISE_VARARGS, 1);
2240 compiler_use_next_block(c, end);
2241 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242}
2243
2244static int
2245compiler_visit_stmt(struct compiler *c, stmt_ty s)
2246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* Always assign a lineno to the next instruction for a stmt. */
2250 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002251 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 switch (s->kind) {
2255 case FunctionDef_kind:
2256 return compiler_function(c, s);
2257 case ClassDef_kind:
2258 return compiler_class(c, s);
2259 case Return_kind:
2260 if (c->u->u_ste->ste_type != FunctionBlock)
2261 return compiler_error(c, "'return' outside function");
2262 if (s->v.Return.value) {
2263 VISIT(c, expr, s->v.Return.value);
2264 }
2265 else
2266 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2267 ADDOP(c, RETURN_VALUE);
2268 break;
2269 case Delete_kind:
2270 VISIT_SEQ(c, expr, s->v.Delete.targets)
2271 break;
2272 case Assign_kind:
2273 n = asdl_seq_LEN(s->v.Assign.targets);
2274 VISIT(c, expr, s->v.Assign.value);
2275 for (i = 0; i < n; i++) {
2276 if (i < n - 1)
2277 ADDOP(c, DUP_TOP);
2278 VISIT(c, expr,
2279 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2280 }
2281 break;
2282 case AugAssign_kind:
2283 return compiler_augassign(c, s);
2284 case For_kind:
2285 return compiler_for(c, s);
2286 case While_kind:
2287 return compiler_while(c, s);
2288 case If_kind:
2289 return compiler_if(c, s);
2290 case Raise_kind:
2291 n = 0;
2292 if (s->v.Raise.exc) {
2293 VISIT(c, expr, s->v.Raise.exc);
2294 n++;
2295 if (s->v.Raise.cause) {
2296 VISIT(c, expr, s->v.Raise.cause);
2297 n++;
2298 }
2299 }
2300 ADDOP_I(c, RAISE_VARARGS, n);
2301 break;
2302 case TryExcept_kind:
2303 return compiler_try_except(c, s);
2304 case TryFinally_kind:
2305 return compiler_try_finally(c, s);
2306 case Assert_kind:
2307 return compiler_assert(c, s);
2308 case Import_kind:
2309 return compiler_import(c, s);
2310 case ImportFrom_kind:
2311 return compiler_from_import(c, s);
2312 case Global_kind:
2313 case Nonlocal_kind:
2314 break;
2315 case Expr_kind:
2316 if (c->c_interactive && c->c_nestlevel <= 1) {
2317 VISIT(c, expr, s->v.Expr.value);
2318 ADDOP(c, PRINT_EXPR);
2319 }
2320 else if (s->v.Expr.value->kind != Str_kind &&
2321 s->v.Expr.value->kind != Num_kind) {
2322 VISIT(c, expr, s->v.Expr.value);
2323 ADDOP(c, POP_TOP);
2324 }
2325 break;
2326 case Pass_kind:
2327 break;
2328 case Break_kind:
2329 if (!compiler_in_loop(c))
2330 return compiler_error(c, "'break' outside loop");
2331 ADDOP(c, BREAK_LOOP);
2332 break;
2333 case Continue_kind:
2334 return compiler_continue(c);
2335 case With_kind:
2336 return compiler_with(c, s);
2337 }
2338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339}
2340
2341static int
2342unaryop(unaryop_ty op)
2343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 switch (op) {
2345 case Invert:
2346 return UNARY_INVERT;
2347 case Not:
2348 return UNARY_NOT;
2349 case UAdd:
2350 return UNARY_POSITIVE;
2351 case USub:
2352 return UNARY_NEGATIVE;
2353 default:
2354 PyErr_Format(PyExc_SystemError,
2355 "unary op %d should not be possible", op);
2356 return 0;
2357 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358}
2359
2360static int
2361binop(struct compiler *c, operator_ty op)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 switch (op) {
2364 case Add:
2365 return BINARY_ADD;
2366 case Sub:
2367 return BINARY_SUBTRACT;
2368 case Mult:
2369 return BINARY_MULTIPLY;
2370 case Div:
2371 return BINARY_TRUE_DIVIDE;
2372 case Mod:
2373 return BINARY_MODULO;
2374 case Pow:
2375 return BINARY_POWER;
2376 case LShift:
2377 return BINARY_LSHIFT;
2378 case RShift:
2379 return BINARY_RSHIFT;
2380 case BitOr:
2381 return BINARY_OR;
2382 case BitXor:
2383 return BINARY_XOR;
2384 case BitAnd:
2385 return BINARY_AND;
2386 case FloorDiv:
2387 return BINARY_FLOOR_DIVIDE;
2388 default:
2389 PyErr_Format(PyExc_SystemError,
2390 "binary op %d should not be possible", op);
2391 return 0;
2392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393}
2394
2395static int
2396cmpop(cmpop_ty op)
2397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 switch (op) {
2399 case Eq:
2400 return PyCmp_EQ;
2401 case NotEq:
2402 return PyCmp_NE;
2403 case Lt:
2404 return PyCmp_LT;
2405 case LtE:
2406 return PyCmp_LE;
2407 case Gt:
2408 return PyCmp_GT;
2409 case GtE:
2410 return PyCmp_GE;
2411 case Is:
2412 return PyCmp_IS;
2413 case IsNot:
2414 return PyCmp_IS_NOT;
2415 case In:
2416 return PyCmp_IN;
2417 case NotIn:
2418 return PyCmp_NOT_IN;
2419 default:
2420 return PyCmp_BAD;
2421 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422}
2423
2424static int
2425inplace_binop(struct compiler *c, operator_ty op)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 switch (op) {
2428 case Add:
2429 return INPLACE_ADD;
2430 case Sub:
2431 return INPLACE_SUBTRACT;
2432 case Mult:
2433 return INPLACE_MULTIPLY;
2434 case Div:
2435 return INPLACE_TRUE_DIVIDE;
2436 case Mod:
2437 return INPLACE_MODULO;
2438 case Pow:
2439 return INPLACE_POWER;
2440 case LShift:
2441 return INPLACE_LSHIFT;
2442 case RShift:
2443 return INPLACE_RSHIFT;
2444 case BitOr:
2445 return INPLACE_OR;
2446 case BitXor:
2447 return INPLACE_XOR;
2448 case BitAnd:
2449 return INPLACE_AND;
2450 case FloorDiv:
2451 return INPLACE_FLOOR_DIVIDE;
2452 default:
2453 PyErr_Format(PyExc_SystemError,
2454 "inplace binary op %d should not be possible", op);
2455 return 0;
2456 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002457}
2458
2459static int
2460compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 int op, scope, arg;
2463 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 PyObject *dict = c->u->u_names;
2466 PyObject *mangled;
2467 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 mangled = _Py_Mangle(c->u->u_private, name);
2470 if (!mangled)
2471 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 op = 0;
2474 optype = OP_NAME;
2475 scope = PyST_GetScope(c->u->u_ste, mangled);
2476 switch (scope) {
2477 case FREE:
2478 dict = c->u->u_freevars;
2479 optype = OP_DEREF;
2480 break;
2481 case CELL:
2482 dict = c->u->u_cellvars;
2483 optype = OP_DEREF;
2484 break;
2485 case LOCAL:
2486 if (c->u->u_ste->ste_type == FunctionBlock)
2487 optype = OP_FAST;
2488 break;
2489 case GLOBAL_IMPLICIT:
2490 if (c->u->u_ste->ste_type == FunctionBlock &&
2491 !c->u->u_ste->ste_unoptimized)
2492 optype = OP_GLOBAL;
2493 break;
2494 case GLOBAL_EXPLICIT:
2495 optype = OP_GLOBAL;
2496 break;
2497 default:
2498 /* scope can be 0 */
2499 break;
2500 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* XXX Leave assert here, but handle __doc__ and the like better */
2503 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 switch (optype) {
2506 case OP_DEREF:
2507 switch (ctx) {
2508 case Load: op = LOAD_DEREF; break;
2509 case Store: op = STORE_DEREF; break;
2510 case AugLoad:
2511 case AugStore:
2512 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002513 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 case Param:
2515 default:
2516 PyErr_SetString(PyExc_SystemError,
2517 "param invalid for deref variable");
2518 return 0;
2519 }
2520 break;
2521 case OP_FAST:
2522 switch (ctx) {
2523 case Load: op = LOAD_FAST; break;
2524 case Store: op = STORE_FAST; break;
2525 case Del: op = DELETE_FAST; break;
2526 case AugLoad:
2527 case AugStore:
2528 break;
2529 case Param:
2530 default:
2531 PyErr_SetString(PyExc_SystemError,
2532 "param invalid for local variable");
2533 return 0;
2534 }
2535 ADDOP_O(c, op, mangled, varnames);
2536 Py_DECREF(mangled);
2537 return 1;
2538 case OP_GLOBAL:
2539 switch (ctx) {
2540 case Load: op = LOAD_GLOBAL; break;
2541 case Store: op = STORE_GLOBAL; break;
2542 case Del: op = DELETE_GLOBAL; break;
2543 case AugLoad:
2544 case AugStore:
2545 break;
2546 case Param:
2547 default:
2548 PyErr_SetString(PyExc_SystemError,
2549 "param invalid for global variable");
2550 return 0;
2551 }
2552 break;
2553 case OP_NAME:
2554 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002555 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 case Store: op = STORE_NAME; break;
2557 case Del: op = DELETE_NAME; break;
2558 case AugLoad:
2559 case AugStore:
2560 break;
2561 case Param:
2562 default:
2563 PyErr_SetString(PyExc_SystemError,
2564 "param invalid for name variable");
2565 return 0;
2566 }
2567 break;
2568 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 assert(op);
2571 arg = compiler_add_o(c, dict, mangled);
2572 Py_DECREF(mangled);
2573 if (arg < 0)
2574 return 0;
2575 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576}
2577
2578static int
2579compiler_boolop(struct compiler *c, expr_ty e)
2580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 basicblock *end;
2582 int jumpi, i, n;
2583 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 assert(e->kind == BoolOp_kind);
2586 if (e->v.BoolOp.op == And)
2587 jumpi = JUMP_IF_FALSE_OR_POP;
2588 else
2589 jumpi = JUMP_IF_TRUE_OR_POP;
2590 end = compiler_new_block(c);
2591 if (end == NULL)
2592 return 0;
2593 s = e->v.BoolOp.values;
2594 n = asdl_seq_LEN(s) - 1;
2595 assert(n >= 0);
2596 for (i = 0; i < n; ++i) {
2597 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2598 ADDOP_JABS(c, jumpi, end);
2599 }
2600 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2601 compiler_use_next_block(c, end);
2602 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603}
2604
2605static int
2606compiler_list(struct compiler *c, expr_ty e)
2607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 int n = asdl_seq_LEN(e->v.List.elts);
2609 if (e->v.List.ctx == Store) {
2610 int i, seen_star = 0;
2611 for (i = 0; i < n; i++) {
2612 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2613 if (elt->kind == Starred_kind && !seen_star) {
2614 if ((i >= (1 << 8)) ||
2615 (n-i-1 >= (INT_MAX >> 8)))
2616 return compiler_error(c,
2617 "too many expressions in "
2618 "star-unpacking assignment");
2619 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2620 seen_star = 1;
2621 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2622 } else if (elt->kind == Starred_kind) {
2623 return compiler_error(c,
2624 "two starred expressions in assignment");
2625 }
2626 }
2627 if (!seen_star) {
2628 ADDOP_I(c, UNPACK_SEQUENCE, n);
2629 }
2630 }
2631 VISIT_SEQ(c, expr, e->v.List.elts);
2632 if (e->v.List.ctx == Load) {
2633 ADDOP_I(c, BUILD_LIST, n);
2634 }
2635 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636}
2637
2638static int
2639compiler_tuple(struct compiler *c, expr_ty e)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 int n = asdl_seq_LEN(e->v.Tuple.elts);
2642 if (e->v.Tuple.ctx == Store) {
2643 int i, seen_star = 0;
2644 for (i = 0; i < n; i++) {
2645 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2646 if (elt->kind == Starred_kind && !seen_star) {
2647 if ((i >= (1 << 8)) ||
2648 (n-i-1 >= (INT_MAX >> 8)))
2649 return compiler_error(c,
2650 "too many expressions in "
2651 "star-unpacking assignment");
2652 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2653 seen_star = 1;
2654 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2655 } else if (elt->kind == Starred_kind) {
2656 return compiler_error(c,
2657 "two starred expressions in assignment");
2658 }
2659 }
2660 if (!seen_star) {
2661 ADDOP_I(c, UNPACK_SEQUENCE, n);
2662 }
2663 }
2664 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2665 if (e->v.Tuple.ctx == Load) {
2666 ADDOP_I(c, BUILD_TUPLE, n);
2667 }
2668 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669}
2670
2671static int
2672compiler_compare(struct compiler *c, expr_ty e)
2673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 int i, n;
2675 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2678 VISIT(c, expr, e->v.Compare.left);
2679 n = asdl_seq_LEN(e->v.Compare.ops);
2680 assert(n > 0);
2681 if (n > 1) {
2682 cleanup = compiler_new_block(c);
2683 if (cleanup == NULL)
2684 return 0;
2685 VISIT(c, expr,
2686 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2687 }
2688 for (i = 1; i < n; i++) {
2689 ADDOP(c, DUP_TOP);
2690 ADDOP(c, ROT_THREE);
2691 ADDOP_I(c, COMPARE_OP,
2692 cmpop((cmpop_ty)(asdl_seq_GET(
2693 e->v.Compare.ops, i - 1))));
2694 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2695 NEXT_BLOCK(c);
2696 if (i < (n - 1))
2697 VISIT(c, expr,
2698 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2699 }
2700 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2701 ADDOP_I(c, COMPARE_OP,
2702 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2703 if (n > 1) {
2704 basicblock *end = compiler_new_block(c);
2705 if (end == NULL)
2706 return 0;
2707 ADDOP_JREL(c, JUMP_FORWARD, end);
2708 compiler_use_next_block(c, cleanup);
2709 ADDOP(c, ROT_TWO);
2710 ADDOP(c, POP_TOP);
2711 compiler_use_next_block(c, end);
2712 }
2713 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714}
2715
2716static int
2717compiler_call(struct compiler *c, expr_ty e)
2718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 VISIT(c, expr, e->v.Call.func);
2720 return compiler_call_helper(c, 0,
2721 e->v.Call.args,
2722 e->v.Call.keywords,
2723 e->v.Call.starargs,
2724 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002725}
2726
2727/* shared code between compiler_call and compiler_class */
2728static int
2729compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 int n, /* Args already pushed */
2731 asdl_seq *args,
2732 asdl_seq *keywords,
2733 expr_ty starargs,
2734 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 n += asdl_seq_LEN(args);
2739 VISIT_SEQ(c, expr, args);
2740 if (keywords) {
2741 VISIT_SEQ(c, keyword, keywords);
2742 n |= asdl_seq_LEN(keywords) << 8;
2743 }
2744 if (starargs) {
2745 VISIT(c, expr, starargs);
2746 code |= 1;
2747 }
2748 if (kwargs) {
2749 VISIT(c, expr, kwargs);
2750 code |= 2;
2751 }
2752 switch (code) {
2753 case 0:
2754 ADDOP_I(c, CALL_FUNCTION, n);
2755 break;
2756 case 1:
2757 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2758 break;
2759 case 2:
2760 ADDOP_I(c, CALL_FUNCTION_KW, n);
2761 break;
2762 case 3:
2763 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2764 break;
2765 }
2766 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767}
2768
Nick Coghlan650f0d02007-04-15 12:05:43 +00002769
2770/* List and set comprehensions and generator expressions work by creating a
2771 nested function to perform the actual iteration. This means that the
2772 iteration variables don't leak into the current scope.
2773 The defined function is called immediately following its definition, with the
2774 result of that call being the result of the expression.
2775 The LC/SC version returns the populated container, while the GE version is
2776 flagged in symtable.c as a generator, so it returns the generator object
2777 when the function is called.
2778 This code *knows* that the loop cannot contain break, continue, or return,
2779 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2780
2781 Possible cleanups:
2782 - iterate over the generator sequence instead of using recursion
2783*/
2784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786compiler_comprehension_generator(struct compiler *c,
2787 asdl_seq *generators, int gen_index,
2788 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 /* generate code for the iterator, then each of the ifs,
2791 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 comprehension_ty gen;
2794 basicblock *start, *anchor, *skip, *if_cleanup;
2795 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 start = compiler_new_block(c);
2798 skip = compiler_new_block(c);
2799 if_cleanup = compiler_new_block(c);
2800 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2803 anchor == NULL)
2804 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 if (gen_index == 0) {
2809 /* Receive outermost iter as an implicit argument */
2810 c->u->u_argcount = 1;
2811 ADDOP_I(c, LOAD_FAST, 0);
2812 }
2813 else {
2814 /* Sub-iter - calculate on the fly */
2815 VISIT(c, expr, gen->iter);
2816 ADDOP(c, GET_ITER);
2817 }
2818 compiler_use_next_block(c, start);
2819 ADDOP_JREL(c, FOR_ITER, anchor);
2820 NEXT_BLOCK(c);
2821 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 /* XXX this needs to be cleaned up...a lot! */
2824 n = asdl_seq_LEN(gen->ifs);
2825 for (i = 0; i < n; i++) {
2826 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2827 VISIT(c, expr, e);
2828 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2829 NEXT_BLOCK(c);
2830 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 if (++gen_index < asdl_seq_LEN(generators))
2833 if (!compiler_comprehension_generator(c,
2834 generators, gen_index,
2835 elt, val, type))
2836 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 /* only append after the last for generator */
2839 if (gen_index >= asdl_seq_LEN(generators)) {
2840 /* comprehension specific code */
2841 switch (type) {
2842 case COMP_GENEXP:
2843 VISIT(c, expr, elt);
2844 ADDOP(c, YIELD_VALUE);
2845 ADDOP(c, POP_TOP);
2846 break;
2847 case COMP_LISTCOMP:
2848 VISIT(c, expr, elt);
2849 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2850 break;
2851 case COMP_SETCOMP:
2852 VISIT(c, expr, elt);
2853 ADDOP_I(c, SET_ADD, gen_index + 1);
2854 break;
2855 case COMP_DICTCOMP:
2856 /* With 'd[k] = v', v is evaluated before k, so we do
2857 the same. */
2858 VISIT(c, expr, val);
2859 VISIT(c, expr, elt);
2860 ADDOP_I(c, MAP_ADD, gen_index + 1);
2861 break;
2862 default:
2863 return 0;
2864 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 compiler_use_next_block(c, skip);
2867 }
2868 compiler_use_next_block(c, if_cleanup);
2869 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2870 compiler_use_next_block(c, anchor);
2871
2872 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873}
2874
2875static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002876compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 PyCodeObject *co = NULL;
2880 expr_ty outermost_iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 outermost_iter = ((comprehension_ty)
2883 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2886 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (type != COMP_GENEXP) {
2889 int op;
2890 switch (type) {
2891 case COMP_LISTCOMP:
2892 op = BUILD_LIST;
2893 break;
2894 case COMP_SETCOMP:
2895 op = BUILD_SET;
2896 break;
2897 case COMP_DICTCOMP:
2898 op = BUILD_MAP;
2899 break;
2900 default:
2901 PyErr_Format(PyExc_SystemError,
2902 "unknown comprehension type %d", type);
2903 goto error_in_scope;
2904 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 ADDOP_I(c, op, 0);
2907 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 if (!compiler_comprehension_generator(c, generators, 0, elt,
2910 val, type))
2911 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 if (type != COMP_GENEXP) {
2914 ADDOP(c, RETURN_VALUE);
2915 }
2916
2917 co = assemble(c, 1);
2918 compiler_exit_scope(c);
2919 if (co == NULL)
2920 goto error;
2921
2922 if (!compiler_make_closure(c, co, 0))
2923 goto error;
2924 Py_DECREF(co);
2925
2926 VISIT(c, expr, outermost_iter);
2927 ADDOP(c, GET_ITER);
2928 ADDOP_I(c, CALL_FUNCTION, 1);
2929 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002930error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002932error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 Py_XDECREF(co);
2934 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002935}
2936
2937static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938compiler_genexp(struct compiler *c, expr_ty e)
2939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 static identifier name;
2941 if (!name) {
2942 name = PyUnicode_FromString("<genexpr>");
2943 if (!name)
2944 return 0;
2945 }
2946 assert(e->kind == GeneratorExp_kind);
2947 return compiler_comprehension(c, e, COMP_GENEXP, name,
2948 e->v.GeneratorExp.generators,
2949 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950}
2951
2952static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002953compiler_listcomp(struct compiler *c, expr_ty e)
2954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 static identifier name;
2956 if (!name) {
2957 name = PyUnicode_FromString("<listcomp>");
2958 if (!name)
2959 return 0;
2960 }
2961 assert(e->kind == ListComp_kind);
2962 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2963 e->v.ListComp.generators,
2964 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002965}
2966
2967static int
2968compiler_setcomp(struct compiler *c, expr_ty e)
2969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 static identifier name;
2971 if (!name) {
2972 name = PyUnicode_FromString("<setcomp>");
2973 if (!name)
2974 return 0;
2975 }
2976 assert(e->kind == SetComp_kind);
2977 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2978 e->v.SetComp.generators,
2979 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002980}
2981
2982
2983static int
2984compiler_dictcomp(struct compiler *c, expr_ty e)
2985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 static identifier name;
2987 if (!name) {
2988 name = PyUnicode_FromString("<dictcomp>");
2989 if (!name)
2990 return 0;
2991 }
2992 assert(e->kind == DictComp_kind);
2993 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2994 e->v.DictComp.generators,
2995 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002996}
2997
2998
2999static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003000compiler_visit_keyword(struct compiler *c, keyword_ty k)
3001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3003 VISIT(c, expr, k->value);
3004 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005}
3006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008 whether they are true or false.
3009
3010 Return values: 1 for true, 0 for false, -1 for non-constant.
3011 */
3012
3013static int
3014expr_constant(expr_ty e)
3015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 char *id;
3017 switch (e->kind) {
3018 case Ellipsis_kind:
3019 return 1;
3020 case Num_kind:
3021 return PyObject_IsTrue(e->v.Num.n);
3022 case Str_kind:
3023 return PyObject_IsTrue(e->v.Str.s);
3024 case Name_kind:
3025 /* optimize away names that can't be reassigned */
3026 id = PyBytes_AS_STRING(
3027 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
3028 if (strcmp(id, "True") == 0) return 1;
3029 if (strcmp(id, "False") == 0) return 0;
3030 if (strcmp(id, "None") == 0) return 0;
3031 if (strcmp(id, "__debug__") == 0)
3032 return ! Py_OptimizeFlag;
3033 /* fall through */
3034 default:
3035 return -1;
3036 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037}
3038
Guido van Rossumc2e20742006-02-27 22:32:47 +00003039/*
3040 Implements the with statement from PEP 343.
3041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003043
3044 with EXPR as VAR:
3045 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046
Guido van Rossumc2e20742006-02-27 22:32:47 +00003047 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048
Thomas Wouters477c8d52006-05-27 19:21:47 +00003049 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003050 exit = context.__exit__ # not calling it
3051 value = context.__enter__()
3052 try:
3053 VAR = value # if VAR present in the syntax
3054 BLOCK
3055 finally:
3056 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003058 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003060 exit(*exc)
3061 */
3062static int
3063compiler_with(struct compiler *c, stmt_ty s)
3064{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003065 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003066
3067 assert(s->kind == With_kind);
3068
Guido van Rossumc2e20742006-02-27 22:32:47 +00003069 block = compiler_new_block(c);
3070 finally = compiler_new_block(c);
3071 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003072 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003073
Thomas Wouters477c8d52006-05-27 19:21:47 +00003074 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003076 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003077
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003078 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079 compiler_use_next_block(c, block);
3080 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003081 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003082 }
3083
3084 if (s->v.With.optional_vars) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003085 VISIT(c, expr, s->v.With.optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003086 }
3087 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003089 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003090 }
3091
3092 /* BLOCK code */
3093 VISIT_SEQ(c, stmt, s->v.With.body);
3094
3095 /* End of try block; start the finally block */
3096 ADDOP(c, POP_BLOCK);
3097 compiler_pop_fblock(c, FINALLY_TRY, block);
3098
3099 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3100 compiler_use_next_block(c, finally);
3101 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003102 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003103
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003104 /* Finally block starts; context.__exit__ is on the stack under
3105 the exception or return information. Just issue our magic
3106 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003107 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003108
3109 /* Finally block ends. */
3110 ADDOP(c, END_FINALLY);
3111 compiler_pop_fblock(c, FINALLY_END, finally);
3112 return 1;
3113}
3114
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115static int
3116compiler_visit_expr(struct compiler *c, expr_ty e)
3117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 /* If expr e has a different line number than the last expr/stmt,
3121 set a new line number for the next instruction.
3122 */
3123 if (e->lineno > c->u->u_lineno) {
3124 c->u->u_lineno = e->lineno;
3125 c->u->u_lineno_set = 0;
3126 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003127 /* Updating the column offset is always harmless. */
3128 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 switch (e->kind) {
3130 case BoolOp_kind:
3131 return compiler_boolop(c, e);
3132 case BinOp_kind:
3133 VISIT(c, expr, e->v.BinOp.left);
3134 VISIT(c, expr, e->v.BinOp.right);
3135 ADDOP(c, binop(c, e->v.BinOp.op));
3136 break;
3137 case UnaryOp_kind:
3138 VISIT(c, expr, e->v.UnaryOp.operand);
3139 ADDOP(c, unaryop(e->v.UnaryOp.op));
3140 break;
3141 case Lambda_kind:
3142 return compiler_lambda(c, e);
3143 case IfExp_kind:
3144 return compiler_ifexp(c, e);
3145 case Dict_kind:
3146 n = asdl_seq_LEN(e->v.Dict.values);
3147 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3148 for (i = 0; i < n; i++) {
3149 VISIT(c, expr,
3150 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3151 VISIT(c, expr,
3152 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3153 ADDOP(c, STORE_MAP);
3154 }
3155 break;
3156 case Set_kind:
3157 n = asdl_seq_LEN(e->v.Set.elts);
3158 VISIT_SEQ(c, expr, e->v.Set.elts);
3159 ADDOP_I(c, BUILD_SET, n);
3160 break;
3161 case GeneratorExp_kind:
3162 return compiler_genexp(c, e);
3163 case ListComp_kind:
3164 return compiler_listcomp(c, e);
3165 case SetComp_kind:
3166 return compiler_setcomp(c, e);
3167 case DictComp_kind:
3168 return compiler_dictcomp(c, e);
3169 case Yield_kind:
3170 if (c->u->u_ste->ste_type != FunctionBlock)
3171 return compiler_error(c, "'yield' outside function");
3172 if (e->v.Yield.value) {
3173 VISIT(c, expr, e->v.Yield.value);
3174 }
3175 else {
3176 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3177 }
3178 ADDOP(c, YIELD_VALUE);
3179 break;
3180 case Compare_kind:
3181 return compiler_compare(c, e);
3182 case Call_kind:
3183 return compiler_call(c, e);
3184 case Num_kind:
3185 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3186 break;
3187 case Str_kind:
3188 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3189 break;
3190 case Bytes_kind:
3191 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3192 break;
3193 case Ellipsis_kind:
3194 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3195 break;
3196 /* The following exprs can be assignment targets. */
3197 case Attribute_kind:
3198 if (e->v.Attribute.ctx != AugStore)
3199 VISIT(c, expr, e->v.Attribute.value);
3200 switch (e->v.Attribute.ctx) {
3201 case AugLoad:
3202 ADDOP(c, DUP_TOP);
3203 /* Fall through to load */
3204 case Load:
3205 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3206 break;
3207 case AugStore:
3208 ADDOP(c, ROT_TWO);
3209 /* Fall through to save */
3210 case Store:
3211 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3212 break;
3213 case Del:
3214 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3215 break;
3216 case Param:
3217 default:
3218 PyErr_SetString(PyExc_SystemError,
3219 "param invalid in attribute expression");
3220 return 0;
3221 }
3222 break;
3223 case Subscript_kind:
3224 switch (e->v.Subscript.ctx) {
3225 case AugLoad:
3226 VISIT(c, expr, e->v.Subscript.value);
3227 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3228 break;
3229 case Load:
3230 VISIT(c, expr, e->v.Subscript.value);
3231 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3232 break;
3233 case AugStore:
3234 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3235 break;
3236 case Store:
3237 VISIT(c, expr, e->v.Subscript.value);
3238 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3239 break;
3240 case Del:
3241 VISIT(c, expr, e->v.Subscript.value);
3242 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3243 break;
3244 case Param:
3245 default:
3246 PyErr_SetString(PyExc_SystemError,
3247 "param invalid in subscript expression");
3248 return 0;
3249 }
3250 break;
3251 case Starred_kind:
3252 switch (e->v.Starred.ctx) {
3253 case Store:
3254 /* In all legitimate cases, the Starred node was already replaced
3255 * by compiler_list/compiler_tuple. XXX: is that okay? */
3256 return compiler_error(c,
3257 "starred assignment target must be in a list or tuple");
3258 default:
3259 return compiler_error(c,
3260 "can use starred expression only as assignment target");
3261 }
3262 break;
3263 case Name_kind:
3264 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3265 /* child nodes of List and Tuple will have expr_context set */
3266 case List_kind:
3267 return compiler_list(c, e);
3268 case Tuple_kind:
3269 return compiler_tuple(c, e);
3270 }
3271 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272}
3273
3274static int
3275compiler_augassign(struct compiler *c, stmt_ty s)
3276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 expr_ty e = s->v.AugAssign.target;
3278 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 switch (e->kind) {
3283 case Attribute_kind:
3284 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3285 AugLoad, e->lineno, e->col_offset, c->c_arena);
3286 if (auge == NULL)
3287 return 0;
3288 VISIT(c, expr, auge);
3289 VISIT(c, expr, s->v.AugAssign.value);
3290 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3291 auge->v.Attribute.ctx = AugStore;
3292 VISIT(c, expr, auge);
3293 break;
3294 case Subscript_kind:
3295 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3296 AugLoad, e->lineno, e->col_offset, c->c_arena);
3297 if (auge == NULL)
3298 return 0;
3299 VISIT(c, expr, auge);
3300 VISIT(c, expr, s->v.AugAssign.value);
3301 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3302 auge->v.Subscript.ctx = AugStore;
3303 VISIT(c, expr, auge);
3304 break;
3305 case Name_kind:
3306 if (!compiler_nameop(c, e->v.Name.id, Load))
3307 return 0;
3308 VISIT(c, expr, s->v.AugAssign.value);
3309 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3310 return compiler_nameop(c, e->v.Name.id, Store);
3311 default:
3312 PyErr_Format(PyExc_SystemError,
3313 "invalid node type (%d) for augmented assignment",
3314 e->kind);
3315 return 0;
3316 }
3317 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318}
3319
3320static int
3321compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 struct fblockinfo *f;
3324 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3325 PyErr_SetString(PyExc_SystemError,
3326 "too many statically nested blocks");
3327 return 0;
3328 }
3329 f = &c->u->u_fblock[c->u->u_nfblocks++];
3330 f->fb_type = t;
3331 f->fb_block = b;
3332 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333}
3334
3335static void
3336compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 struct compiler_unit *u = c->u;
3339 assert(u->u_nfblocks > 0);
3340 u->u_nfblocks--;
3341 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3342 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343}
3344
Thomas Wouters89f507f2006-12-13 04:49:30 +00003345static int
3346compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 int i;
3348 struct compiler_unit *u = c->u;
3349 for (i = 0; i < u->u_nfblocks; ++i) {
3350 if (u->u_fblock[i].fb_type == LOOP)
3351 return 1;
3352 }
3353 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003354}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355/* Raises a SyntaxError and returns 0.
3356 If something goes wrong, a different exception may be raised.
3357*/
3358
3359static int
3360compiler_error(struct compiler *c, const char *errstr)
3361{
Victor Stinnerc0499822010-10-17 19:16:33 +00003362 PyObject *loc, *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3366 if (!loc) {
3367 Py_INCREF(Py_None);
3368 loc = Py_None;
3369 }
Victor Stinnerc0499822010-10-17 19:16:33 +00003370 if (c->c_filename != NULL) {
3371 filename = PyUnicode_DecodeFSDefault(c->c_filename);
3372 if (!filename)
3373 goto exit;
3374 }
3375 else {
3376 Py_INCREF(Py_None);
3377 filename = Py_None;
3378 }
3379 u = Py_BuildValue("(NiiO)", filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003380 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 if (!u)
3382 goto exit;
3383 v = Py_BuildValue("(zO)", errstr, u);
3384 if (!v)
3385 goto exit;
3386 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 Py_DECREF(loc);
3389 Py_XDECREF(u);
3390 Py_XDECREF(v);
3391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392}
3393
3394static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395compiler_handle_subscr(struct compiler *c, const char *kind,
3396 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 /* XXX this code is duplicated */
3401 switch (ctx) {
3402 case AugLoad: /* fall through to Load */
3403 case Load: op = BINARY_SUBSCR; break;
3404 case AugStore:/* fall through to Store */
3405 case Store: op = STORE_SUBSCR; break;
3406 case Del: op = DELETE_SUBSCR; break;
3407 case Param:
3408 PyErr_Format(PyExc_SystemError,
3409 "invalid %s kind %d in subscript\n",
3410 kind, ctx);
3411 return 0;
3412 }
3413 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003414 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 }
3416 else if (ctx == AugStore) {
3417 ADDOP(c, ROT_THREE);
3418 }
3419 ADDOP(c, op);
3420 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421}
3422
3423static int
3424compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 int n = 2;
3427 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 /* only handles the cases where BUILD_SLICE is emitted */
3430 if (s->v.Slice.lower) {
3431 VISIT(c, expr, s->v.Slice.lower);
3432 }
3433 else {
3434 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3435 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 if (s->v.Slice.upper) {
3438 VISIT(c, expr, s->v.Slice.upper);
3439 }
3440 else {
3441 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3442 }
3443
3444 if (s->v.Slice.step) {
3445 n++;
3446 VISIT(c, expr, s->v.Slice.step);
3447 }
3448 ADDOP_I(c, BUILD_SLICE, n);
3449 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450}
3451
3452static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3454 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 switch (s->kind) {
3457 case Slice_kind:
3458 return compiler_slice(c, s, ctx);
3459 case Index_kind:
3460 VISIT(c, expr, s->v.Index.value);
3461 break;
3462 case ExtSlice_kind:
3463 default:
3464 PyErr_SetString(PyExc_SystemError,
3465 "extended slice invalid in nested slice");
3466 return 0;
3467 }
3468 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469}
3470
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003471static int
3472compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 char * kindname = NULL;
3475 switch (s->kind) {
3476 case Index_kind:
3477 kindname = "index";
3478 if (ctx != AugStore) {
3479 VISIT(c, expr, s->v.Index.value);
3480 }
3481 break;
3482 case Slice_kind:
3483 kindname = "slice";
3484 if (ctx != AugStore) {
3485 if (!compiler_slice(c, s, ctx))
3486 return 0;
3487 }
3488 break;
3489 case ExtSlice_kind:
3490 kindname = "extended slice";
3491 if (ctx != AugStore) {
3492 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3493 for (i = 0; i < n; i++) {
3494 slice_ty sub = (slice_ty)asdl_seq_GET(
3495 s->v.ExtSlice.dims, i);
3496 if (!compiler_visit_nested_slice(c, sub, ctx))
3497 return 0;
3498 }
3499 ADDOP_I(c, BUILD_TUPLE, n);
3500 }
3501 break;
3502 default:
3503 PyErr_Format(PyExc_SystemError,
3504 "invalid subscript kind %d", s->kind);
3505 return 0;
3506 }
3507 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003508}
3509
Thomas Wouters89f507f2006-12-13 04:49:30 +00003510/* End of the compiler section, beginning of the assembler section */
3511
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512/* do depth-first search of basic block graph, starting with block.
3513 post records the block indices in post-order.
3514
3515 XXX must handle implicit jumps from one block to next
3516*/
3517
Thomas Wouters89f507f2006-12-13 04:49:30 +00003518struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 PyObject *a_bytecode; /* string containing bytecode */
3520 int a_offset; /* offset into bytecode */
3521 int a_nblocks; /* number of reachable blocks */
3522 basicblock **a_postorder; /* list of blocks in dfs postorder */
3523 PyObject *a_lnotab; /* string containing lnotab */
3524 int a_lnotab_off; /* offset into lnotab */
3525 int a_lineno; /* last lineno of emitted instruction */
3526 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003527};
3528
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529static void
3530dfs(struct compiler *c, basicblock *b, struct assembler *a)
3531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 int i;
3533 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 if (b->b_seen)
3536 return;
3537 b->b_seen = 1;
3538 if (b->b_next != NULL)
3539 dfs(c, b->b_next, a);
3540 for (i = 0; i < b->b_iused; i++) {
3541 instr = &b->b_instr[i];
3542 if (instr->i_jrel || instr->i_jabs)
3543 dfs(c, instr->i_target, a);
3544 }
3545 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546}
3547
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003548static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 int i, target_depth;
3552 struct instr *instr;
3553 if (b->b_seen || b->b_startdepth >= depth)
3554 return maxdepth;
3555 b->b_seen = 1;
3556 b->b_startdepth = depth;
3557 for (i = 0; i < b->b_iused; i++) {
3558 instr = &b->b_instr[i];
3559 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3560 if (depth > maxdepth)
3561 maxdepth = depth;
3562 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3563 if (instr->i_jrel || instr->i_jabs) {
3564 target_depth = depth;
3565 if (instr->i_opcode == FOR_ITER) {
3566 target_depth = depth-2;
3567 } else if (instr->i_opcode == SETUP_FINALLY ||
3568 instr->i_opcode == SETUP_EXCEPT) {
3569 target_depth = depth+3;
3570 if (target_depth > maxdepth)
3571 maxdepth = target_depth;
3572 }
3573 maxdepth = stackdepth_walk(c, instr->i_target,
3574 target_depth, maxdepth);
3575 if (instr->i_opcode == JUMP_ABSOLUTE ||
3576 instr->i_opcode == JUMP_FORWARD) {
3577 goto out; /* remaining code is dead */
3578 }
3579 }
3580 }
3581 if (b->b_next)
3582 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 b->b_seen = 0;
3585 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586}
3587
3588/* Find the flow path that needs the largest stack. We assume that
3589 * cycles in the flow graph have no net effect on the stack depth.
3590 */
3591static int
3592stackdepth(struct compiler *c)
3593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 basicblock *b, *entryblock;
3595 entryblock = NULL;
3596 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3597 b->b_seen = 0;
3598 b->b_startdepth = INT_MIN;
3599 entryblock = b;
3600 }
3601 if (!entryblock)
3602 return 0;
3603 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604}
3605
3606static int
3607assemble_init(struct assembler *a, int nblocks, int firstlineno)
3608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 memset(a, 0, sizeof(struct assembler));
3610 a->a_lineno = firstlineno;
3611 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3612 if (!a->a_bytecode)
3613 return 0;
3614 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3615 if (!a->a_lnotab)
3616 return 0;
3617 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3618 PyErr_NoMemory();
3619 return 0;
3620 }
3621 a->a_postorder = (basicblock **)PyObject_Malloc(
3622 sizeof(basicblock *) * nblocks);
3623 if (!a->a_postorder) {
3624 PyErr_NoMemory();
3625 return 0;
3626 }
3627 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628}
3629
3630static void
3631assemble_free(struct assembler *a)
3632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 Py_XDECREF(a->a_bytecode);
3634 Py_XDECREF(a->a_lnotab);
3635 if (a->a_postorder)
3636 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637}
3638
3639/* Return the size of a basic block in bytes. */
3640
3641static int
3642instrsize(struct instr *instr)
3643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 if (!instr->i_hasarg)
3645 return 1; /* 1 byte for the opcode*/
3646 if (instr->i_oparg > 0xffff)
3647 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3648 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649}
3650
3651static int
3652blocksize(basicblock *b)
3653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 int i;
3655 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 for (i = 0; i < b->b_iused; i++)
3658 size += instrsize(&b->b_instr[i]);
3659 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660}
3661
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003662/* Appends a pair to the end of the line number table, a_lnotab, representing
3663 the instruction's bytecode offset and line number. See
3664 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003665
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003666static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 int d_bytecode, d_lineno;
3670 int len;
3671 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 d_bytecode = a->a_offset - a->a_lineno_off;
3674 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 assert(d_bytecode >= 0);
3677 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 if(d_bytecode == 0 && d_lineno == 0)
3680 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 if (d_bytecode > 255) {
3683 int j, nbytes, ncodes = d_bytecode / 255;
3684 nbytes = a->a_lnotab_off + 2 * ncodes;
3685 len = PyBytes_GET_SIZE(a->a_lnotab);
3686 if (nbytes >= len) {
3687 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3688 len = nbytes;
3689 else if (len <= INT_MAX / 2)
3690 len *= 2;
3691 else {
3692 PyErr_NoMemory();
3693 return 0;
3694 }
3695 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3696 return 0;
3697 }
3698 lnotab = (unsigned char *)
3699 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3700 for (j = 0; j < ncodes; j++) {
3701 *lnotab++ = 255;
3702 *lnotab++ = 0;
3703 }
3704 d_bytecode -= ncodes * 255;
3705 a->a_lnotab_off += ncodes * 2;
3706 }
3707 assert(d_bytecode <= 255);
3708 if (d_lineno > 255) {
3709 int j, nbytes, ncodes = d_lineno / 255;
3710 nbytes = a->a_lnotab_off + 2 * ncodes;
3711 len = PyBytes_GET_SIZE(a->a_lnotab);
3712 if (nbytes >= len) {
3713 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3714 len = nbytes;
3715 else if (len <= INT_MAX / 2)
3716 len *= 2;
3717 else {
3718 PyErr_NoMemory();
3719 return 0;
3720 }
3721 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3722 return 0;
3723 }
3724 lnotab = (unsigned char *)
3725 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3726 *lnotab++ = d_bytecode;
3727 *lnotab++ = 255;
3728 d_bytecode = 0;
3729 for (j = 1; j < ncodes; j++) {
3730 *lnotab++ = 0;
3731 *lnotab++ = 255;
3732 }
3733 d_lineno -= ncodes * 255;
3734 a->a_lnotab_off += ncodes * 2;
3735 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 len = PyBytes_GET_SIZE(a->a_lnotab);
3738 if (a->a_lnotab_off + 2 >= len) {
3739 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3740 return 0;
3741 }
3742 lnotab = (unsigned char *)
3743 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 a->a_lnotab_off += 2;
3746 if (d_bytecode) {
3747 *lnotab++ = d_bytecode;
3748 *lnotab++ = d_lineno;
3749 }
3750 else { /* First line of a block; def stmt, etc. */
3751 *lnotab++ = 0;
3752 *lnotab++ = d_lineno;
3753 }
3754 a->a_lineno = i->i_lineno;
3755 a->a_lineno_off = a->a_offset;
3756 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003757}
3758
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759/* assemble_emit()
3760 Extend the bytecode with a new instruction.
3761 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003762*/
3763
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003764static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 int size, arg = 0, ext = 0;
3768 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3769 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 size = instrsize(i);
3772 if (i->i_hasarg) {
3773 arg = i->i_oparg;
3774 ext = arg >> 16;
3775 }
3776 if (i->i_lineno && !assemble_lnotab(a, i))
3777 return 0;
3778 if (a->a_offset + size >= len) {
3779 if (len > PY_SSIZE_T_MAX / 2)
3780 return 0;
3781 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3782 return 0;
3783 }
3784 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3785 a->a_offset += size;
3786 if (size == 6) {
3787 assert(i->i_hasarg);
3788 *code++ = (char)EXTENDED_ARG;
3789 *code++ = ext & 0xff;
3790 *code++ = ext >> 8;
3791 arg &= 0xffff;
3792 }
3793 *code++ = i->i_opcode;
3794 if (i->i_hasarg) {
3795 assert(size == 3 || size == 6);
3796 *code++ = arg & 0xff;
3797 *code++ = arg >> 8;
3798 }
3799 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003800}
3801
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003802static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003803assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 basicblock *b;
3806 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3807 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 /* Compute the size of each block and fixup jump args.
3810 Replace block pointer with position in bytecode. */
3811 do {
3812 totsize = 0;
3813 for (i = a->a_nblocks - 1; i >= 0; i--) {
3814 b = a->a_postorder[i];
3815 bsize = blocksize(b);
3816 b->b_offset = totsize;
3817 totsize += bsize;
3818 }
3819 last_extended_arg_count = extended_arg_count;
3820 extended_arg_count = 0;
3821 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3822 bsize = b->b_offset;
3823 for (i = 0; i < b->b_iused; i++) {
3824 struct instr *instr = &b->b_instr[i];
3825 /* Relative jumps are computed relative to
3826 the instruction pointer after fetching
3827 the jump instruction.
3828 */
3829 bsize += instrsize(instr);
3830 if (instr->i_jabs)
3831 instr->i_oparg = instr->i_target->b_offset;
3832 else if (instr->i_jrel) {
3833 int delta = instr->i_target->b_offset - bsize;
3834 instr->i_oparg = delta;
3835 }
3836 else
3837 continue;
3838 if (instr->i_oparg > 0xffff)
3839 extended_arg_count++;
3840 }
3841 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 /* XXX: This is an awful hack that could hurt performance, but
3844 on the bright side it should work until we come up
3845 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 The issue is that in the first loop blocksize() is called
3848 which calls instrsize() which requires i_oparg be set
3849 appropriately. There is a bootstrap problem because
3850 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 So we loop until we stop seeing new EXTENDED_ARGs.
3853 The only EXTENDED_ARGs that could be popping up are
3854 ones in jump instructions. So this should converge
3855 fairly quickly.
3856 */
3857 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003858}
3859
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003860static PyObject *
3861dict_keys_inorder(PyObject *dict, int offset)
3862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 PyObject *tuple, *k, *v;
3864 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 tuple = PyTuple_New(size);
3867 if (tuple == NULL)
3868 return NULL;
3869 while (PyDict_Next(dict, &pos, &k, &v)) {
3870 i = PyLong_AS_LONG(v);
3871 /* The keys of the dictionary are tuples. (see compiler_add_o)
3872 The object we want is always first, though. */
3873 k = PyTuple_GET_ITEM(k, 0);
3874 Py_INCREF(k);
3875 assert((i - offset) < size);
3876 assert((i - offset) >= 0);
3877 PyTuple_SET_ITEM(tuple, i - offset, k);
3878 }
3879 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003880}
3881
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003882static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 PySTEntryObject *ste = c->u->u_ste;
3886 int flags = 0, n;
3887 if (ste->ste_type != ModuleBlock)
3888 flags |= CO_NEWLOCALS;
3889 if (ste->ste_type == FunctionBlock) {
3890 if (!ste->ste_unoptimized)
3891 flags |= CO_OPTIMIZED;
3892 if (ste->ste_nested)
3893 flags |= CO_NESTED;
3894 if (ste->ste_generator)
3895 flags |= CO_GENERATOR;
3896 if (ste->ste_varargs)
3897 flags |= CO_VARARGS;
3898 if (ste->ste_varkeywords)
3899 flags |= CO_VARKEYWORDS;
3900 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 /* (Only) inherit compilerflags in PyCF_MASK */
3903 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 n = PyDict_Size(c->u->u_freevars);
3906 if (n < 0)
3907 return -1;
3908 if (n == 0) {
3909 n = PyDict_Size(c->u->u_cellvars);
3910 if (n < 0)
3911 return -1;
3912 if (n == 0) {
3913 flags |= CO_NOFREE;
3914 }
3915 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003918}
3919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920static PyCodeObject *
3921makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 PyObject *tmp;
3924 PyCodeObject *co = NULL;
3925 PyObject *consts = NULL;
3926 PyObject *names = NULL;
3927 PyObject *varnames = NULL;
3928 PyObject *filename = NULL;
3929 PyObject *name = NULL;
3930 PyObject *freevars = NULL;
3931 PyObject *cellvars = NULL;
3932 PyObject *bytecode = NULL;
3933 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 tmp = dict_keys_inorder(c->u->u_consts, 0);
3936 if (!tmp)
3937 goto error;
3938 consts = PySequence_List(tmp); /* optimize_code requires a list */
3939 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 names = dict_keys_inorder(c->u->u_names, 0);
3942 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3943 if (!consts || !names || !varnames)
3944 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3947 if (!cellvars)
3948 goto error;
3949 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3950 if (!freevars)
3951 goto error;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00003952 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 if (!filename)
3954 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 nlocals = PyDict_Size(c->u->u_varnames);
3957 flags = compute_code_flags(c);
3958 if (flags < 0)
3959 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3962 if (!bytecode)
3963 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3966 if (!tmp)
3967 goto error;
3968 Py_DECREF(consts);
3969 consts = tmp;
3970
3971 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3972 nlocals, stackdepth(c), flags,
3973 bytecode, consts, names, varnames,
3974 freevars, cellvars,
3975 filename, c->u->u_name,
3976 c->u->u_firstlineno,
3977 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003978 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 Py_XDECREF(consts);
3980 Py_XDECREF(names);
3981 Py_XDECREF(varnames);
3982 Py_XDECREF(filename);
3983 Py_XDECREF(name);
3984 Py_XDECREF(freevars);
3985 Py_XDECREF(cellvars);
3986 Py_XDECREF(bytecode);
3987 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003988}
3989
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003990
3991/* For debugging purposes only */
3992#if 0
3993static void
3994dump_instr(const struct instr *i)
3995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 const char *jrel = i->i_jrel ? "jrel " : "";
3997 const char *jabs = i->i_jabs ? "jabs " : "";
3998 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 *arg = '\0';
4001 if (i->i_hasarg)
4002 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4005 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004006}
4007
4008static void
4009dump_basicblock(const basicblock *b)
4010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 const char *seen = b->b_seen ? "seen " : "";
4012 const char *b_return = b->b_return ? "return " : "";
4013 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4014 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4015 if (b->b_instr) {
4016 int i;
4017 for (i = 0; i < b->b_iused; i++) {
4018 fprintf(stderr, " [%02d] ", i);
4019 dump_instr(b->b_instr + i);
4020 }
4021 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004022}
4023#endif
4024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025static PyCodeObject *
4026assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 basicblock *b, *entryblock;
4029 struct assembler a;
4030 int i, j, nblocks;
4031 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 /* Make sure every block that falls off the end returns None.
4034 XXX NEXT_BLOCK() isn't quite right, because if the last
4035 block ends with a jump or return b_next shouldn't set.
4036 */
4037 if (!c->u->u_curblock->b_return) {
4038 NEXT_BLOCK(c);
4039 if (addNone)
4040 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4041 ADDOP(c, RETURN_VALUE);
4042 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 nblocks = 0;
4045 entryblock = NULL;
4046 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4047 nblocks++;
4048 entryblock = b;
4049 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 /* Set firstlineno if it wasn't explicitly set. */
4052 if (!c->u->u_firstlineno) {
4053 if (entryblock && entryblock->b_instr)
4054 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4055 else
4056 c->u->u_firstlineno = 1;
4057 }
4058 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4059 goto error;
4060 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 /* Can't modify the bytecode after computing jump offsets. */
4063 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 /* Emit code in reverse postorder from dfs. */
4066 for (i = a.a_nblocks - 1; i >= 0; i--) {
4067 b = a.a_postorder[i];
4068 for (j = 0; j < b->b_iused; j++)
4069 if (!assemble_emit(&a, &b->b_instr[j]))
4070 goto error;
4071 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4074 goto error;
4075 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4076 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004079 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 assemble_free(&a);
4081 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004082}