blob: 19e7cb2b3f2314861c3e7d089a48e4c662b4ad6b [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
Georg Brandl8334fd92010-12-04 10:26:46 +0000142 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 int c_interactive; /* true if in interactive mode */
144 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 struct compiler_unit *u; /* compiler state for current block */
147 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
148 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149};
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151static int compiler_enter_scope(struct compiler *, identifier, void *, int);
152static void compiler_free(struct compiler *);
153static basicblock *compiler_new_block(struct compiler *);
154static int compiler_next_instr(struct compiler *, basicblock *);
155static int compiler_addop(struct compiler *, int);
156static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
157static int compiler_addop_i(struct compiler *, int, int);
158static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159static basicblock *compiler_use_new_block(struct compiler *);
160static int compiler_error(struct compiler *, const char *);
161static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
162
163static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
164static int compiler_visit_stmt(struct compiler *, stmt_ty);
165static int compiler_visit_keyword(struct compiler *, keyword_ty);
166static int compiler_visit_expr(struct compiler *, expr_ty);
167static int compiler_augassign(struct compiler *, stmt_ty);
168static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170
171static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175/* Returns true if there is a loop on the fblock stack. */
176static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177
178static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000179static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180
Guido van Rossumc2e20742006-02-27 22:32:47 +0000181static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000182static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 asdl_seq *args,
184 asdl_seq *keywords,
185 expr_ty starargs,
186 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static PyCodeObject *assemble(struct compiler *, int addNone);
189static PyObject *__doc__;
190
Benjamin Petersonb173f782009-05-05 22:31:58 +0000191#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Name mangling: __private becomes _classname__private.
197 This is independent from how the name is used. */
198 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
199 Py_UNICODE *buffer;
200 size_t nlen, plen;
201 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
202 name == NULL || name[0] != '_' || name[1] != '_') {
203 Py_INCREF(ident);
204 return ident;
205 }
206 p = PyUnicode_AS_UNICODE(privateobj);
207 nlen = Py_UNICODE_strlen(name);
208 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 The only time a name with a dot can occur is when
211 we are compiling an import statement that has a
212 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 TODO(jhylton): Decide whether we want to support
215 mangling of the module name, e.g. __M.X.
216 */
217 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
218 || Py_UNICODE_strchr(name, '.')) {
219 Py_INCREF(ident);
220 return ident; /* Don't mangle __whatever__ */
221 }
222 /* Strip leading underscores from class name */
223 while (*p == '_')
224 p++;
225 if (*p == 0) {
226 Py_INCREF(ident);
227 return ident; /* Don't mangle if class is just underscores */
228 }
229 plen = Py_UNICODE_strlen(p);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 assert(1 <= PY_SSIZE_T_MAX - nlen);
232 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
235 if (!ident)
236 return 0;
237 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
238 buffer = PyUnicode_AS_UNICODE(ident);
239 buffer[0] = '_';
240 Py_UNICODE_strncpy(buffer+1, p, plen);
241 Py_UNICODE_strcpy(buffer+1+plen, name);
242 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000243}
244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245static int
246compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 c->c_stack = PyList_New(0);
251 if (!c->c_stack)
252 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255}
256
257PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +0000258PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
259 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 struct compiler c;
262 PyCodeObject *co = NULL;
263 PyCompilerFlags local_flags;
264 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (!__doc__) {
267 __doc__ = PyUnicode_InternFromString("__doc__");
268 if (!__doc__)
269 return NULL;
270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (!compiler_init(&c))
273 return NULL;
274 c.c_filename = filename;
275 c.c_arena = arena;
276 c.c_future = PyFuture_FromAST(mod, filename);
277 if (c.c_future == NULL)
278 goto finally;
279 if (!flags) {
280 local_flags.cf_flags = 0;
281 flags = &local_flags;
282 }
283 merged = c.c_future->ff_features | flags->cf_flags;
284 c.c_future->ff_features = merged;
285 flags->cf_flags = merged;
286 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000287 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 c.c_st = PySymtable_Build(mod, filename, c.c_future);
291 if (c.c_st == NULL) {
292 if (!PyErr_Occurred())
293 PyErr_SetString(PyExc_SystemError, "no symtable");
294 goto finally;
295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
Thomas Wouters1175c432006-02-27 22:49:54 +0000299 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 compiler_free(&c);
301 assert(co || PyErr_Occurred());
302 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303}
304
305PyCodeObject *
306PyNode_Compile(struct _node *n, const char *filename)
307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 PyCodeObject *co = NULL;
309 mod_ty mod;
310 PyArena *arena = PyArena_New();
311 if (!arena)
312 return NULL;
313 mod = PyAST_FromNode(n, NULL, filename, arena);
314 if (mod)
315 co = PyAST_Compile(mod, filename, NULL, arena);
316 PyArena_Free(arena);
317 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000318}
319
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (c->c_st)
324 PySymtable_Free(c->c_st);
325 if (c->c_future)
326 PyObject_Free(c->c_future);
327 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000328}
329
Guido van Rossum79f25d91997-04-29 20:08:16 +0000330static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 Py_ssize_t i, n;
334 PyObject *v, *k;
335 PyObject *dict = PyDict_New();
336 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 n = PyList_Size(list);
339 for (i = 0; i < n; i++) {
340 v = PyLong_FromLong(i);
341 if (!v) {
342 Py_DECREF(dict);
343 return NULL;
344 }
345 k = PyList_GET_ITEM(list, i);
346 k = PyTuple_Pack(2, k, k->ob_type);
347 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
348 Py_XDECREF(k);
349 Py_DECREF(v);
350 Py_DECREF(dict);
351 return NULL;
352 }
353 Py_DECREF(k);
354 Py_DECREF(v);
355 }
356 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357}
358
359/* Return new dict containing names from src that match scope(s).
360
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000361src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000363values are integers, starting at offset and increasing by one for
364each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365*/
366
367static PyObject *
368dictbytype(PyObject *src, int scope_type, int flag, int offset)
369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 Py_ssize_t pos = 0, i = offset, scope;
371 PyObject *k, *v, *dest = PyDict_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 assert(offset >= 0);
374 if (dest == NULL)
375 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 while (PyDict_Next(src, &pos, &k, &v)) {
378 /* XXX this should probably be a macro in symtable.h */
379 long vi;
380 assert(PyLong_Check(v));
381 vi = PyLong_AS_LONG(v);
382 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (scope == scope_type || vi & flag) {
385 PyObject *tuple, *item = PyLong_FromLong(i);
386 if (item == NULL) {
387 Py_DECREF(dest);
388 return NULL;
389 }
390 i++;
391 tuple = PyTuple_Pack(2, k, k->ob_type);
392 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
393 Py_DECREF(item);
394 Py_DECREF(dest);
395 Py_XDECREF(tuple);
396 return NULL;
397 }
398 Py_DECREF(item);
399 Py_DECREF(tuple);
400 }
401 }
402 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000403}
404
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405static void
406compiler_unit_check(struct compiler_unit *u)
407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 basicblock *block;
409 for (block = u->u_blocks; block != NULL; block = block->b_list) {
410 assert((void *)block != (void *)0xcbcbcbcb);
411 assert((void *)block != (void *)0xfbfbfbfb);
412 assert((void *)block != (void *)0xdbdbdbdb);
413 if (block->b_instr != NULL) {
414 assert(block->b_ialloc > 0);
415 assert(block->b_iused > 0);
416 assert(block->b_ialloc >= block->b_iused);
417 }
418 else {
419 assert (block->b_iused == 0);
420 assert (block->b_ialloc == 0);
421 }
422 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423}
424
425static void
426compiler_unit_free(struct compiler_unit *u)
427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 compiler_unit_check(u);
431 b = u->u_blocks;
432 while (b != NULL) {
433 if (b->b_instr)
434 PyObject_Free((void *)b->b_instr);
435 next = b->b_list;
436 PyObject_Free((void *)b);
437 b = next;
438 }
439 Py_CLEAR(u->u_ste);
440 Py_CLEAR(u->u_name);
441 Py_CLEAR(u->u_consts);
442 Py_CLEAR(u->u_names);
443 Py_CLEAR(u->u_varnames);
444 Py_CLEAR(u->u_freevars);
445 Py_CLEAR(u->u_cellvars);
446 Py_CLEAR(u->u_private);
447 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448}
449
450static int
451compiler_enter_scope(struct compiler *c, identifier name, void *key,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
457 struct compiler_unit));
458 if (!u) {
459 PyErr_NoMemory();
460 return 0;
461 }
462 memset(u, 0, sizeof(struct compiler_unit));
463 u->u_argcount = 0;
464 u->u_kwonlyargcount = 0;
465 u->u_ste = PySymtable_Lookup(c->c_st, key);
466 if (!u->u_ste) {
467 compiler_unit_free(u);
468 return 0;
469 }
470 Py_INCREF(name);
471 u->u_name = name;
472 u->u_varnames = list2dict(u->u_ste->ste_varnames);
473 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
474 if (!u->u_varnames || !u->u_cellvars) {
475 compiler_unit_free(u);
476 return 0;
477 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
480 PyDict_Size(u->u_cellvars));
481 if (!u->u_freevars) {
482 compiler_unit_free(u);
483 return 0;
484 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 u->u_blocks = NULL;
487 u->u_nfblocks = 0;
488 u->u_firstlineno = lineno;
489 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000490 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 u->u_lineno_set = 0;
492 u->u_consts = PyDict_New();
493 if (!u->u_consts) {
494 compiler_unit_free(u);
495 return 0;
496 }
497 u->u_names = PyDict_New();
498 if (!u->u_names) {
499 compiler_unit_free(u);
500 return 0;
501 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 /* Push the old compiler_unit on the stack. */
506 if (c->u) {
507 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
508 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
509 Py_XDECREF(capsule);
510 compiler_unit_free(u);
511 return 0;
512 }
513 Py_DECREF(capsule);
514 u->u_private = c->u->u_private;
515 Py_XINCREF(u->u_private);
516 }
517 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 c->c_nestlevel++;
520 if (compiler_use_new_block(c) == NULL)
521 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524}
525
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000526static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527compiler_exit_scope(struct compiler *c)
528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 int n;
530 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 c->c_nestlevel--;
533 compiler_unit_free(c->u);
534 /* Restore c->u to the parent unit. */
535 n = PyList_GET_SIZE(c->c_stack) - 1;
536 if (n >= 0) {
537 capsule = PyList_GET_ITEM(c->c_stack, n);
538 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
539 assert(c->u);
540 /* we are deleting from a list so this really shouldn't fail */
541 if (PySequence_DelItem(c->c_stack, n) < 0)
542 Py_FatalError("compiler_exit_scope()");
543 compiler_unit_check(c->u);
544 }
545 else
546 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548}
549
550/* Allocate a new block and return a pointer to it.
551 Returns NULL on error.
552*/
553
554static basicblock *
555compiler_new_block(struct compiler *c)
556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 basicblock *b;
558 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 u = c->u;
561 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
562 if (b == NULL) {
563 PyErr_NoMemory();
564 return NULL;
565 }
566 memset((void *)b, 0, sizeof(basicblock));
567 /* Extend the singly linked list of blocks with new block. */
568 b->b_list = u->u_blocks;
569 u->u_blocks = b;
570 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000571}
572
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573static basicblock *
574compiler_use_new_block(struct compiler *c)
575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 basicblock *block = compiler_new_block(c);
577 if (block == NULL)
578 return NULL;
579 c->u->u_curblock = block;
580 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000581}
582
583static basicblock *
584compiler_next_block(struct compiler *c)
585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 basicblock *block = compiler_new_block(c);
587 if (block == NULL)
588 return NULL;
589 c->u->u_curblock->b_next = block;
590 c->u->u_curblock = block;
591 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000592}
593
594static basicblock *
595compiler_use_next_block(struct compiler *c, basicblock *block)
596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 assert(block != NULL);
598 c->u->u_curblock->b_next = block;
599 c->u->u_curblock = block;
600 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000601}
602
603/* Returns the offset of the next instruction in the current block's
604 b_instr array. Resizes the b_instr as necessary.
605 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000606*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
608static int
609compiler_next_instr(struct compiler *c, basicblock *b)
610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 assert(b != NULL);
612 if (b->b_instr == NULL) {
613 b->b_instr = (struct instr *)PyObject_Malloc(
614 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
615 if (b->b_instr == NULL) {
616 PyErr_NoMemory();
617 return -1;
618 }
619 b->b_ialloc = DEFAULT_BLOCK_SIZE;
620 memset((char *)b->b_instr, 0,
621 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
622 }
623 else if (b->b_iused == b->b_ialloc) {
624 struct instr *tmp;
625 size_t oldsize, newsize;
626 oldsize = b->b_ialloc * sizeof(struct instr);
627 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (oldsize > (PY_SIZE_MAX >> 1)) {
630 PyErr_NoMemory();
631 return -1;
632 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (newsize == 0) {
635 PyErr_NoMemory();
636 return -1;
637 }
638 b->b_ialloc <<= 1;
639 tmp = (struct instr *)PyObject_Realloc(
640 (void *)b->b_instr, newsize);
641 if (tmp == NULL) {
642 PyErr_NoMemory();
643 return -1;
644 }
645 b->b_instr = tmp;
646 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
647 }
648 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649}
650
Christian Heimes2202f872008-02-06 14:31:34 +0000651/* Set the i_lineno member of the instruction at offset off if the
652 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000653 already been set. If it has been set, the call has no effect.
654
Christian Heimes2202f872008-02-06 14:31:34 +0000655 The line number is reset in the following cases:
656 - when entering a new scope
657 - on each statement
658 - on each expression that start a new line
659 - before the "except" clause
660 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000661*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663static void
664compiler_set_lineno(struct compiler *c, int off)
665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 basicblock *b;
667 if (c->u->u_lineno_set)
668 return;
669 c->u->u_lineno_set = 1;
670 b = c->u->u_curblock;
671 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672}
673
674static int
675opcode_stack_effect(int opcode, int oparg)
676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 switch (opcode) {
678 case POP_TOP:
679 return -1;
680 case ROT_TWO:
681 case ROT_THREE:
682 return 0;
683 case DUP_TOP:
684 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000685 case DUP_TOP_TWO:
686 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 case UNARY_POSITIVE:
689 case UNARY_NEGATIVE:
690 case UNARY_NOT:
691 case UNARY_INVERT:
692 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 case SET_ADD:
695 case LIST_APPEND:
696 return -1;
697 case MAP_ADD:
698 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 case BINARY_POWER:
701 case BINARY_MULTIPLY:
702 case BINARY_MODULO:
703 case BINARY_ADD:
704 case BINARY_SUBTRACT:
705 case BINARY_SUBSCR:
706 case BINARY_FLOOR_DIVIDE:
707 case BINARY_TRUE_DIVIDE:
708 return -1;
709 case INPLACE_FLOOR_DIVIDE:
710 case INPLACE_TRUE_DIVIDE:
711 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 case INPLACE_ADD:
714 case INPLACE_SUBTRACT:
715 case INPLACE_MULTIPLY:
716 case INPLACE_MODULO:
717 return -1;
718 case STORE_SUBSCR:
719 return -3;
720 case STORE_MAP:
721 return -2;
722 case DELETE_SUBSCR:
723 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 case BINARY_LSHIFT:
726 case BINARY_RSHIFT:
727 case BINARY_AND:
728 case BINARY_XOR:
729 case BINARY_OR:
730 return -1;
731 case INPLACE_POWER:
732 return -1;
733 case GET_ITER:
734 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 case PRINT_EXPR:
737 return -1;
738 case LOAD_BUILD_CLASS:
739 return 1;
740 case INPLACE_LSHIFT:
741 case INPLACE_RSHIFT:
742 case INPLACE_AND:
743 case INPLACE_XOR:
744 case INPLACE_OR:
745 return -1;
746 case BREAK_LOOP:
747 return 0;
748 case SETUP_WITH:
749 return 7;
750 case WITH_CLEANUP:
751 return -1; /* XXX Sometimes more */
752 case STORE_LOCALS:
753 return -1;
754 case RETURN_VALUE:
755 return -1;
756 case IMPORT_STAR:
757 return -1;
758 case YIELD_VALUE:
759 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 case POP_BLOCK:
762 return 0;
763 case POP_EXCEPT:
764 return 0; /* -3 except if bad bytecode */
765 case END_FINALLY:
766 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 case STORE_NAME:
769 return -1;
770 case DELETE_NAME:
771 return 0;
772 case UNPACK_SEQUENCE:
773 return oparg-1;
774 case UNPACK_EX:
775 return (oparg&0xFF) + (oparg>>8);
776 case FOR_ITER:
777 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 case STORE_ATTR:
780 return -2;
781 case DELETE_ATTR:
782 return -1;
783 case STORE_GLOBAL:
784 return -1;
785 case DELETE_GLOBAL:
786 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 case LOAD_CONST:
788 return 1;
789 case LOAD_NAME:
790 return 1;
791 case BUILD_TUPLE:
792 case BUILD_LIST:
793 case BUILD_SET:
794 return 1-oparg;
795 case BUILD_MAP:
796 return 1;
797 case LOAD_ATTR:
798 return 0;
799 case COMPARE_OP:
800 return -1;
801 case IMPORT_NAME:
802 return -1;
803 case IMPORT_FROM:
804 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 case JUMP_FORWARD:
807 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
808 case JUMP_IF_FALSE_OR_POP: /* "" */
809 case JUMP_ABSOLUTE:
810 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 case POP_JUMP_IF_FALSE:
813 case POP_JUMP_IF_TRUE:
814 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 case LOAD_GLOBAL:
817 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 case CONTINUE_LOOP:
820 return 0;
821 case SETUP_LOOP:
822 return 0;
823 case SETUP_EXCEPT:
824 case SETUP_FINALLY:
825 return 6; /* can push 3 values for the new exception
826 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 case LOAD_FAST:
829 return 1;
830 case STORE_FAST:
831 return -1;
832 case DELETE_FAST:
833 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 case RAISE_VARARGS:
836 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000837#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 case CALL_FUNCTION:
839 return -NARGS(oparg);
840 case CALL_FUNCTION_VAR:
841 case CALL_FUNCTION_KW:
842 return -NARGS(oparg)-1;
843 case CALL_FUNCTION_VAR_KW:
844 return -NARGS(oparg)-2;
845 case MAKE_FUNCTION:
846 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
847 case MAKE_CLOSURE:
848 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000849#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 case BUILD_SLICE:
851 if (oparg == 3)
852 return -2;
853 else
854 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 case LOAD_CLOSURE:
857 return 1;
858 case LOAD_DEREF:
859 return 1;
860 case STORE_DEREF:
861 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000862 case DELETE_DEREF:
863 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 default:
865 fprintf(stderr, "opcode = %d\n", opcode);
866 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 }
869 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870}
871
872/* Add an opcode with no argument.
873 Returns 0 on failure, 1 on success.
874*/
875
876static int
877compiler_addop(struct compiler *c, int opcode)
878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 basicblock *b;
880 struct instr *i;
881 int off;
882 off = compiler_next_instr(c, c->u->u_curblock);
883 if (off < 0)
884 return 0;
885 b = c->u->u_curblock;
886 i = &b->b_instr[off];
887 i->i_opcode = opcode;
888 i->i_hasarg = 0;
889 if (opcode == RETURN_VALUE)
890 b->b_return = 1;
891 compiler_set_lineno(c, off);
892 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000893}
894
895static int
896compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 PyObject *t, *v;
899 Py_ssize_t arg;
900 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* necessary to make sure types aren't coerced (e.g., int and long) */
903 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
904 if (PyFloat_Check(o)) {
905 d = PyFloat_AS_DOUBLE(o);
906 /* all we need is to make the tuple different in either the 0.0
907 * or -0.0 case from all others, just to avoid the "coercion".
908 */
909 if (d == 0.0 && copysign(1.0, d) < 0.0)
910 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
911 else
912 t = PyTuple_Pack(2, o, o->ob_type);
913 }
914 else if (PyComplex_Check(o)) {
915 Py_complex z;
916 int real_negzero, imag_negzero;
917 /* For the complex case we must make complex(x, 0.)
918 different from complex(x, -0.) and complex(0., y)
919 different from complex(-0., y), for any x and y.
920 All four complex zeros must be distinguished.*/
921 z = PyComplex_AsCComplex(o);
922 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
923 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
924 if (real_negzero && imag_negzero) {
925 t = PyTuple_Pack(5, o, o->ob_type,
926 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000927 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 else if (imag_negzero) {
929 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000930 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 else if (real_negzero) {
932 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
933 }
934 else {
935 t = PyTuple_Pack(2, o, o->ob_type);
936 }
937 }
938 else {
939 t = PyTuple_Pack(2, o, o->ob_type);
940 }
941 if (t == NULL)
942 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 v = PyDict_GetItem(dict, t);
945 if (!v) {
946 if (PyErr_Occurred())
947 return -1;
948 arg = PyDict_Size(dict);
949 v = PyLong_FromLong(arg);
950 if (!v) {
951 Py_DECREF(t);
952 return -1;
953 }
954 if (PyDict_SetItem(dict, t, v) < 0) {
955 Py_DECREF(t);
956 Py_DECREF(v);
957 return -1;
958 }
959 Py_DECREF(v);
960 }
961 else
962 arg = PyLong_AsLong(v);
963 Py_DECREF(t);
964 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000965}
966
967static int
968compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970{
971 int arg = compiler_add_o(c, dict, o);
972 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000973 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974 return compiler_addop_i(c, opcode, arg);
975}
976
977static int
978compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980{
981 int arg;
982 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
983 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000984 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985 arg = compiler_add_o(c, dict, mangled);
986 Py_DECREF(mangled);
987 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000988 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989 return compiler_addop_i(c, opcode, arg);
990}
991
992/* Add an opcode with an integer argument.
993 Returns 0 on failure, 1 on success.
994*/
995
996static int
997compiler_addop_i(struct compiler *c, int opcode, int oparg)
998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 struct instr *i;
1000 int off;
1001 off = compiler_next_instr(c, c->u->u_curblock);
1002 if (off < 0)
1003 return 0;
1004 i = &c->u->u_curblock->b_instr[off];
1005 i->i_opcode = opcode;
1006 i->i_oparg = oparg;
1007 i->i_hasarg = 1;
1008 compiler_set_lineno(c, off);
1009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010}
1011
1012static int
1013compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 struct instr *i;
1016 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 assert(b != NULL);
1019 off = compiler_next_instr(c, c->u->u_curblock);
1020 if (off < 0)
1021 return 0;
1022 i = &c->u->u_curblock->b_instr[off];
1023 i->i_opcode = opcode;
1024 i->i_target = b;
1025 i->i_hasarg = 1;
1026 if (absolute)
1027 i->i_jabs = 1;
1028 else
1029 i->i_jrel = 1;
1030 compiler_set_lineno(c, off);
1031 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032}
1033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1035 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 it as the current block. NEXT_BLOCK() also creates an implicit jump
1037 from the current block to the new block.
1038*/
1039
Thomas Wouters89f507f2006-12-13 04:49:30 +00001040/* The returns inside these macros make it impossible to decref objects
1041 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001042*/
1043
1044
1045#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (compiler_use_new_block((C)) == NULL) \
1047 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048}
1049
1050#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 if (compiler_next_block((C)) == NULL) \
1052 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001053}
1054
1055#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (!compiler_addop((C), (OP))) \
1057 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058}
1059
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001060#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (!compiler_addop((C), (OP))) { \
1062 compiler_exit_scope(c); \
1063 return 0; \
1064 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001065}
1066
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1069 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070}
1071
1072#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1074 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075}
1076
1077#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (!compiler_addop_i((C), (OP), (O))) \
1079 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080}
1081
1082#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (!compiler_addop_j((C), (OP), (O), 1)) \
1084 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085}
1086
1087#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (!compiler_addop_j((C), (OP), (O), 0)) \
1089 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001090}
1091
1092/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1093 the ASDL name to synthesize the name of the C type and the visit function.
1094*/
1095
1096#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (!compiler_visit_ ## TYPE((C), (V))) \
1098 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099}
1100
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001101#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (!compiler_visit_ ## TYPE((C), (V))) { \
1103 compiler_exit_scope(c); \
1104 return 0; \
1105 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001106}
1107
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (!compiler_visit_slice((C), (V), (CTX))) \
1110 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111}
1112
1113#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 int _i; \
1115 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1116 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1117 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1118 if (!compiler_visit_ ## TYPE((C), elt)) \
1119 return 0; \
1120 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121}
1122
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001123#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 int _i; \
1125 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1126 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1127 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1128 if (!compiler_visit_ ## TYPE((C), elt)) { \
1129 compiler_exit_scope(c); \
1130 return 0; \
1131 } \
1132 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001133}
1134
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135static int
1136compiler_isdocstring(stmt_ty s)
1137{
1138 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001139 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return s->v.Expr.value->kind == Str_kind;
1141}
1142
1143/* Compile a sequence of statements, checking for a docstring. */
1144
1145static int
1146compiler_body(struct compiler *c, asdl_seq *stmts)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 int i = 0;
1149 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (!asdl_seq_LEN(stmts))
1152 return 1;
1153 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001154 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 /* don't generate docstrings if -OO */
1156 i = 1;
1157 VISIT(c, expr, st->v.Expr.value);
1158 if (!compiler_nameop(c, __doc__, Store))
1159 return 0;
1160 }
1161 for (; i < asdl_seq_LEN(stmts); i++)
1162 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1163 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
1166static PyCodeObject *
1167compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 PyCodeObject *co;
1170 int addNone = 1;
1171 static PyObject *module;
1172 if (!module) {
1173 module = PyUnicode_InternFromString("<module>");
1174 if (!module)
1175 return NULL;
1176 }
1177 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1178 if (!compiler_enter_scope(c, module, mod, 0))
1179 return NULL;
1180 switch (mod->kind) {
1181 case Module_kind:
1182 if (!compiler_body(c, mod->v.Module.body)) {
1183 compiler_exit_scope(c);
1184 return 0;
1185 }
1186 break;
1187 case Interactive_kind:
1188 c->c_interactive = 1;
1189 VISIT_SEQ_IN_SCOPE(c, stmt,
1190 mod->v.Interactive.body);
1191 break;
1192 case Expression_kind:
1193 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1194 addNone = 0;
1195 break;
1196 case Suite_kind:
1197 PyErr_SetString(PyExc_SystemError,
1198 "suite should not be possible");
1199 return 0;
1200 default:
1201 PyErr_Format(PyExc_SystemError,
1202 "module kind %d should not be possible",
1203 mod->kind);
1204 return 0;
1205 }
1206 co = assemble(c, addNone);
1207 compiler_exit_scope(c);
1208 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001209}
1210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211/* The test for LOCAL must come before the test for FREE in order to
1212 handle classes where name is both local and free. The local var is
1213 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001214*/
1215
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216static int
1217get_ref_type(struct compiler *c, PyObject *name)
1218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 int scope = PyST_GetScope(c->u->u_ste, name);
1220 if (scope == 0) {
1221 char buf[350];
1222 PyOS_snprintf(buf, sizeof(buf),
1223 "unknown scope for %.100s in %.100s(%s) in %s\n"
1224 "symbols: %s\nlocals: %s\nglobals: %s",
1225 PyBytes_AS_STRING(name),
1226 PyBytes_AS_STRING(c->u->u_name),
1227 PyObject_REPR(c->u->u_ste->ste_id),
1228 c->c_filename,
1229 PyObject_REPR(c->u->u_ste->ste_symbols),
1230 PyObject_REPR(c->u->u_varnames),
1231 PyObject_REPR(c->u->u_names)
1232 );
1233 Py_FatalError(buf);
1234 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001237}
1238
1239static int
1240compiler_lookup_arg(PyObject *dict, PyObject *name)
1241{
1242 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001243 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001245 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001247 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001248 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001249 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001250 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251}
1252
1253static int
1254compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 int i, free = PyCode_GetNumFree(co);
1257 if (free == 0) {
1258 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1259 ADDOP_I(c, MAKE_FUNCTION, args);
1260 return 1;
1261 }
1262 for (i = 0; i < free; ++i) {
1263 /* Bypass com_addop_varname because it will generate
1264 LOAD_DEREF but LOAD_CLOSURE is needed.
1265 */
1266 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1267 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* Special case: If a class contains a method with a
1270 free variable that has the same name as a method,
1271 the name will be considered free *and* local in the
1272 class. It should be handled by the closure, as
1273 well as by the normal name loookup logic.
1274 */
1275 reftype = get_ref_type(c, name);
1276 if (reftype == CELL)
1277 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1278 else /* (reftype == FREE) */
1279 arg = compiler_lookup_arg(c->u->u_freevars, name);
1280 if (arg == -1) {
1281 fprintf(stderr,
1282 "lookup %s in %s %d %d\n"
1283 "freevars of %s: %s\n",
1284 PyObject_REPR(name),
1285 PyBytes_AS_STRING(c->u->u_name),
1286 reftype, arg,
1287 _PyUnicode_AsString(co->co_name),
1288 PyObject_REPR(co->co_freevars));
1289 Py_FatalError("compiler_make_closure()");
1290 }
1291 ADDOP_I(c, LOAD_CLOSURE, arg);
1292 }
1293 ADDOP_I(c, BUILD_TUPLE, free);
1294 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1295 ADDOP_I(c, MAKE_CLOSURE, args);
1296 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
1299static int
1300compiler_decorators(struct compiler *c, asdl_seq* decos)
1301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 if (!decos)
1305 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1308 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1309 }
1310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001314compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 int i, default_count = 0;
1318 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1319 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1320 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1321 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001322 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1323 if (!mangled)
1324 return -1;
1325 ADDOP_O(c, LOAD_CONST, mangled, consts);
1326 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (!compiler_visit_expr(c, default_)) {
1328 return -1;
1329 }
1330 default_count++;
1331 }
1332 }
1333 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001334}
1335
1336static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001337compiler_visit_argannotation(struct compiler *c, identifier id,
1338 expr_ty annotation, PyObject *names)
1339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (annotation) {
1341 VISIT(c, expr, annotation);
1342 if (PyList_Append(names, id))
1343 return -1;
1344 }
1345 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001346}
1347
1348static int
1349compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1350 PyObject *names)
1351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 int i, error;
1353 for (i = 0; i < asdl_seq_LEN(args); i++) {
1354 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1355 error = compiler_visit_argannotation(
1356 c,
1357 arg->arg,
1358 arg->annotation,
1359 names);
1360 if (error)
1361 return error;
1362 }
1363 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001364}
1365
1366static int
1367compiler_visit_annotations(struct compiler *c, arguments_ty args,
1368 expr_ty returns)
1369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* Push arg annotations and a list of the argument names. Return the #
1371 of items pushed. The expressions are evaluated out-of-order wrt the
1372 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1375 */
1376 static identifier return_str;
1377 PyObject *names;
1378 int len;
1379 names = PyList_New(0);
1380 if (!names)
1381 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (compiler_visit_argannotations(c, args->args, names))
1384 goto error;
1385 if (args->varargannotation &&
1386 compiler_visit_argannotation(c, args->vararg,
1387 args->varargannotation, names))
1388 goto error;
1389 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1390 goto error;
1391 if (args->kwargannotation &&
1392 compiler_visit_argannotation(c, args->kwarg,
1393 args->kwargannotation, names))
1394 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (!return_str) {
1397 return_str = PyUnicode_InternFromString("return");
1398 if (!return_str)
1399 goto error;
1400 }
1401 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1402 goto error;
1403 }
1404
1405 len = PyList_GET_SIZE(names);
1406 if (len > 65534) {
1407 /* len must fit in 16 bits, and len is incremented below */
1408 PyErr_SetString(PyExc_SyntaxError,
1409 "too many annotations");
1410 goto error;
1411 }
1412 if (len) {
1413 /* convert names to a tuple and place on stack */
1414 PyObject *elt;
1415 int i;
1416 PyObject *s = PyTuple_New(len);
1417 if (!s)
1418 goto error;
1419 for (i = 0; i < len; i++) {
1420 elt = PyList_GET_ITEM(names, i);
1421 Py_INCREF(elt);
1422 PyTuple_SET_ITEM(s, i, elt);
1423 }
1424 ADDOP_O(c, LOAD_CONST, s, consts);
1425 Py_DECREF(s);
1426 len++; /* include the just-pushed tuple */
1427 }
1428 Py_DECREF(names);
1429 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001430
1431error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 Py_DECREF(names);
1433 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001434}
1435
1436static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437compiler_function(struct compiler *c, stmt_ty s)
1438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyCodeObject *co;
1440 PyObject *first_const = Py_None;
1441 arguments_ty args = s->v.FunctionDef.args;
1442 expr_ty returns = s->v.FunctionDef.returns;
1443 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1444 stmt_ty st;
1445 int i, n, docstring, kw_default_count = 0, arglength;
1446 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (!compiler_decorators(c, decos))
1451 return 0;
1452 if (args->kwonlyargs) {
1453 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1454 args->kw_defaults);
1455 if (res < 0)
1456 return 0;
1457 kw_default_count = res;
1458 }
1459 if (args->defaults)
1460 VISIT_SEQ(c, expr, args->defaults);
1461 num_annotations = compiler_visit_annotations(c, args, returns);
1462 if (num_annotations < 0)
1463 return 0;
1464 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1467 s->lineno))
1468 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1471 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001472 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 first_const = st->v.Expr.value->v.Str.s;
1474 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1475 compiler_exit_scope(c);
1476 return 0;
1477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 c->u->u_argcount = asdl_seq_LEN(args->args);
1480 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1481 n = asdl_seq_LEN(s->v.FunctionDef.body);
1482 /* if there was a docstring, we need to skip the first statement */
1483 for (i = docstring; i < n; i++) {
1484 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1485 VISIT_IN_SCOPE(c, stmt, st);
1486 }
1487 co = assemble(c, 1);
1488 compiler_exit_scope(c);
1489 if (co == NULL)
1490 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 arglength = asdl_seq_LEN(args->defaults);
1493 arglength |= kw_default_count << 8;
1494 arglength |= num_annotations << 16;
1495 compiler_make_closure(c, co, arglength);
1496 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 /* decorators */
1499 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1500 ADDOP_I(c, CALL_FUNCTION, 1);
1501 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504}
1505
1506static int
1507compiler_class(struct compiler *c, stmt_ty s)
1508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 PyCodeObject *co;
1510 PyObject *str;
1511 int i;
1512 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (!compiler_decorators(c, decos))
1515 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 /* ultimately generate code for:
1518 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1519 where:
1520 <func> is a function/closure created from the class body;
1521 it has a single argument (__locals__) where the dict
1522 (or MutableSequence) representing the locals is passed
1523 <name> is the class name
1524 <bases> is the positional arguments and *varargs argument
1525 <keywords> is the keyword arguments and **kwds argument
1526 This borrows from compiler_call.
1527 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 /* 1. compile the class body into a code object */
1530 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1531 return 0;
1532 /* this block represents what we do in the new scope */
1533 {
1534 /* use the class name for name mangling */
1535 Py_INCREF(s->v.ClassDef.name);
1536 Py_XDECREF(c->u->u_private);
1537 c->u->u_private = s->v.ClassDef.name;
1538 /* force it to have one mandatory argument */
1539 c->u->u_argcount = 1;
1540 /* load the first argument (__locals__) ... */
1541 ADDOP_I(c, LOAD_FAST, 0);
1542 /* ... and store it into f_locals */
1543 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1544 /* load (global) __name__ ... */
1545 str = PyUnicode_InternFromString("__name__");
1546 if (!str || !compiler_nameop(c, str, Load)) {
1547 Py_XDECREF(str);
1548 compiler_exit_scope(c);
1549 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 Py_DECREF(str);
1552 /* ... and store it as __module__ */
1553 str = PyUnicode_InternFromString("__module__");
1554 if (!str || !compiler_nameop(c, str, Store)) {
1555 Py_XDECREF(str);
1556 compiler_exit_scope(c);
1557 return 0;
1558 }
1559 Py_DECREF(str);
1560 /* compile the body proper */
1561 if (!compiler_body(c, s->v.ClassDef.body)) {
1562 compiler_exit_scope(c);
1563 return 0;
1564 }
1565 /* return the (empty) __class__ cell */
1566 str = PyUnicode_InternFromString("__class__");
1567 if (str == NULL) {
1568 compiler_exit_scope(c);
1569 return 0;
1570 }
1571 i = compiler_lookup_arg(c->u->u_cellvars, str);
1572 Py_DECREF(str);
1573 if (i == -1) {
1574 /* This happens when nobody references the cell */
1575 PyErr_Clear();
1576 /* Return None */
1577 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1578 }
1579 else {
1580 /* Return the cell where to store __class__ */
1581 ADDOP_I(c, LOAD_CLOSURE, i);
1582 }
1583 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1584 /* create the code object */
1585 co = assemble(c, 1);
1586 }
1587 /* leave the new scope */
1588 compiler_exit_scope(c);
1589 if (co == NULL)
1590 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 /* 2. load the 'build_class' function */
1593 ADDOP(c, LOAD_BUILD_CLASS);
1594
1595 /* 3. load a function (or closure) made from the code object */
1596 compiler_make_closure(c, co, 0);
1597 Py_DECREF(co);
1598
1599 /* 4. load class name */
1600 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1601
1602 /* 5. generate the rest of the code for the call */
1603 if (!compiler_call_helper(c, 2,
1604 s->v.ClassDef.bases,
1605 s->v.ClassDef.keywords,
1606 s->v.ClassDef.starargs,
1607 s->v.ClassDef.kwargs))
1608 return 0;
1609
1610 /* 6. apply decorators */
1611 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1612 ADDOP_I(c, CALL_FUNCTION, 1);
1613 }
1614
1615 /* 7. store into <name> */
1616 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1617 return 0;
1618 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001619}
1620
1621static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001622compiler_ifexp(struct compiler *c, expr_ty e)
1623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 basicblock *end, *next;
1625
1626 assert(e->kind == IfExp_kind);
1627 end = compiler_new_block(c);
1628 if (end == NULL)
1629 return 0;
1630 next = compiler_new_block(c);
1631 if (next == NULL)
1632 return 0;
1633 VISIT(c, expr, e->v.IfExp.test);
1634 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1635 VISIT(c, expr, e->v.IfExp.body);
1636 ADDOP_JREL(c, JUMP_FORWARD, end);
1637 compiler_use_next_block(c, next);
1638 VISIT(c, expr, e->v.IfExp.orelse);
1639 compiler_use_next_block(c, end);
1640 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001641}
1642
1643static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001644compiler_lambda(struct compiler *c, expr_ty e)
1645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 PyCodeObject *co;
1647 static identifier name;
1648 int kw_default_count = 0, arglength;
1649 arguments_ty args = e->v.Lambda.args;
1650 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 if (!name) {
1653 name = PyUnicode_InternFromString("<lambda>");
1654 if (!name)
1655 return 0;
1656 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (args->kwonlyargs) {
1659 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1660 args->kw_defaults);
1661 if (res < 0) return 0;
1662 kw_default_count = res;
1663 }
1664 if (args->defaults)
1665 VISIT_SEQ(c, expr, args->defaults);
1666 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1667 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* Make None the first constant, so the lambda can't have a
1670 docstring. */
1671 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1672 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 c->u->u_argcount = asdl_seq_LEN(args->args);
1675 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1676 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1677 if (c->u->u_ste->ste_generator) {
1678 ADDOP_IN_SCOPE(c, POP_TOP);
1679 }
1680 else {
1681 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1682 }
1683 co = assemble(c, 1);
1684 compiler_exit_scope(c);
1685 if (co == NULL)
1686 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 arglength = asdl_seq_LEN(args->defaults);
1689 arglength |= kw_default_count << 8;
1690 compiler_make_closure(c, co, arglength);
1691 Py_DECREF(co);
1692
1693 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694}
1695
1696static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697compiler_if(struct compiler *c, stmt_ty s)
1698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 basicblock *end, *next;
1700 int constant;
1701 assert(s->kind == If_kind);
1702 end = compiler_new_block(c);
1703 if (end == NULL)
1704 return 0;
1705
Georg Brandl8334fd92010-12-04 10:26:46 +00001706 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* constant = 0: "if 0"
1708 * constant = 1: "if 1", "if 2", ...
1709 * constant = -1: rest */
1710 if (constant == 0) {
1711 if (s->v.If.orelse)
1712 VISIT_SEQ(c, stmt, s->v.If.orelse);
1713 } else if (constant == 1) {
1714 VISIT_SEQ(c, stmt, s->v.If.body);
1715 } else {
1716 if (s->v.If.orelse) {
1717 next = compiler_new_block(c);
1718 if (next == NULL)
1719 return 0;
1720 }
1721 else
1722 next = end;
1723 VISIT(c, expr, s->v.If.test);
1724 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1725 VISIT_SEQ(c, stmt, s->v.If.body);
1726 ADDOP_JREL(c, JUMP_FORWARD, end);
1727 if (s->v.If.orelse) {
1728 compiler_use_next_block(c, next);
1729 VISIT_SEQ(c, stmt, s->v.If.orelse);
1730 }
1731 }
1732 compiler_use_next_block(c, end);
1733 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001734}
1735
1736static int
1737compiler_for(struct compiler *c, stmt_ty s)
1738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 start = compiler_new_block(c);
1742 cleanup = compiler_new_block(c);
1743 end = compiler_new_block(c);
1744 if (start == NULL || end == NULL || cleanup == NULL)
1745 return 0;
1746 ADDOP_JREL(c, SETUP_LOOP, end);
1747 if (!compiler_push_fblock(c, LOOP, start))
1748 return 0;
1749 VISIT(c, expr, s->v.For.iter);
1750 ADDOP(c, GET_ITER);
1751 compiler_use_next_block(c, start);
1752 ADDOP_JREL(c, FOR_ITER, cleanup);
1753 VISIT(c, expr, s->v.For.target);
1754 VISIT_SEQ(c, stmt, s->v.For.body);
1755 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1756 compiler_use_next_block(c, cleanup);
1757 ADDOP(c, POP_BLOCK);
1758 compiler_pop_fblock(c, LOOP, start);
1759 VISIT_SEQ(c, stmt, s->v.For.orelse);
1760 compiler_use_next_block(c, end);
1761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001762}
1763
1764static int
1765compiler_while(struct compiler *c, stmt_ty s)
1766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001768 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (constant == 0) {
1771 if (s->v.While.orelse)
1772 VISIT_SEQ(c, stmt, s->v.While.orelse);
1773 return 1;
1774 }
1775 loop = compiler_new_block(c);
1776 end = compiler_new_block(c);
1777 if (constant == -1) {
1778 anchor = compiler_new_block(c);
1779 if (anchor == NULL)
1780 return 0;
1781 }
1782 if (loop == NULL || end == NULL)
1783 return 0;
1784 if (s->v.While.orelse) {
1785 orelse = compiler_new_block(c);
1786 if (orelse == NULL)
1787 return 0;
1788 }
1789 else
1790 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 ADDOP_JREL(c, SETUP_LOOP, end);
1793 compiler_use_next_block(c, loop);
1794 if (!compiler_push_fblock(c, LOOP, loop))
1795 return 0;
1796 if (constant == -1) {
1797 VISIT(c, expr, s->v.While.test);
1798 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1799 }
1800 VISIT_SEQ(c, stmt, s->v.While.body);
1801 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 /* XXX should the two POP instructions be in a separate block
1804 if there is no else clause ?
1805 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (constant == -1) {
1808 compiler_use_next_block(c, anchor);
1809 ADDOP(c, POP_BLOCK);
1810 }
1811 compiler_pop_fblock(c, LOOP, loop);
1812 if (orelse != NULL) /* what if orelse is just pass? */
1813 VISIT_SEQ(c, stmt, s->v.While.orelse);
1814 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817}
1818
1819static int
1820compiler_continue(struct compiler *c)
1821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1823 static const char IN_FINALLY_ERROR_MSG[] =
1824 "'continue' not supported inside 'finally' clause";
1825 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (!c->u->u_nfblocks)
1828 return compiler_error(c, LOOP_ERROR_MSG);
1829 i = c->u->u_nfblocks - 1;
1830 switch (c->u->u_fblock[i].fb_type) {
1831 case LOOP:
1832 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1833 break;
1834 case EXCEPT:
1835 case FINALLY_TRY:
1836 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1837 /* Prevent continue anywhere under a finally
1838 even if hidden in a sub-try or except. */
1839 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1840 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1841 }
1842 if (i == -1)
1843 return compiler_error(c, LOOP_ERROR_MSG);
1844 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1845 break;
1846 case FINALLY_END:
1847 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1848 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851}
1852
1853/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854
1855 SETUP_FINALLY L
1856 <code for body>
1857 POP_BLOCK
1858 LOAD_CONST <None>
1859 L: <code for finalbody>
1860 END_FINALLY
1861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 The special instructions use the block stack. Each block
1863 stack entry contains the instruction that created it (here
1864 SETUP_FINALLY), the level of the value stack at the time the
1865 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 Pushes the current value stack level and the label
1869 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 Pops en entry from the block stack, and pops the value
1872 stack until its level is the same as indicated on the
1873 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 Pops a variable number of entries from the *value* stack
1876 and re-raises the exception they specify. The number of
1877 entries popped depends on the (pseudo) exception type.
1878
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 The block stack is unwound when an exception is raised:
1880 when a SETUP_FINALLY entry is found, the exception is pushed
1881 onto the value stack (and the exception condition is cleared),
1882 and the interpreter jumps to the label gotten from the block
1883 stack.
1884*/
1885
1886static int
1887compiler_try_finally(struct compiler *c, stmt_ty s)
1888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 basicblock *body, *end;
1890 body = compiler_new_block(c);
1891 end = compiler_new_block(c);
1892 if (body == NULL || end == NULL)
1893 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 ADDOP_JREL(c, SETUP_FINALLY, end);
1896 compiler_use_next_block(c, body);
1897 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1898 return 0;
1899 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1900 ADDOP(c, POP_BLOCK);
1901 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1904 compiler_use_next_block(c, end);
1905 if (!compiler_push_fblock(c, FINALLY_END, end))
1906 return 0;
1907 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1908 ADDOP(c, END_FINALLY);
1909 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912}
1913
1914/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001915 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 (The contents of the value stack is shown in [], with the top
1917 at the right; 'tb' is trace-back info, 'val' the exception's
1918 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919
1920 Value stack Label Instruction Argument
1921 [] SETUP_EXCEPT L1
1922 [] <code for S>
1923 [] POP_BLOCK
1924 [] JUMP_FORWARD L0
1925
1926 [tb, val, exc] L1: DUP )
1927 [tb, val, exc, exc] <evaluate E1> )
1928 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1929 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1930 [tb, val, exc] POP
1931 [tb, val] <assign to V1> (or POP if no V1)
1932 [tb] POP
1933 [] <code for S1>
1934 JUMP_FORWARD L0
1935
1936 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937 .............................etc.......................
1938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1940
1941 [] L0: <next statement>
1942
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943 Of course, parts are not generated if Vi or Ei is not present.
1944*/
1945static int
1946compiler_try_except(struct compiler *c, stmt_ty s)
1947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 basicblock *body, *orelse, *except, *end;
1949 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 body = compiler_new_block(c);
1952 except = compiler_new_block(c);
1953 orelse = compiler_new_block(c);
1954 end = compiler_new_block(c);
1955 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1956 return 0;
1957 ADDOP_JREL(c, SETUP_EXCEPT, except);
1958 compiler_use_next_block(c, body);
1959 if (!compiler_push_fblock(c, EXCEPT, body))
1960 return 0;
1961 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1962 ADDOP(c, POP_BLOCK);
1963 compiler_pop_fblock(c, EXCEPT, body);
1964 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1965 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1966 compiler_use_next_block(c, except);
1967 for (i = 0; i < n; i++) {
1968 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson74897ba2011-05-27 14:10:24 -05001969 s->v.TryExcept.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (!handler->v.ExceptHandler.type && i < n-1)
1971 return compiler_error(c, "default 'except:' must be last");
1972 c->u->u_lineno_set = 0;
1973 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00001974 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 except = compiler_new_block(c);
1976 if (except == NULL)
1977 return 0;
1978 if (handler->v.ExceptHandler.type) {
1979 ADDOP(c, DUP_TOP);
1980 VISIT(c, expr, handler->v.ExceptHandler.type);
1981 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1982 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
1983 }
1984 ADDOP(c, POP_TOP);
1985 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05001986 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001987
Benjamin Peterson74897ba2011-05-27 14:10:24 -05001988 cleanup_end = compiler_new_block(c);
1989 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05001990 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05001991 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00001992
Benjamin Peterson74897ba2011-05-27 14:10:24 -05001993 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
1994 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995
Benjamin Peterson74897ba2011-05-27 14:10:24 -05001996 /*
1997 try:
1998 # body
1999 except type as name:
2000 try:
2001 # body
2002 finally:
2003 name = None
2004 del name
2005 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002007 /* second try: */
2008 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2009 compiler_use_next_block(c, cleanup_body);
2010 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2011 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002013 /* second # body */
2014 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2015 ADDOP(c, POP_BLOCK);
2016 ADDOP(c, POP_EXCEPT);
2017 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002019 /* finally: */
2020 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2021 compiler_use_next_block(c, cleanup_end);
2022 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2023 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002025 /* name = None */
2026 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2027 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002029 /* del name */
2030 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002032 ADDOP(c, END_FINALLY);
2033 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 }
2035 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002036 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002038 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002039 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002040 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041
Guido van Rossumb940e112007-01-10 16:19:56 +00002042 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002043 ADDOP(c, POP_TOP);
2044 compiler_use_next_block(c, cleanup_body);
2045 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2046 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002048 ADDOP(c, POP_EXCEPT);
2049 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
2051 ADDOP_JREL(c, JUMP_FORWARD, end);
2052 compiler_use_next_block(c, except);
2053 }
2054 ADDOP(c, END_FINALLY);
2055 compiler_use_next_block(c, orelse);
2056 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2057 compiler_use_next_block(c, end);
2058 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059}
2060
2061static int
2062compiler_import_as(struct compiler *c, identifier name, identifier asname)
2063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* The IMPORT_NAME opcode was already generated. This function
2065 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 If there is a dot in name, we need to split it and emit a
2068 LOAD_ATTR for each name.
2069 */
2070 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2071 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
2072 if (dot) {
2073 /* Consume the base module name to get the first attribute */
2074 src = dot + 1;
2075 while (dot) {
2076 /* NB src is only defined when dot != NULL */
2077 PyObject *attr;
2078 dot = Py_UNICODE_strchr(src, '.');
2079 attr = PyUnicode_FromUnicode(src,
2080 dot ? dot - src : Py_UNICODE_strlen(src));
2081 if (!attr)
2082 return -1;
2083 ADDOP_O(c, LOAD_ATTR, attr, names);
2084 Py_DECREF(attr);
2085 src = dot + 1;
2086 }
2087 }
2088 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089}
2090
2091static int
2092compiler_import(struct compiler *c, stmt_ty s)
2093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* The Import node stores a module name like a.b.c as a single
2095 string. This is convenient for all cases except
2096 import a.b.c as d
2097 where we need to parse that string to extract the individual
2098 module names.
2099 XXX Perhaps change the representation to make this case simpler?
2100 */
2101 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 for (i = 0; i < n; i++) {
2104 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2105 int r;
2106 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 level = PyLong_FromLong(0);
2109 if (level == NULL)
2110 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 ADDOP_O(c, LOAD_CONST, level, consts);
2113 Py_DECREF(level);
2114 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2115 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (alias->asname) {
2118 r = compiler_import_as(c, alias->name, alias->asname);
2119 if (!r)
2120 return r;
2121 }
2122 else {
2123 identifier tmp = alias->name;
2124 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2125 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
2126 if (dot)
2127 tmp = PyUnicode_FromUnicode(base,
2128 dot - base);
2129 r = compiler_nameop(c, tmp, Store);
2130 if (dot) {
2131 Py_DECREF(tmp);
2132 }
2133 if (!r)
2134 return r;
2135 }
2136 }
2137 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138}
2139
2140static int
2141compiler_from_import(struct compiler *c, stmt_ty s)
2142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyObject *names = PyTuple_New(n);
2146 PyObject *level;
2147 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (!empty_string) {
2150 empty_string = PyUnicode_FromString("");
2151 if (!empty_string)
2152 return 0;
2153 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (!names)
2156 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 level = PyLong_FromLong(s->v.ImportFrom.level);
2159 if (!level) {
2160 Py_DECREF(names);
2161 return 0;
2162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* build up the names */
2165 for (i = 0; i < n; i++) {
2166 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2167 Py_INCREF(alias->name);
2168 PyTuple_SET_ITEM(names, i, alias->name);
2169 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2172 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2173 Py_DECREF(level);
2174 Py_DECREF(names);
2175 return compiler_error(c, "from __future__ imports must occur "
2176 "at the beginning of the file");
2177 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 ADDOP_O(c, LOAD_CONST, level, consts);
2180 Py_DECREF(level);
2181 ADDOP_O(c, LOAD_CONST, names, consts);
2182 Py_DECREF(names);
2183 if (s->v.ImportFrom.module) {
2184 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2185 }
2186 else {
2187 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2188 }
2189 for (i = 0; i < n; i++) {
2190 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2191 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
2194 assert(n == 1);
2195 ADDOP(c, IMPORT_STAR);
2196 return 1;
2197 }
2198
2199 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2200 store_name = alias->name;
2201 if (alias->asname)
2202 store_name = alias->asname;
2203
2204 if (!compiler_nameop(c, store_name, Store)) {
2205 Py_DECREF(names);
2206 return 0;
2207 }
2208 }
2209 /* remove imported module */
2210 ADDOP(c, POP_TOP);
2211 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212}
2213
2214static int
2215compiler_assert(struct compiler *c, stmt_ty s)
2216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 static PyObject *assertion_error = NULL;
2218 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002219
Georg Brandl8334fd92010-12-04 10:26:46 +00002220 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 return 1;
2222 if (assertion_error == NULL) {
2223 assertion_error = PyUnicode_InternFromString("AssertionError");
2224 if (assertion_error == NULL)
2225 return 0;
2226 }
2227 if (s->v.Assert.test->kind == Tuple_kind &&
2228 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2229 const char* msg =
2230 "assertion is always true, perhaps remove parentheses?";
2231 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2232 c->u->u_lineno, NULL, NULL) == -1)
2233 return 0;
2234 }
2235 VISIT(c, expr, s->v.Assert.test);
2236 end = compiler_new_block(c);
2237 if (end == NULL)
2238 return 0;
2239 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2240 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2241 if (s->v.Assert.msg) {
2242 VISIT(c, expr, s->v.Assert.msg);
2243 ADDOP_I(c, CALL_FUNCTION, 1);
2244 }
2245 ADDOP_I(c, RAISE_VARARGS, 1);
2246 compiler_use_next_block(c, end);
2247 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248}
2249
2250static int
2251compiler_visit_stmt(struct compiler *c, stmt_ty s)
2252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* Always assign a lineno to the next instruction for a stmt. */
2256 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002257 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 switch (s->kind) {
2261 case FunctionDef_kind:
2262 return compiler_function(c, s);
2263 case ClassDef_kind:
2264 return compiler_class(c, s);
2265 case Return_kind:
2266 if (c->u->u_ste->ste_type != FunctionBlock)
2267 return compiler_error(c, "'return' outside function");
2268 if (s->v.Return.value) {
2269 VISIT(c, expr, s->v.Return.value);
2270 }
2271 else
2272 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2273 ADDOP(c, RETURN_VALUE);
2274 break;
2275 case Delete_kind:
2276 VISIT_SEQ(c, expr, s->v.Delete.targets)
2277 break;
2278 case Assign_kind:
2279 n = asdl_seq_LEN(s->v.Assign.targets);
2280 VISIT(c, expr, s->v.Assign.value);
2281 for (i = 0; i < n; i++) {
2282 if (i < n - 1)
2283 ADDOP(c, DUP_TOP);
2284 VISIT(c, expr,
2285 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2286 }
2287 break;
2288 case AugAssign_kind:
2289 return compiler_augassign(c, s);
2290 case For_kind:
2291 return compiler_for(c, s);
2292 case While_kind:
2293 return compiler_while(c, s);
2294 case If_kind:
2295 return compiler_if(c, s);
2296 case Raise_kind:
2297 n = 0;
2298 if (s->v.Raise.exc) {
2299 VISIT(c, expr, s->v.Raise.exc);
2300 n++;
2301 if (s->v.Raise.cause) {
2302 VISIT(c, expr, s->v.Raise.cause);
2303 n++;
2304 }
2305 }
2306 ADDOP_I(c, RAISE_VARARGS, n);
2307 break;
2308 case TryExcept_kind:
2309 return compiler_try_except(c, s);
2310 case TryFinally_kind:
2311 return compiler_try_finally(c, s);
2312 case Assert_kind:
2313 return compiler_assert(c, s);
2314 case Import_kind:
2315 return compiler_import(c, s);
2316 case ImportFrom_kind:
2317 return compiler_from_import(c, s);
2318 case Global_kind:
2319 case Nonlocal_kind:
2320 break;
2321 case Expr_kind:
2322 if (c->c_interactive && c->c_nestlevel <= 1) {
2323 VISIT(c, expr, s->v.Expr.value);
2324 ADDOP(c, PRINT_EXPR);
2325 }
2326 else if (s->v.Expr.value->kind != Str_kind &&
2327 s->v.Expr.value->kind != Num_kind) {
2328 VISIT(c, expr, s->v.Expr.value);
2329 ADDOP(c, POP_TOP);
2330 }
2331 break;
2332 case Pass_kind:
2333 break;
2334 case Break_kind:
2335 if (!compiler_in_loop(c))
2336 return compiler_error(c, "'break' outside loop");
2337 ADDOP(c, BREAK_LOOP);
2338 break;
2339 case Continue_kind:
2340 return compiler_continue(c);
2341 case With_kind:
2342 return compiler_with(c, s);
2343 }
2344 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345}
2346
2347static int
2348unaryop(unaryop_ty op)
2349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 switch (op) {
2351 case Invert:
2352 return UNARY_INVERT;
2353 case Not:
2354 return UNARY_NOT;
2355 case UAdd:
2356 return UNARY_POSITIVE;
2357 case USub:
2358 return UNARY_NEGATIVE;
2359 default:
2360 PyErr_Format(PyExc_SystemError,
2361 "unary op %d should not be possible", op);
2362 return 0;
2363 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364}
2365
2366static int
2367binop(struct compiler *c, operator_ty op)
2368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 switch (op) {
2370 case Add:
2371 return BINARY_ADD;
2372 case Sub:
2373 return BINARY_SUBTRACT;
2374 case Mult:
2375 return BINARY_MULTIPLY;
2376 case Div:
2377 return BINARY_TRUE_DIVIDE;
2378 case Mod:
2379 return BINARY_MODULO;
2380 case Pow:
2381 return BINARY_POWER;
2382 case LShift:
2383 return BINARY_LSHIFT;
2384 case RShift:
2385 return BINARY_RSHIFT;
2386 case BitOr:
2387 return BINARY_OR;
2388 case BitXor:
2389 return BINARY_XOR;
2390 case BitAnd:
2391 return BINARY_AND;
2392 case FloorDiv:
2393 return BINARY_FLOOR_DIVIDE;
2394 default:
2395 PyErr_Format(PyExc_SystemError,
2396 "binary op %d should not be possible", op);
2397 return 0;
2398 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399}
2400
2401static int
2402cmpop(cmpop_ty op)
2403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 switch (op) {
2405 case Eq:
2406 return PyCmp_EQ;
2407 case NotEq:
2408 return PyCmp_NE;
2409 case Lt:
2410 return PyCmp_LT;
2411 case LtE:
2412 return PyCmp_LE;
2413 case Gt:
2414 return PyCmp_GT;
2415 case GtE:
2416 return PyCmp_GE;
2417 case Is:
2418 return PyCmp_IS;
2419 case IsNot:
2420 return PyCmp_IS_NOT;
2421 case In:
2422 return PyCmp_IN;
2423 case NotIn:
2424 return PyCmp_NOT_IN;
2425 default:
2426 return PyCmp_BAD;
2427 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428}
2429
2430static int
2431inplace_binop(struct compiler *c, operator_ty op)
2432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 switch (op) {
2434 case Add:
2435 return INPLACE_ADD;
2436 case Sub:
2437 return INPLACE_SUBTRACT;
2438 case Mult:
2439 return INPLACE_MULTIPLY;
2440 case Div:
2441 return INPLACE_TRUE_DIVIDE;
2442 case Mod:
2443 return INPLACE_MODULO;
2444 case Pow:
2445 return INPLACE_POWER;
2446 case LShift:
2447 return INPLACE_LSHIFT;
2448 case RShift:
2449 return INPLACE_RSHIFT;
2450 case BitOr:
2451 return INPLACE_OR;
2452 case BitXor:
2453 return INPLACE_XOR;
2454 case BitAnd:
2455 return INPLACE_AND;
2456 case FloorDiv:
2457 return INPLACE_FLOOR_DIVIDE;
2458 default:
2459 PyErr_Format(PyExc_SystemError,
2460 "inplace binary op %d should not be possible", op);
2461 return 0;
2462 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463}
2464
2465static int
2466compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 int op, scope, arg;
2469 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 PyObject *dict = c->u->u_names;
2472 PyObject *mangled;
2473 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 mangled = _Py_Mangle(c->u->u_private, name);
2476 if (!mangled)
2477 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 op = 0;
2480 optype = OP_NAME;
2481 scope = PyST_GetScope(c->u->u_ste, mangled);
2482 switch (scope) {
2483 case FREE:
2484 dict = c->u->u_freevars;
2485 optype = OP_DEREF;
2486 break;
2487 case CELL:
2488 dict = c->u->u_cellvars;
2489 optype = OP_DEREF;
2490 break;
2491 case LOCAL:
2492 if (c->u->u_ste->ste_type == FunctionBlock)
2493 optype = OP_FAST;
2494 break;
2495 case GLOBAL_IMPLICIT:
2496 if (c->u->u_ste->ste_type == FunctionBlock &&
2497 !c->u->u_ste->ste_unoptimized)
2498 optype = OP_GLOBAL;
2499 break;
2500 case GLOBAL_EXPLICIT:
2501 optype = OP_GLOBAL;
2502 break;
2503 default:
2504 /* scope can be 0 */
2505 break;
2506 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* XXX Leave assert here, but handle __doc__ and the like better */
2509 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 switch (optype) {
2512 case OP_DEREF:
2513 switch (ctx) {
2514 case Load: op = LOAD_DEREF; break;
2515 case Store: op = STORE_DEREF; break;
2516 case AugLoad:
2517 case AugStore:
2518 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002519 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 case Param:
2521 default:
2522 PyErr_SetString(PyExc_SystemError,
2523 "param invalid for deref variable");
2524 return 0;
2525 }
2526 break;
2527 case OP_FAST:
2528 switch (ctx) {
2529 case Load: op = LOAD_FAST; break;
2530 case Store: op = STORE_FAST; break;
2531 case Del: op = DELETE_FAST; break;
2532 case AugLoad:
2533 case AugStore:
2534 break;
2535 case Param:
2536 default:
2537 PyErr_SetString(PyExc_SystemError,
2538 "param invalid for local variable");
2539 return 0;
2540 }
2541 ADDOP_O(c, op, mangled, varnames);
2542 Py_DECREF(mangled);
2543 return 1;
2544 case OP_GLOBAL:
2545 switch (ctx) {
2546 case Load: op = LOAD_GLOBAL; break;
2547 case Store: op = STORE_GLOBAL; break;
2548 case Del: op = DELETE_GLOBAL; break;
2549 case AugLoad:
2550 case AugStore:
2551 break;
2552 case Param:
2553 default:
2554 PyErr_SetString(PyExc_SystemError,
2555 "param invalid for global variable");
2556 return 0;
2557 }
2558 break;
2559 case OP_NAME:
2560 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002561 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 case Store: op = STORE_NAME; break;
2563 case Del: op = DELETE_NAME; break;
2564 case AugLoad:
2565 case AugStore:
2566 break;
2567 case Param:
2568 default:
2569 PyErr_SetString(PyExc_SystemError,
2570 "param invalid for name variable");
2571 return 0;
2572 }
2573 break;
2574 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 assert(op);
2577 arg = compiler_add_o(c, dict, mangled);
2578 Py_DECREF(mangled);
2579 if (arg < 0)
2580 return 0;
2581 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582}
2583
2584static int
2585compiler_boolop(struct compiler *c, expr_ty e)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 basicblock *end;
2588 int jumpi, i, n;
2589 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 assert(e->kind == BoolOp_kind);
2592 if (e->v.BoolOp.op == And)
2593 jumpi = JUMP_IF_FALSE_OR_POP;
2594 else
2595 jumpi = JUMP_IF_TRUE_OR_POP;
2596 end = compiler_new_block(c);
2597 if (end == NULL)
2598 return 0;
2599 s = e->v.BoolOp.values;
2600 n = asdl_seq_LEN(s) - 1;
2601 assert(n >= 0);
2602 for (i = 0; i < n; ++i) {
2603 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2604 ADDOP_JABS(c, jumpi, end);
2605 }
2606 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2607 compiler_use_next_block(c, end);
2608 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609}
2610
2611static int
2612compiler_list(struct compiler *c, expr_ty e)
2613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 int n = asdl_seq_LEN(e->v.List.elts);
2615 if (e->v.List.ctx == Store) {
2616 int i, seen_star = 0;
2617 for (i = 0; i < n; i++) {
2618 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2619 if (elt->kind == Starred_kind && !seen_star) {
2620 if ((i >= (1 << 8)) ||
2621 (n-i-1 >= (INT_MAX >> 8)))
2622 return compiler_error(c,
2623 "too many expressions in "
2624 "star-unpacking assignment");
2625 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2626 seen_star = 1;
2627 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2628 } else if (elt->kind == Starred_kind) {
2629 return compiler_error(c,
2630 "two starred expressions in assignment");
2631 }
2632 }
2633 if (!seen_star) {
2634 ADDOP_I(c, UNPACK_SEQUENCE, n);
2635 }
2636 }
2637 VISIT_SEQ(c, expr, e->v.List.elts);
2638 if (e->v.List.ctx == Load) {
2639 ADDOP_I(c, BUILD_LIST, n);
2640 }
2641 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642}
2643
2644static int
2645compiler_tuple(struct compiler *c, expr_ty e)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 int n = asdl_seq_LEN(e->v.Tuple.elts);
2648 if (e->v.Tuple.ctx == Store) {
2649 int i, seen_star = 0;
2650 for (i = 0; i < n; i++) {
2651 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2652 if (elt->kind == Starred_kind && !seen_star) {
2653 if ((i >= (1 << 8)) ||
2654 (n-i-1 >= (INT_MAX >> 8)))
2655 return compiler_error(c,
2656 "too many expressions in "
2657 "star-unpacking assignment");
2658 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2659 seen_star = 1;
2660 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2661 } else if (elt->kind == Starred_kind) {
2662 return compiler_error(c,
2663 "two starred expressions in assignment");
2664 }
2665 }
2666 if (!seen_star) {
2667 ADDOP_I(c, UNPACK_SEQUENCE, n);
2668 }
2669 }
2670 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2671 if (e->v.Tuple.ctx == Load) {
2672 ADDOP_I(c, BUILD_TUPLE, n);
2673 }
2674 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675}
2676
2677static int
2678compiler_compare(struct compiler *c, expr_ty e)
2679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 int i, n;
2681 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2684 VISIT(c, expr, e->v.Compare.left);
2685 n = asdl_seq_LEN(e->v.Compare.ops);
2686 assert(n > 0);
2687 if (n > 1) {
2688 cleanup = compiler_new_block(c);
2689 if (cleanup == NULL)
2690 return 0;
2691 VISIT(c, expr,
2692 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2693 }
2694 for (i = 1; i < n; i++) {
2695 ADDOP(c, DUP_TOP);
2696 ADDOP(c, ROT_THREE);
2697 ADDOP_I(c, COMPARE_OP,
2698 cmpop((cmpop_ty)(asdl_seq_GET(
2699 e->v.Compare.ops, i - 1))));
2700 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2701 NEXT_BLOCK(c);
2702 if (i < (n - 1))
2703 VISIT(c, expr,
2704 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2705 }
2706 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2707 ADDOP_I(c, COMPARE_OP,
2708 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2709 if (n > 1) {
2710 basicblock *end = compiler_new_block(c);
2711 if (end == NULL)
2712 return 0;
2713 ADDOP_JREL(c, JUMP_FORWARD, end);
2714 compiler_use_next_block(c, cleanup);
2715 ADDOP(c, ROT_TWO);
2716 ADDOP(c, POP_TOP);
2717 compiler_use_next_block(c, end);
2718 }
2719 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720}
2721
2722static int
2723compiler_call(struct compiler *c, expr_ty e)
2724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 VISIT(c, expr, e->v.Call.func);
2726 return compiler_call_helper(c, 0,
2727 e->v.Call.args,
2728 e->v.Call.keywords,
2729 e->v.Call.starargs,
2730 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002731}
2732
2733/* shared code between compiler_call and compiler_class */
2734static int
2735compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 int n, /* Args already pushed */
2737 asdl_seq *args,
2738 asdl_seq *keywords,
2739 expr_ty starargs,
2740 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 n += asdl_seq_LEN(args);
2745 VISIT_SEQ(c, expr, args);
2746 if (keywords) {
2747 VISIT_SEQ(c, keyword, keywords);
2748 n |= asdl_seq_LEN(keywords) << 8;
2749 }
2750 if (starargs) {
2751 VISIT(c, expr, starargs);
2752 code |= 1;
2753 }
2754 if (kwargs) {
2755 VISIT(c, expr, kwargs);
2756 code |= 2;
2757 }
2758 switch (code) {
2759 case 0:
2760 ADDOP_I(c, CALL_FUNCTION, n);
2761 break;
2762 case 1:
2763 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2764 break;
2765 case 2:
2766 ADDOP_I(c, CALL_FUNCTION_KW, n);
2767 break;
2768 case 3:
2769 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2770 break;
2771 }
2772 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773}
2774
Nick Coghlan650f0d02007-04-15 12:05:43 +00002775
2776/* List and set comprehensions and generator expressions work by creating a
2777 nested function to perform the actual iteration. This means that the
2778 iteration variables don't leak into the current scope.
2779 The defined function is called immediately following its definition, with the
2780 result of that call being the result of the expression.
2781 The LC/SC version returns the populated container, while the GE version is
2782 flagged in symtable.c as a generator, so it returns the generator object
2783 when the function is called.
2784 This code *knows* that the loop cannot contain break, continue, or return,
2785 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2786
2787 Possible cleanups:
2788 - iterate over the generator sequence instead of using recursion
2789*/
2790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792compiler_comprehension_generator(struct compiler *c,
2793 asdl_seq *generators, int gen_index,
2794 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 /* generate code for the iterator, then each of the ifs,
2797 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 comprehension_ty gen;
2800 basicblock *start, *anchor, *skip, *if_cleanup;
2801 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 start = compiler_new_block(c);
2804 skip = compiler_new_block(c);
2805 if_cleanup = compiler_new_block(c);
2806 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2809 anchor == NULL)
2810 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 if (gen_index == 0) {
2815 /* Receive outermost iter as an implicit argument */
2816 c->u->u_argcount = 1;
2817 ADDOP_I(c, LOAD_FAST, 0);
2818 }
2819 else {
2820 /* Sub-iter - calculate on the fly */
2821 VISIT(c, expr, gen->iter);
2822 ADDOP(c, GET_ITER);
2823 }
2824 compiler_use_next_block(c, start);
2825 ADDOP_JREL(c, FOR_ITER, anchor);
2826 NEXT_BLOCK(c);
2827 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 /* XXX this needs to be cleaned up...a lot! */
2830 n = asdl_seq_LEN(gen->ifs);
2831 for (i = 0; i < n; i++) {
2832 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2833 VISIT(c, expr, e);
2834 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2835 NEXT_BLOCK(c);
2836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 if (++gen_index < asdl_seq_LEN(generators))
2839 if (!compiler_comprehension_generator(c,
2840 generators, gen_index,
2841 elt, val, type))
2842 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 /* only append after the last for generator */
2845 if (gen_index >= asdl_seq_LEN(generators)) {
2846 /* comprehension specific code */
2847 switch (type) {
2848 case COMP_GENEXP:
2849 VISIT(c, expr, elt);
2850 ADDOP(c, YIELD_VALUE);
2851 ADDOP(c, POP_TOP);
2852 break;
2853 case COMP_LISTCOMP:
2854 VISIT(c, expr, elt);
2855 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2856 break;
2857 case COMP_SETCOMP:
2858 VISIT(c, expr, elt);
2859 ADDOP_I(c, SET_ADD, gen_index + 1);
2860 break;
2861 case COMP_DICTCOMP:
2862 /* With 'd[k] = v', v is evaluated before k, so we do
2863 the same. */
2864 VISIT(c, expr, val);
2865 VISIT(c, expr, elt);
2866 ADDOP_I(c, MAP_ADD, gen_index + 1);
2867 break;
2868 default:
2869 return 0;
2870 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 compiler_use_next_block(c, skip);
2873 }
2874 compiler_use_next_block(c, if_cleanup);
2875 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2876 compiler_use_next_block(c, anchor);
2877
2878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879}
2880
2881static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002882compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 PyCodeObject *co = NULL;
2886 expr_ty outermost_iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 outermost_iter = ((comprehension_ty)
2889 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2892 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (type != COMP_GENEXP) {
2895 int op;
2896 switch (type) {
2897 case COMP_LISTCOMP:
2898 op = BUILD_LIST;
2899 break;
2900 case COMP_SETCOMP:
2901 op = BUILD_SET;
2902 break;
2903 case COMP_DICTCOMP:
2904 op = BUILD_MAP;
2905 break;
2906 default:
2907 PyErr_Format(PyExc_SystemError,
2908 "unknown comprehension type %d", type);
2909 goto error_in_scope;
2910 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 ADDOP_I(c, op, 0);
2913 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 if (!compiler_comprehension_generator(c, generators, 0, elt,
2916 val, type))
2917 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 if (type != COMP_GENEXP) {
2920 ADDOP(c, RETURN_VALUE);
2921 }
2922
2923 co = assemble(c, 1);
2924 compiler_exit_scope(c);
2925 if (co == NULL)
2926 goto error;
2927
2928 if (!compiler_make_closure(c, co, 0))
2929 goto error;
2930 Py_DECREF(co);
2931
2932 VISIT(c, expr, outermost_iter);
2933 ADDOP(c, GET_ITER);
2934 ADDOP_I(c, CALL_FUNCTION, 1);
2935 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002936error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002938error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 Py_XDECREF(co);
2940 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002941}
2942
2943static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944compiler_genexp(struct compiler *c, expr_ty e)
2945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 static identifier name;
2947 if (!name) {
2948 name = PyUnicode_FromString("<genexpr>");
2949 if (!name)
2950 return 0;
2951 }
2952 assert(e->kind == GeneratorExp_kind);
2953 return compiler_comprehension(c, e, COMP_GENEXP, name,
2954 e->v.GeneratorExp.generators,
2955 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956}
2957
2958static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002959compiler_listcomp(struct compiler *c, expr_ty e)
2960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 static identifier name;
2962 if (!name) {
2963 name = PyUnicode_FromString("<listcomp>");
2964 if (!name)
2965 return 0;
2966 }
2967 assert(e->kind == ListComp_kind);
2968 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2969 e->v.ListComp.generators,
2970 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002971}
2972
2973static int
2974compiler_setcomp(struct compiler *c, expr_ty e)
2975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 static identifier name;
2977 if (!name) {
2978 name = PyUnicode_FromString("<setcomp>");
2979 if (!name)
2980 return 0;
2981 }
2982 assert(e->kind == SetComp_kind);
2983 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2984 e->v.SetComp.generators,
2985 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002986}
2987
2988
2989static int
2990compiler_dictcomp(struct compiler *c, expr_ty e)
2991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 static identifier name;
2993 if (!name) {
2994 name = PyUnicode_FromString("<dictcomp>");
2995 if (!name)
2996 return 0;
2997 }
2998 assert(e->kind == DictComp_kind);
2999 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3000 e->v.DictComp.generators,
3001 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003002}
3003
3004
3005static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006compiler_visit_keyword(struct compiler *c, keyword_ty k)
3007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3009 VISIT(c, expr, k->value);
3010 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011}
3012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 whether they are true or false.
3015
3016 Return values: 1 for true, 0 for false, -1 for non-constant.
3017 */
3018
3019static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003020expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 char *id;
3023 switch (e->kind) {
3024 case Ellipsis_kind:
3025 return 1;
3026 case Num_kind:
3027 return PyObject_IsTrue(e->v.Num.n);
3028 case Str_kind:
3029 return PyObject_IsTrue(e->v.Str.s);
3030 case Name_kind:
3031 /* optimize away names that can't be reassigned */
3032 id = PyBytes_AS_STRING(
3033 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
3034 if (strcmp(id, "True") == 0) return 1;
3035 if (strcmp(id, "False") == 0) return 0;
3036 if (strcmp(id, "None") == 0) return 0;
3037 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003038 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 /* fall through */
3040 default:
3041 return -1;
3042 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043}
3044
Guido van Rossumc2e20742006-02-27 22:32:47 +00003045/*
3046 Implements the with statement from PEP 343.
3047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003049
3050 with EXPR as VAR:
3051 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052
Guido van Rossumc2e20742006-02-27 22:32:47 +00003053 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054
Thomas Wouters477c8d52006-05-27 19:21:47 +00003055 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003056 exit = context.__exit__ # not calling it
3057 value = context.__enter__()
3058 try:
3059 VAR = value # if VAR present in the syntax
3060 BLOCK
3061 finally:
3062 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003064 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003066 exit(*exc)
3067 */
3068static int
3069compiler_with(struct compiler *c, stmt_ty s)
3070{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003072
3073 assert(s->kind == With_kind);
3074
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075 block = compiler_new_block(c);
3076 finally = compiler_new_block(c);
3077 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003078 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079
Thomas Wouters477c8d52006-05-27 19:21:47 +00003080 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003082 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003083
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003084 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003085 compiler_use_next_block(c, block);
3086 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003087 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003088 }
3089
3090 if (s->v.With.optional_vars) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003091 VISIT(c, expr, s->v.With.optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003092 }
3093 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003095 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003096 }
3097
3098 /* BLOCK code */
3099 VISIT_SEQ(c, stmt, s->v.With.body);
3100
3101 /* End of try block; start the finally block */
3102 ADDOP(c, POP_BLOCK);
3103 compiler_pop_fblock(c, FINALLY_TRY, block);
3104
3105 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3106 compiler_use_next_block(c, finally);
3107 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003108 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003109
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003110 /* Finally block starts; context.__exit__ is on the stack under
3111 the exception or return information. Just issue our magic
3112 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003113 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003114
3115 /* Finally block ends. */
3116 ADDOP(c, END_FINALLY);
3117 compiler_pop_fblock(c, FINALLY_END, finally);
3118 return 1;
3119}
3120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121static int
3122compiler_visit_expr(struct compiler *c, expr_ty e)
3123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 /* If expr e has a different line number than the last expr/stmt,
3127 set a new line number for the next instruction.
3128 */
3129 if (e->lineno > c->u->u_lineno) {
3130 c->u->u_lineno = e->lineno;
3131 c->u->u_lineno_set = 0;
3132 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003133 /* Updating the column offset is always harmless. */
3134 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 switch (e->kind) {
3136 case BoolOp_kind:
3137 return compiler_boolop(c, e);
3138 case BinOp_kind:
3139 VISIT(c, expr, e->v.BinOp.left);
3140 VISIT(c, expr, e->v.BinOp.right);
3141 ADDOP(c, binop(c, e->v.BinOp.op));
3142 break;
3143 case UnaryOp_kind:
3144 VISIT(c, expr, e->v.UnaryOp.operand);
3145 ADDOP(c, unaryop(e->v.UnaryOp.op));
3146 break;
3147 case Lambda_kind:
3148 return compiler_lambda(c, e);
3149 case IfExp_kind:
3150 return compiler_ifexp(c, e);
3151 case Dict_kind:
3152 n = asdl_seq_LEN(e->v.Dict.values);
3153 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3154 for (i = 0; i < n; i++) {
3155 VISIT(c, expr,
3156 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3157 VISIT(c, expr,
3158 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3159 ADDOP(c, STORE_MAP);
3160 }
3161 break;
3162 case Set_kind:
3163 n = asdl_seq_LEN(e->v.Set.elts);
3164 VISIT_SEQ(c, expr, e->v.Set.elts);
3165 ADDOP_I(c, BUILD_SET, n);
3166 break;
3167 case GeneratorExp_kind:
3168 return compiler_genexp(c, e);
3169 case ListComp_kind:
3170 return compiler_listcomp(c, e);
3171 case SetComp_kind:
3172 return compiler_setcomp(c, e);
3173 case DictComp_kind:
3174 return compiler_dictcomp(c, e);
3175 case Yield_kind:
3176 if (c->u->u_ste->ste_type != FunctionBlock)
3177 return compiler_error(c, "'yield' outside function");
3178 if (e->v.Yield.value) {
3179 VISIT(c, expr, e->v.Yield.value);
3180 }
3181 else {
3182 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3183 }
3184 ADDOP(c, YIELD_VALUE);
3185 break;
3186 case Compare_kind:
3187 return compiler_compare(c, e);
3188 case Call_kind:
3189 return compiler_call(c, e);
3190 case Num_kind:
3191 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3192 break;
3193 case Str_kind:
3194 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3195 break;
3196 case Bytes_kind:
3197 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3198 break;
3199 case Ellipsis_kind:
3200 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3201 break;
3202 /* The following exprs can be assignment targets. */
3203 case Attribute_kind:
3204 if (e->v.Attribute.ctx != AugStore)
3205 VISIT(c, expr, e->v.Attribute.value);
3206 switch (e->v.Attribute.ctx) {
3207 case AugLoad:
3208 ADDOP(c, DUP_TOP);
3209 /* Fall through to load */
3210 case Load:
3211 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3212 break;
3213 case AugStore:
3214 ADDOP(c, ROT_TWO);
3215 /* Fall through to save */
3216 case Store:
3217 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3218 break;
3219 case Del:
3220 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3221 break;
3222 case Param:
3223 default:
3224 PyErr_SetString(PyExc_SystemError,
3225 "param invalid in attribute expression");
3226 return 0;
3227 }
3228 break;
3229 case Subscript_kind:
3230 switch (e->v.Subscript.ctx) {
3231 case AugLoad:
3232 VISIT(c, expr, e->v.Subscript.value);
3233 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3234 break;
3235 case Load:
3236 VISIT(c, expr, e->v.Subscript.value);
3237 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3238 break;
3239 case AugStore:
3240 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3241 break;
3242 case Store:
3243 VISIT(c, expr, e->v.Subscript.value);
3244 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3245 break;
3246 case Del:
3247 VISIT(c, expr, e->v.Subscript.value);
3248 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3249 break;
3250 case Param:
3251 default:
3252 PyErr_SetString(PyExc_SystemError,
3253 "param invalid in subscript expression");
3254 return 0;
3255 }
3256 break;
3257 case Starred_kind:
3258 switch (e->v.Starred.ctx) {
3259 case Store:
3260 /* In all legitimate cases, the Starred node was already replaced
3261 * by compiler_list/compiler_tuple. XXX: is that okay? */
3262 return compiler_error(c,
3263 "starred assignment target must be in a list or tuple");
3264 default:
3265 return compiler_error(c,
3266 "can use starred expression only as assignment target");
3267 }
3268 break;
3269 case Name_kind:
3270 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3271 /* child nodes of List and Tuple will have expr_context set */
3272 case List_kind:
3273 return compiler_list(c, e);
3274 case Tuple_kind:
3275 return compiler_tuple(c, e);
3276 }
3277 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278}
3279
3280static int
3281compiler_augassign(struct compiler *c, stmt_ty s)
3282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 expr_ty e = s->v.AugAssign.target;
3284 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 switch (e->kind) {
3289 case Attribute_kind:
3290 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3291 AugLoad, e->lineno, e->col_offset, c->c_arena);
3292 if (auge == NULL)
3293 return 0;
3294 VISIT(c, expr, auge);
3295 VISIT(c, expr, s->v.AugAssign.value);
3296 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3297 auge->v.Attribute.ctx = AugStore;
3298 VISIT(c, expr, auge);
3299 break;
3300 case Subscript_kind:
3301 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3302 AugLoad, e->lineno, e->col_offset, c->c_arena);
3303 if (auge == NULL)
3304 return 0;
3305 VISIT(c, expr, auge);
3306 VISIT(c, expr, s->v.AugAssign.value);
3307 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3308 auge->v.Subscript.ctx = AugStore;
3309 VISIT(c, expr, auge);
3310 break;
3311 case Name_kind:
3312 if (!compiler_nameop(c, e->v.Name.id, Load))
3313 return 0;
3314 VISIT(c, expr, s->v.AugAssign.value);
3315 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3316 return compiler_nameop(c, e->v.Name.id, Store);
3317 default:
3318 PyErr_Format(PyExc_SystemError,
3319 "invalid node type (%d) for augmented assignment",
3320 e->kind);
3321 return 0;
3322 }
3323 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324}
3325
3326static int
3327compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 struct fblockinfo *f;
3330 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3331 PyErr_SetString(PyExc_SystemError,
3332 "too many statically nested blocks");
3333 return 0;
3334 }
3335 f = &c->u->u_fblock[c->u->u_nfblocks++];
3336 f->fb_type = t;
3337 f->fb_block = b;
3338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339}
3340
3341static void
3342compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 struct compiler_unit *u = c->u;
3345 assert(u->u_nfblocks > 0);
3346 u->u_nfblocks--;
3347 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3348 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349}
3350
Thomas Wouters89f507f2006-12-13 04:49:30 +00003351static int
3352compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 int i;
3354 struct compiler_unit *u = c->u;
3355 for (i = 0; i < u->u_nfblocks; ++i) {
3356 if (u->u_fblock[i].fb_type == LOOP)
3357 return 1;
3358 }
3359 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003360}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003361/* Raises a SyntaxError and returns 0.
3362 If something goes wrong, a different exception may be raised.
3363*/
3364
3365static int
3366compiler_error(struct compiler *c, const char *errstr)
3367{
Victor Stinnerc0499822010-10-17 19:16:33 +00003368 PyObject *loc, *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3372 if (!loc) {
3373 Py_INCREF(Py_None);
3374 loc = Py_None;
3375 }
Victor Stinnerc0499822010-10-17 19:16:33 +00003376 if (c->c_filename != NULL) {
3377 filename = PyUnicode_DecodeFSDefault(c->c_filename);
3378 if (!filename)
3379 goto exit;
3380 }
3381 else {
3382 Py_INCREF(Py_None);
3383 filename = Py_None;
3384 }
3385 u = Py_BuildValue("(NiiO)", filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003386 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 if (!u)
3388 goto exit;
3389 v = Py_BuildValue("(zO)", errstr, u);
3390 if (!v)
3391 goto exit;
3392 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 Py_DECREF(loc);
3395 Py_XDECREF(u);
3396 Py_XDECREF(v);
3397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398}
3399
3400static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401compiler_handle_subscr(struct compiler *c, const char *kind,
3402 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* XXX this code is duplicated */
3407 switch (ctx) {
3408 case AugLoad: /* fall through to Load */
3409 case Load: op = BINARY_SUBSCR; break;
3410 case AugStore:/* fall through to Store */
3411 case Store: op = STORE_SUBSCR; break;
3412 case Del: op = DELETE_SUBSCR; break;
3413 case Param:
3414 PyErr_Format(PyExc_SystemError,
3415 "invalid %s kind %d in subscript\n",
3416 kind, ctx);
3417 return 0;
3418 }
3419 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003420 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 }
3422 else if (ctx == AugStore) {
3423 ADDOP(c, ROT_THREE);
3424 }
3425 ADDOP(c, op);
3426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427}
3428
3429static int
3430compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 int n = 2;
3433 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 /* only handles the cases where BUILD_SLICE is emitted */
3436 if (s->v.Slice.lower) {
3437 VISIT(c, expr, s->v.Slice.lower);
3438 }
3439 else {
3440 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3441 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 if (s->v.Slice.upper) {
3444 VISIT(c, expr, s->v.Slice.upper);
3445 }
3446 else {
3447 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3448 }
3449
3450 if (s->v.Slice.step) {
3451 n++;
3452 VISIT(c, expr, s->v.Slice.step);
3453 }
3454 ADDOP_I(c, BUILD_SLICE, n);
3455 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456}
3457
3458static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3460 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 switch (s->kind) {
3463 case Slice_kind:
3464 return compiler_slice(c, s, ctx);
3465 case Index_kind:
3466 VISIT(c, expr, s->v.Index.value);
3467 break;
3468 case ExtSlice_kind:
3469 default:
3470 PyErr_SetString(PyExc_SystemError,
3471 "extended slice invalid in nested slice");
3472 return 0;
3473 }
3474 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003475}
3476
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477static int
3478compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 char * kindname = NULL;
3481 switch (s->kind) {
3482 case Index_kind:
3483 kindname = "index";
3484 if (ctx != AugStore) {
3485 VISIT(c, expr, s->v.Index.value);
3486 }
3487 break;
3488 case Slice_kind:
3489 kindname = "slice";
3490 if (ctx != AugStore) {
3491 if (!compiler_slice(c, s, ctx))
3492 return 0;
3493 }
3494 break;
3495 case ExtSlice_kind:
3496 kindname = "extended slice";
3497 if (ctx != AugStore) {
3498 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3499 for (i = 0; i < n; i++) {
3500 slice_ty sub = (slice_ty)asdl_seq_GET(
3501 s->v.ExtSlice.dims, i);
3502 if (!compiler_visit_nested_slice(c, sub, ctx))
3503 return 0;
3504 }
3505 ADDOP_I(c, BUILD_TUPLE, n);
3506 }
3507 break;
3508 default:
3509 PyErr_Format(PyExc_SystemError,
3510 "invalid subscript kind %d", s->kind);
3511 return 0;
3512 }
3513 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514}
3515
Thomas Wouters89f507f2006-12-13 04:49:30 +00003516/* End of the compiler section, beginning of the assembler section */
3517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518/* do depth-first search of basic block graph, starting with block.
3519 post records the block indices in post-order.
3520
3521 XXX must handle implicit jumps from one block to next
3522*/
3523
Thomas Wouters89f507f2006-12-13 04:49:30 +00003524struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 PyObject *a_bytecode; /* string containing bytecode */
3526 int a_offset; /* offset into bytecode */
3527 int a_nblocks; /* number of reachable blocks */
3528 basicblock **a_postorder; /* list of blocks in dfs postorder */
3529 PyObject *a_lnotab; /* string containing lnotab */
3530 int a_lnotab_off; /* offset into lnotab */
3531 int a_lineno; /* last lineno of emitted instruction */
3532 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003533};
3534
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535static void
3536dfs(struct compiler *c, basicblock *b, struct assembler *a)
3537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 int i;
3539 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 if (b->b_seen)
3542 return;
3543 b->b_seen = 1;
3544 if (b->b_next != NULL)
3545 dfs(c, b->b_next, a);
3546 for (i = 0; i < b->b_iused; i++) {
3547 instr = &b->b_instr[i];
3548 if (instr->i_jrel || instr->i_jabs)
3549 dfs(c, instr->i_target, a);
3550 }
3551 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552}
3553
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003554static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 int i, target_depth;
3558 struct instr *instr;
3559 if (b->b_seen || b->b_startdepth >= depth)
3560 return maxdepth;
3561 b->b_seen = 1;
3562 b->b_startdepth = depth;
3563 for (i = 0; i < b->b_iused; i++) {
3564 instr = &b->b_instr[i];
3565 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3566 if (depth > maxdepth)
3567 maxdepth = depth;
3568 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3569 if (instr->i_jrel || instr->i_jabs) {
3570 target_depth = depth;
3571 if (instr->i_opcode == FOR_ITER) {
3572 target_depth = depth-2;
3573 } else if (instr->i_opcode == SETUP_FINALLY ||
3574 instr->i_opcode == SETUP_EXCEPT) {
3575 target_depth = depth+3;
3576 if (target_depth > maxdepth)
3577 maxdepth = target_depth;
3578 }
3579 maxdepth = stackdepth_walk(c, instr->i_target,
3580 target_depth, maxdepth);
3581 if (instr->i_opcode == JUMP_ABSOLUTE ||
3582 instr->i_opcode == JUMP_FORWARD) {
3583 goto out; /* remaining code is dead */
3584 }
3585 }
3586 }
3587 if (b->b_next)
3588 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 b->b_seen = 0;
3591 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592}
3593
3594/* Find the flow path that needs the largest stack. We assume that
3595 * cycles in the flow graph have no net effect on the stack depth.
3596 */
3597static int
3598stackdepth(struct compiler *c)
3599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 basicblock *b, *entryblock;
3601 entryblock = NULL;
3602 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3603 b->b_seen = 0;
3604 b->b_startdepth = INT_MIN;
3605 entryblock = b;
3606 }
3607 if (!entryblock)
3608 return 0;
3609 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610}
3611
3612static int
3613assemble_init(struct assembler *a, int nblocks, int firstlineno)
3614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 memset(a, 0, sizeof(struct assembler));
3616 a->a_lineno = firstlineno;
3617 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3618 if (!a->a_bytecode)
3619 return 0;
3620 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3621 if (!a->a_lnotab)
3622 return 0;
3623 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3624 PyErr_NoMemory();
3625 return 0;
3626 }
3627 a->a_postorder = (basicblock **)PyObject_Malloc(
3628 sizeof(basicblock *) * nblocks);
3629 if (!a->a_postorder) {
3630 PyErr_NoMemory();
3631 return 0;
3632 }
3633 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634}
3635
3636static void
3637assemble_free(struct assembler *a)
3638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 Py_XDECREF(a->a_bytecode);
3640 Py_XDECREF(a->a_lnotab);
3641 if (a->a_postorder)
3642 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643}
3644
3645/* Return the size of a basic block in bytes. */
3646
3647static int
3648instrsize(struct instr *instr)
3649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 if (!instr->i_hasarg)
3651 return 1; /* 1 byte for the opcode*/
3652 if (instr->i_oparg > 0xffff)
3653 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3654 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655}
3656
3657static int
3658blocksize(basicblock *b)
3659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 int i;
3661 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 for (i = 0; i < b->b_iused; i++)
3664 size += instrsize(&b->b_instr[i]);
3665 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666}
3667
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003668/* Appends a pair to the end of the line number table, a_lnotab, representing
3669 the instruction's bytecode offset and line number. See
3670 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003671
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003672static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 int d_bytecode, d_lineno;
3676 int len;
3677 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 d_bytecode = a->a_offset - a->a_lineno_off;
3680 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 assert(d_bytecode >= 0);
3683 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 if(d_bytecode == 0 && d_lineno == 0)
3686 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 if (d_bytecode > 255) {
3689 int j, nbytes, ncodes = d_bytecode / 255;
3690 nbytes = a->a_lnotab_off + 2 * ncodes;
3691 len = PyBytes_GET_SIZE(a->a_lnotab);
3692 if (nbytes >= len) {
3693 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3694 len = nbytes;
3695 else if (len <= INT_MAX / 2)
3696 len *= 2;
3697 else {
3698 PyErr_NoMemory();
3699 return 0;
3700 }
3701 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3702 return 0;
3703 }
3704 lnotab = (unsigned char *)
3705 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3706 for (j = 0; j < ncodes; j++) {
3707 *lnotab++ = 255;
3708 *lnotab++ = 0;
3709 }
3710 d_bytecode -= ncodes * 255;
3711 a->a_lnotab_off += ncodes * 2;
3712 }
3713 assert(d_bytecode <= 255);
3714 if (d_lineno > 255) {
3715 int j, nbytes, ncodes = d_lineno / 255;
3716 nbytes = a->a_lnotab_off + 2 * ncodes;
3717 len = PyBytes_GET_SIZE(a->a_lnotab);
3718 if (nbytes >= len) {
3719 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3720 len = nbytes;
3721 else if (len <= INT_MAX / 2)
3722 len *= 2;
3723 else {
3724 PyErr_NoMemory();
3725 return 0;
3726 }
3727 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3728 return 0;
3729 }
3730 lnotab = (unsigned char *)
3731 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3732 *lnotab++ = d_bytecode;
3733 *lnotab++ = 255;
3734 d_bytecode = 0;
3735 for (j = 1; j < ncodes; j++) {
3736 *lnotab++ = 0;
3737 *lnotab++ = 255;
3738 }
3739 d_lineno -= ncodes * 255;
3740 a->a_lnotab_off += ncodes * 2;
3741 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 len = PyBytes_GET_SIZE(a->a_lnotab);
3744 if (a->a_lnotab_off + 2 >= len) {
3745 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3746 return 0;
3747 }
3748 lnotab = (unsigned char *)
3749 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 a->a_lnotab_off += 2;
3752 if (d_bytecode) {
3753 *lnotab++ = d_bytecode;
3754 *lnotab++ = d_lineno;
3755 }
3756 else { /* First line of a block; def stmt, etc. */
3757 *lnotab++ = 0;
3758 *lnotab++ = d_lineno;
3759 }
3760 a->a_lineno = i->i_lineno;
3761 a->a_lineno_off = a->a_offset;
3762 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003763}
3764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765/* assemble_emit()
3766 Extend the bytecode with a new instruction.
3767 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003768*/
3769
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003770static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 int size, arg = 0, ext = 0;
3774 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3775 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 size = instrsize(i);
3778 if (i->i_hasarg) {
3779 arg = i->i_oparg;
3780 ext = arg >> 16;
3781 }
3782 if (i->i_lineno && !assemble_lnotab(a, i))
3783 return 0;
3784 if (a->a_offset + size >= len) {
3785 if (len > PY_SSIZE_T_MAX / 2)
3786 return 0;
3787 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3788 return 0;
3789 }
3790 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3791 a->a_offset += size;
3792 if (size == 6) {
3793 assert(i->i_hasarg);
3794 *code++ = (char)EXTENDED_ARG;
3795 *code++ = ext & 0xff;
3796 *code++ = ext >> 8;
3797 arg &= 0xffff;
3798 }
3799 *code++ = i->i_opcode;
3800 if (i->i_hasarg) {
3801 assert(size == 3 || size == 6);
3802 *code++ = arg & 0xff;
3803 *code++ = arg >> 8;
3804 }
3805 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003806}
3807
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003808static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 basicblock *b;
3812 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3813 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 /* Compute the size of each block and fixup jump args.
3816 Replace block pointer with position in bytecode. */
3817 do {
3818 totsize = 0;
3819 for (i = a->a_nblocks - 1; i >= 0; i--) {
3820 b = a->a_postorder[i];
3821 bsize = blocksize(b);
3822 b->b_offset = totsize;
3823 totsize += bsize;
3824 }
3825 last_extended_arg_count = extended_arg_count;
3826 extended_arg_count = 0;
3827 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3828 bsize = b->b_offset;
3829 for (i = 0; i < b->b_iused; i++) {
3830 struct instr *instr = &b->b_instr[i];
3831 /* Relative jumps are computed relative to
3832 the instruction pointer after fetching
3833 the jump instruction.
3834 */
3835 bsize += instrsize(instr);
3836 if (instr->i_jabs)
3837 instr->i_oparg = instr->i_target->b_offset;
3838 else if (instr->i_jrel) {
3839 int delta = instr->i_target->b_offset - bsize;
3840 instr->i_oparg = delta;
3841 }
3842 else
3843 continue;
3844 if (instr->i_oparg > 0xffff)
3845 extended_arg_count++;
3846 }
3847 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 /* XXX: This is an awful hack that could hurt performance, but
3850 on the bright side it should work until we come up
3851 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 The issue is that in the first loop blocksize() is called
3854 which calls instrsize() which requires i_oparg be set
3855 appropriately. There is a bootstrap problem because
3856 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 So we loop until we stop seeing new EXTENDED_ARGs.
3859 The only EXTENDED_ARGs that could be popping up are
3860 ones in jump instructions. So this should converge
3861 fairly quickly.
3862 */
3863 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003864}
3865
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003866static PyObject *
3867dict_keys_inorder(PyObject *dict, int offset)
3868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 PyObject *tuple, *k, *v;
3870 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 tuple = PyTuple_New(size);
3873 if (tuple == NULL)
3874 return NULL;
3875 while (PyDict_Next(dict, &pos, &k, &v)) {
3876 i = PyLong_AS_LONG(v);
3877 /* The keys of the dictionary are tuples. (see compiler_add_o)
3878 The object we want is always first, though. */
3879 k = PyTuple_GET_ITEM(k, 0);
3880 Py_INCREF(k);
3881 assert((i - offset) < size);
3882 assert((i - offset) >= 0);
3883 PyTuple_SET_ITEM(tuple, i - offset, k);
3884 }
3885 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003886}
3887
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003888static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 PySTEntryObject *ste = c->u->u_ste;
3892 int flags = 0, n;
3893 if (ste->ste_type != ModuleBlock)
3894 flags |= CO_NEWLOCALS;
3895 if (ste->ste_type == FunctionBlock) {
3896 if (!ste->ste_unoptimized)
3897 flags |= CO_OPTIMIZED;
3898 if (ste->ste_nested)
3899 flags |= CO_NESTED;
3900 if (ste->ste_generator)
3901 flags |= CO_GENERATOR;
3902 if (ste->ste_varargs)
3903 flags |= CO_VARARGS;
3904 if (ste->ste_varkeywords)
3905 flags |= CO_VARKEYWORDS;
3906 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 /* (Only) inherit compilerflags in PyCF_MASK */
3909 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 n = PyDict_Size(c->u->u_freevars);
3912 if (n < 0)
3913 return -1;
3914 if (n == 0) {
3915 n = PyDict_Size(c->u->u_cellvars);
3916 if (n < 0)
3917 return -1;
3918 if (n == 0) {
3919 flags |= CO_NOFREE;
3920 }
3921 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003924}
3925
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003926static PyCodeObject *
3927makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 PyObject *tmp;
3930 PyCodeObject *co = NULL;
3931 PyObject *consts = NULL;
3932 PyObject *names = NULL;
3933 PyObject *varnames = NULL;
3934 PyObject *filename = NULL;
3935 PyObject *name = NULL;
3936 PyObject *freevars = NULL;
3937 PyObject *cellvars = NULL;
3938 PyObject *bytecode = NULL;
3939 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 tmp = dict_keys_inorder(c->u->u_consts, 0);
3942 if (!tmp)
3943 goto error;
3944 consts = PySequence_List(tmp); /* optimize_code requires a list */
3945 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 names = dict_keys_inorder(c->u->u_names, 0);
3948 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3949 if (!consts || !names || !varnames)
3950 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3953 if (!cellvars)
3954 goto error;
3955 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3956 if (!freevars)
3957 goto error;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00003958 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 if (!filename)
3960 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 nlocals = PyDict_Size(c->u->u_varnames);
3963 flags = compute_code_flags(c);
3964 if (flags < 0)
3965 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3968 if (!bytecode)
3969 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3972 if (!tmp)
3973 goto error;
3974 Py_DECREF(consts);
3975 consts = tmp;
3976
3977 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3978 nlocals, stackdepth(c), flags,
3979 bytecode, consts, names, varnames,
3980 freevars, cellvars,
3981 filename, c->u->u_name,
3982 c->u->u_firstlineno,
3983 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003984 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 Py_XDECREF(consts);
3986 Py_XDECREF(names);
3987 Py_XDECREF(varnames);
3988 Py_XDECREF(filename);
3989 Py_XDECREF(name);
3990 Py_XDECREF(freevars);
3991 Py_XDECREF(cellvars);
3992 Py_XDECREF(bytecode);
3993 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003994}
3995
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003996
3997/* For debugging purposes only */
3998#if 0
3999static void
4000dump_instr(const struct instr *i)
4001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 const char *jrel = i->i_jrel ? "jrel " : "";
4003 const char *jabs = i->i_jabs ? "jabs " : "";
4004 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 *arg = '\0';
4007 if (i->i_hasarg)
4008 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4011 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004012}
4013
4014static void
4015dump_basicblock(const basicblock *b)
4016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 const char *seen = b->b_seen ? "seen " : "";
4018 const char *b_return = b->b_return ? "return " : "";
4019 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4020 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4021 if (b->b_instr) {
4022 int i;
4023 for (i = 0; i < b->b_iused; i++) {
4024 fprintf(stderr, " [%02d] ", i);
4025 dump_instr(b->b_instr + i);
4026 }
4027 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004028}
4029#endif
4030
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004031static PyCodeObject *
4032assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 basicblock *b, *entryblock;
4035 struct assembler a;
4036 int i, j, nblocks;
4037 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 /* Make sure every block that falls off the end returns None.
4040 XXX NEXT_BLOCK() isn't quite right, because if the last
4041 block ends with a jump or return b_next shouldn't set.
4042 */
4043 if (!c->u->u_curblock->b_return) {
4044 NEXT_BLOCK(c);
4045 if (addNone)
4046 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4047 ADDOP(c, RETURN_VALUE);
4048 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 nblocks = 0;
4051 entryblock = NULL;
4052 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4053 nblocks++;
4054 entryblock = b;
4055 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 /* Set firstlineno if it wasn't explicitly set. */
4058 if (!c->u->u_firstlineno) {
4059 if (entryblock && entryblock->b_instr)
4060 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4061 else
4062 c->u->u_firstlineno = 1;
4063 }
4064 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4065 goto error;
4066 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 /* Can't modify the bytecode after computing jump offsets. */
4069 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 /* Emit code in reverse postorder from dfs. */
4072 for (i = a.a_nblocks - 1; i >= 0; i--) {
4073 b = a.a_postorder[i];
4074 for (j = 0; j < b->b_iused; j++)
4075 if (!assemble_emit(&a, &b->b_instr[j]))
4076 goto error;
4077 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4080 goto error;
4081 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4082 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 assemble_free(&a);
4087 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004088}
Georg Brandl8334fd92010-12-04 10:26:46 +00004089
4090#undef PyAST_Compile
4091PyAPI_FUNC(PyCodeObject *)
4092PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4093 PyArena *arena)
4094{
4095 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4096}
4097
4098