blob: 1d6e38c22e3db7810948d688323f4587b051dc1b [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_) {
1322 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
1323 if (!compiler_visit_expr(c, default_)) {
1324 return -1;
1325 }
1326 default_count++;
1327 }
1328 }
1329 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001330}
1331
1332static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001333compiler_visit_argannotation(struct compiler *c, identifier id,
1334 expr_ty annotation, PyObject *names)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (annotation) {
1337 VISIT(c, expr, annotation);
1338 if (PyList_Append(names, id))
1339 return -1;
1340 }
1341 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001342}
1343
1344static int
1345compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1346 PyObject *names)
1347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 int i, error;
1349 for (i = 0; i < asdl_seq_LEN(args); i++) {
1350 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1351 error = compiler_visit_argannotation(
1352 c,
1353 arg->arg,
1354 arg->annotation,
1355 names);
1356 if (error)
1357 return error;
1358 }
1359 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001360}
1361
1362static int
1363compiler_visit_annotations(struct compiler *c, arguments_ty args,
1364 expr_ty returns)
1365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* Push arg annotations and a list of the argument names. Return the #
1367 of items pushed. The expressions are evaluated out-of-order wrt the
1368 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1371 */
1372 static identifier return_str;
1373 PyObject *names;
1374 int len;
1375 names = PyList_New(0);
1376 if (!names)
1377 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (compiler_visit_argannotations(c, args->args, names))
1380 goto error;
1381 if (args->varargannotation &&
1382 compiler_visit_argannotation(c, args->vararg,
1383 args->varargannotation, names))
1384 goto error;
1385 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1386 goto error;
1387 if (args->kwargannotation &&
1388 compiler_visit_argannotation(c, args->kwarg,
1389 args->kwargannotation, names))
1390 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (!return_str) {
1393 return_str = PyUnicode_InternFromString("return");
1394 if (!return_str)
1395 goto error;
1396 }
1397 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1398 goto error;
1399 }
1400
1401 len = PyList_GET_SIZE(names);
1402 if (len > 65534) {
1403 /* len must fit in 16 bits, and len is incremented below */
1404 PyErr_SetString(PyExc_SyntaxError,
1405 "too many annotations");
1406 goto error;
1407 }
1408 if (len) {
1409 /* convert names to a tuple and place on stack */
1410 PyObject *elt;
1411 int i;
1412 PyObject *s = PyTuple_New(len);
1413 if (!s)
1414 goto error;
1415 for (i = 0; i < len; i++) {
1416 elt = PyList_GET_ITEM(names, i);
1417 Py_INCREF(elt);
1418 PyTuple_SET_ITEM(s, i, elt);
1419 }
1420 ADDOP_O(c, LOAD_CONST, s, consts);
1421 Py_DECREF(s);
1422 len++; /* include the just-pushed tuple */
1423 }
1424 Py_DECREF(names);
1425 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001426
1427error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 Py_DECREF(names);
1429 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001430}
1431
1432static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433compiler_function(struct compiler *c, stmt_ty s)
1434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyCodeObject *co;
1436 PyObject *first_const = Py_None;
1437 arguments_ty args = s->v.FunctionDef.args;
1438 expr_ty returns = s->v.FunctionDef.returns;
1439 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1440 stmt_ty st;
1441 int i, n, docstring, kw_default_count = 0, arglength;
1442 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!compiler_decorators(c, decos))
1447 return 0;
1448 if (args->kwonlyargs) {
1449 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1450 args->kw_defaults);
1451 if (res < 0)
1452 return 0;
1453 kw_default_count = res;
1454 }
1455 if (args->defaults)
1456 VISIT_SEQ(c, expr, args->defaults);
1457 num_annotations = compiler_visit_annotations(c, args, returns);
1458 if (num_annotations < 0)
1459 return 0;
1460 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1463 s->lineno))
1464 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1467 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001468 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 first_const = st->v.Expr.value->v.Str.s;
1470 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1471 compiler_exit_scope(c);
1472 return 0;
1473 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 c->u->u_argcount = asdl_seq_LEN(args->args);
1476 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1477 n = asdl_seq_LEN(s->v.FunctionDef.body);
1478 /* if there was a docstring, we need to skip the first statement */
1479 for (i = docstring; i < n; i++) {
1480 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1481 VISIT_IN_SCOPE(c, stmt, st);
1482 }
1483 co = assemble(c, 1);
1484 compiler_exit_scope(c);
1485 if (co == NULL)
1486 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 arglength = asdl_seq_LEN(args->defaults);
1489 arglength |= kw_default_count << 8;
1490 arglength |= num_annotations << 16;
1491 compiler_make_closure(c, co, arglength);
1492 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 /* decorators */
1495 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1496 ADDOP_I(c, CALL_FUNCTION, 1);
1497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
1502static int
1503compiler_class(struct compiler *c, stmt_ty s)
1504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 PyCodeObject *co;
1506 PyObject *str;
1507 int i;
1508 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 if (!compiler_decorators(c, decos))
1511 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* ultimately generate code for:
1514 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1515 where:
1516 <func> is a function/closure created from the class body;
1517 it has a single argument (__locals__) where the dict
1518 (or MutableSequence) representing the locals is passed
1519 <name> is the class name
1520 <bases> is the positional arguments and *varargs argument
1521 <keywords> is the keyword arguments and **kwds argument
1522 This borrows from compiler_call.
1523 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 /* 1. compile the class body into a code object */
1526 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1527 return 0;
1528 /* this block represents what we do in the new scope */
1529 {
1530 /* use the class name for name mangling */
1531 Py_INCREF(s->v.ClassDef.name);
1532 Py_XDECREF(c->u->u_private);
1533 c->u->u_private = s->v.ClassDef.name;
1534 /* force it to have one mandatory argument */
1535 c->u->u_argcount = 1;
1536 /* load the first argument (__locals__) ... */
1537 ADDOP_I(c, LOAD_FAST, 0);
1538 /* ... and store it into f_locals */
1539 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1540 /* load (global) __name__ ... */
1541 str = PyUnicode_InternFromString("__name__");
1542 if (!str || !compiler_nameop(c, str, Load)) {
1543 Py_XDECREF(str);
1544 compiler_exit_scope(c);
1545 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001546 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 Py_DECREF(str);
1548 /* ... and store it as __module__ */
1549 str = PyUnicode_InternFromString("__module__");
1550 if (!str || !compiler_nameop(c, str, Store)) {
1551 Py_XDECREF(str);
1552 compiler_exit_scope(c);
1553 return 0;
1554 }
1555 Py_DECREF(str);
1556 /* compile the body proper */
1557 if (!compiler_body(c, s->v.ClassDef.body)) {
1558 compiler_exit_scope(c);
1559 return 0;
1560 }
1561 /* return the (empty) __class__ cell */
1562 str = PyUnicode_InternFromString("__class__");
1563 if (str == NULL) {
1564 compiler_exit_scope(c);
1565 return 0;
1566 }
1567 i = compiler_lookup_arg(c->u->u_cellvars, str);
1568 Py_DECREF(str);
1569 if (i == -1) {
1570 /* This happens when nobody references the cell */
1571 PyErr_Clear();
1572 /* Return None */
1573 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1574 }
1575 else {
1576 /* Return the cell where to store __class__ */
1577 ADDOP_I(c, LOAD_CLOSURE, i);
1578 }
1579 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1580 /* create the code object */
1581 co = assemble(c, 1);
1582 }
1583 /* leave the new scope */
1584 compiler_exit_scope(c);
1585 if (co == NULL)
1586 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* 2. load the 'build_class' function */
1589 ADDOP(c, LOAD_BUILD_CLASS);
1590
1591 /* 3. load a function (or closure) made from the code object */
1592 compiler_make_closure(c, co, 0);
1593 Py_DECREF(co);
1594
1595 /* 4. load class name */
1596 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1597
1598 /* 5. generate the rest of the code for the call */
1599 if (!compiler_call_helper(c, 2,
1600 s->v.ClassDef.bases,
1601 s->v.ClassDef.keywords,
1602 s->v.ClassDef.starargs,
1603 s->v.ClassDef.kwargs))
1604 return 0;
1605
1606 /* 6. apply decorators */
1607 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1608 ADDOP_I(c, CALL_FUNCTION, 1);
1609 }
1610
1611 /* 7. store into <name> */
1612 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1613 return 0;
1614 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615}
1616
1617static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001618compiler_ifexp(struct compiler *c, expr_ty e)
1619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 basicblock *end, *next;
1621
1622 assert(e->kind == IfExp_kind);
1623 end = compiler_new_block(c);
1624 if (end == NULL)
1625 return 0;
1626 next = compiler_new_block(c);
1627 if (next == NULL)
1628 return 0;
1629 VISIT(c, expr, e->v.IfExp.test);
1630 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1631 VISIT(c, expr, e->v.IfExp.body);
1632 ADDOP_JREL(c, JUMP_FORWARD, end);
1633 compiler_use_next_block(c, next);
1634 VISIT(c, expr, e->v.IfExp.orelse);
1635 compiler_use_next_block(c, end);
1636 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001637}
1638
1639static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640compiler_lambda(struct compiler *c, expr_ty e)
1641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyCodeObject *co;
1643 static identifier name;
1644 int kw_default_count = 0, arglength;
1645 arguments_ty args = e->v.Lambda.args;
1646 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (!name) {
1649 name = PyUnicode_InternFromString("<lambda>");
1650 if (!name)
1651 return 0;
1652 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (args->kwonlyargs) {
1655 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1656 args->kw_defaults);
1657 if (res < 0) return 0;
1658 kw_default_count = res;
1659 }
1660 if (args->defaults)
1661 VISIT_SEQ(c, expr, args->defaults);
1662 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1663 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 /* Make None the first constant, so the lambda can't have a
1666 docstring. */
1667 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1668 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 c->u->u_argcount = asdl_seq_LEN(args->args);
1671 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1672 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1673 if (c->u->u_ste->ste_generator) {
1674 ADDOP_IN_SCOPE(c, POP_TOP);
1675 }
1676 else {
1677 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1678 }
1679 co = assemble(c, 1);
1680 compiler_exit_scope(c);
1681 if (co == NULL)
1682 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 arglength = asdl_seq_LEN(args->defaults);
1685 arglength |= kw_default_count << 8;
1686 compiler_make_closure(c, co, arglength);
1687 Py_DECREF(co);
1688
1689 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690}
1691
1692static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693compiler_if(struct compiler *c, stmt_ty s)
1694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 basicblock *end, *next;
1696 int constant;
1697 assert(s->kind == If_kind);
1698 end = compiler_new_block(c);
1699 if (end == NULL)
1700 return 0;
1701
Georg Brandl8334fd92010-12-04 10:26:46 +00001702 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 /* constant = 0: "if 0"
1704 * constant = 1: "if 1", "if 2", ...
1705 * constant = -1: rest */
1706 if (constant == 0) {
1707 if (s->v.If.orelse)
1708 VISIT_SEQ(c, stmt, s->v.If.orelse);
1709 } else if (constant == 1) {
1710 VISIT_SEQ(c, stmt, s->v.If.body);
1711 } else {
1712 if (s->v.If.orelse) {
1713 next = compiler_new_block(c);
1714 if (next == NULL)
1715 return 0;
1716 }
1717 else
1718 next = end;
1719 VISIT(c, expr, s->v.If.test);
1720 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1721 VISIT_SEQ(c, stmt, s->v.If.body);
1722 ADDOP_JREL(c, JUMP_FORWARD, end);
1723 if (s->v.If.orelse) {
1724 compiler_use_next_block(c, next);
1725 VISIT_SEQ(c, stmt, s->v.If.orelse);
1726 }
1727 }
1728 compiler_use_next_block(c, end);
1729 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001730}
1731
1732static int
1733compiler_for(struct compiler *c, stmt_ty s)
1734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 start = compiler_new_block(c);
1738 cleanup = compiler_new_block(c);
1739 end = compiler_new_block(c);
1740 if (start == NULL || end == NULL || cleanup == NULL)
1741 return 0;
1742 ADDOP_JREL(c, SETUP_LOOP, end);
1743 if (!compiler_push_fblock(c, LOOP, start))
1744 return 0;
1745 VISIT(c, expr, s->v.For.iter);
1746 ADDOP(c, GET_ITER);
1747 compiler_use_next_block(c, start);
1748 ADDOP_JREL(c, FOR_ITER, cleanup);
1749 VISIT(c, expr, s->v.For.target);
1750 VISIT_SEQ(c, stmt, s->v.For.body);
1751 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1752 compiler_use_next_block(c, cleanup);
1753 ADDOP(c, POP_BLOCK);
1754 compiler_pop_fblock(c, LOOP, start);
1755 VISIT_SEQ(c, stmt, s->v.For.orelse);
1756 compiler_use_next_block(c, end);
1757 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758}
1759
1760static int
1761compiler_while(struct compiler *c, stmt_ty s)
1762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001764 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (constant == 0) {
1767 if (s->v.While.orelse)
1768 VISIT_SEQ(c, stmt, s->v.While.orelse);
1769 return 1;
1770 }
1771 loop = compiler_new_block(c);
1772 end = compiler_new_block(c);
1773 if (constant == -1) {
1774 anchor = compiler_new_block(c);
1775 if (anchor == NULL)
1776 return 0;
1777 }
1778 if (loop == NULL || end == NULL)
1779 return 0;
1780 if (s->v.While.orelse) {
1781 orelse = compiler_new_block(c);
1782 if (orelse == NULL)
1783 return 0;
1784 }
1785 else
1786 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 ADDOP_JREL(c, SETUP_LOOP, end);
1789 compiler_use_next_block(c, loop);
1790 if (!compiler_push_fblock(c, LOOP, loop))
1791 return 0;
1792 if (constant == -1) {
1793 VISIT(c, expr, s->v.While.test);
1794 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1795 }
1796 VISIT_SEQ(c, stmt, s->v.While.body);
1797 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 /* XXX should the two POP instructions be in a separate block
1800 if there is no else clause ?
1801 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (constant == -1) {
1804 compiler_use_next_block(c, anchor);
1805 ADDOP(c, POP_BLOCK);
1806 }
1807 compiler_pop_fblock(c, LOOP, loop);
1808 if (orelse != NULL) /* what if orelse is just pass? */
1809 VISIT_SEQ(c, stmt, s->v.While.orelse);
1810 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813}
1814
1815static int
1816compiler_continue(struct compiler *c)
1817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1819 static const char IN_FINALLY_ERROR_MSG[] =
1820 "'continue' not supported inside 'finally' clause";
1821 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (!c->u->u_nfblocks)
1824 return compiler_error(c, LOOP_ERROR_MSG);
1825 i = c->u->u_nfblocks - 1;
1826 switch (c->u->u_fblock[i].fb_type) {
1827 case LOOP:
1828 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1829 break;
1830 case EXCEPT:
1831 case FINALLY_TRY:
1832 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1833 /* Prevent continue anywhere under a finally
1834 even if hidden in a sub-try or except. */
1835 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1836 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1837 }
1838 if (i == -1)
1839 return compiler_error(c, LOOP_ERROR_MSG);
1840 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1841 break;
1842 case FINALLY_END:
1843 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1844 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847}
1848
1849/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850
1851 SETUP_FINALLY L
1852 <code for body>
1853 POP_BLOCK
1854 LOAD_CONST <None>
1855 L: <code for finalbody>
1856 END_FINALLY
1857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858 The special instructions use the block stack. Each block
1859 stack entry contains the instruction that created it (here
1860 SETUP_FINALLY), the level of the value stack at the time the
1861 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 Pushes the current value stack level and the label
1865 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 Pops en entry from the block stack, and pops the value
1868 stack until its level is the same as indicated on the
1869 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 Pops a variable number of entries from the *value* stack
1872 and re-raises the exception they specify. The number of
1873 entries popped depends on the (pseudo) exception type.
1874
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875 The block stack is unwound when an exception is raised:
1876 when a SETUP_FINALLY entry is found, the exception is pushed
1877 onto the value stack (and the exception condition is cleared),
1878 and the interpreter jumps to the label gotten from the block
1879 stack.
1880*/
1881
1882static int
1883compiler_try_finally(struct compiler *c, stmt_ty s)
1884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 basicblock *body, *end;
1886 body = compiler_new_block(c);
1887 end = compiler_new_block(c);
1888 if (body == NULL || end == NULL)
1889 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 ADDOP_JREL(c, SETUP_FINALLY, end);
1892 compiler_use_next_block(c, body);
1893 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1894 return 0;
1895 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1896 ADDOP(c, POP_BLOCK);
1897 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1900 compiler_use_next_block(c, end);
1901 if (!compiler_push_fblock(c, FINALLY_END, end))
1902 return 0;
1903 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1904 ADDOP(c, END_FINALLY);
1905 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908}
1909
1910/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001911 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912 (The contents of the value stack is shown in [], with the top
1913 at the right; 'tb' is trace-back info, 'val' the exception's
1914 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915
1916 Value stack Label Instruction Argument
1917 [] SETUP_EXCEPT L1
1918 [] <code for S>
1919 [] POP_BLOCK
1920 [] JUMP_FORWARD L0
1921
1922 [tb, val, exc] L1: DUP )
1923 [tb, val, exc, exc] <evaluate E1> )
1924 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1925 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1926 [tb, val, exc] POP
1927 [tb, val] <assign to V1> (or POP if no V1)
1928 [tb] POP
1929 [] <code for S1>
1930 JUMP_FORWARD L0
1931
1932 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933 .............................etc.......................
1934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1936
1937 [] L0: <next statement>
1938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939 Of course, parts are not generated if Vi or Ei is not present.
1940*/
1941static int
1942compiler_try_except(struct compiler *c, stmt_ty s)
1943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 basicblock *body, *orelse, *except, *end;
1945 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 body = compiler_new_block(c);
1948 except = compiler_new_block(c);
1949 orelse = compiler_new_block(c);
1950 end = compiler_new_block(c);
1951 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1952 return 0;
1953 ADDOP_JREL(c, SETUP_EXCEPT, except);
1954 compiler_use_next_block(c, body);
1955 if (!compiler_push_fblock(c, EXCEPT, body))
1956 return 0;
1957 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1958 ADDOP(c, POP_BLOCK);
1959 compiler_pop_fblock(c, EXCEPT, body);
1960 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1961 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1962 compiler_use_next_block(c, except);
1963 for (i = 0; i < n; i++) {
1964 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1965 s->v.TryExcept.handlers, i);
1966 if (!handler->v.ExceptHandler.type && i < n-1)
1967 return compiler_error(c, "default 'except:' must be last");
1968 c->u->u_lineno_set = 0;
1969 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00001970 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 except = compiler_new_block(c);
1972 if (except == NULL)
1973 return 0;
1974 if (handler->v.ExceptHandler.type) {
1975 ADDOP(c, DUP_TOP);
1976 VISIT(c, expr, handler->v.ExceptHandler.type);
1977 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1978 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
1979 }
1980 ADDOP(c, POP_TOP);
1981 if (handler->v.ExceptHandler.name) {
1982 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 cleanup_end = compiler_new_block(c);
1985 cleanup_body = compiler_new_block(c);
1986 if(!(cleanup_end || cleanup_body))
1987 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
1990 ADDOP(c, POP_TOP);
1991
1992 /*
1993 try:
1994 # body
1995 except type as name:
1996 try:
1997 # body
1998 finally:
1999 name = None
2000 del name
2001 */
2002
2003 /* second try: */
2004 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2005 compiler_use_next_block(c, cleanup_body);
2006 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2007 return 0;
2008
2009 /* second # body */
2010 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2011 ADDOP(c, POP_BLOCK);
2012 ADDOP(c, POP_EXCEPT);
2013 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2014
2015 /* finally: */
2016 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2017 compiler_use_next_block(c, cleanup_end);
2018 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2019 return 0;
2020
2021 /* name = None */
2022 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2023 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2024
2025 /* del name */
2026 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
2027
2028 ADDOP(c, END_FINALLY);
2029 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
2030 }
2031 else {
2032 basicblock *cleanup_body;
2033
2034 cleanup_body = compiler_new_block(c);
2035 if(!cleanup_body)
2036 return 0;
2037
Guido van Rossumb940e112007-01-10 16:19:56 +00002038 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 ADDOP(c, POP_TOP);
2040 compiler_use_next_block(c, cleanup_body);
2041 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2042 return 0;
2043 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2044 ADDOP(c, POP_EXCEPT);
2045 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2046 }
2047 ADDOP_JREL(c, JUMP_FORWARD, end);
2048 compiler_use_next_block(c, except);
2049 }
2050 ADDOP(c, END_FINALLY);
2051 compiler_use_next_block(c, orelse);
2052 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2053 compiler_use_next_block(c, end);
2054 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055}
2056
2057static int
2058compiler_import_as(struct compiler *c, identifier name, identifier asname)
2059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* The IMPORT_NAME opcode was already generated. This function
2061 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 If there is a dot in name, we need to split it and emit a
2064 LOAD_ATTR for each name.
2065 */
2066 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2067 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
2068 if (dot) {
2069 /* Consume the base module name to get the first attribute */
2070 src = dot + 1;
2071 while (dot) {
2072 /* NB src is only defined when dot != NULL */
2073 PyObject *attr;
2074 dot = Py_UNICODE_strchr(src, '.');
2075 attr = PyUnicode_FromUnicode(src,
2076 dot ? dot - src : Py_UNICODE_strlen(src));
2077 if (!attr)
2078 return -1;
2079 ADDOP_O(c, LOAD_ATTR, attr, names);
2080 Py_DECREF(attr);
2081 src = dot + 1;
2082 }
2083 }
2084 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085}
2086
2087static int
2088compiler_import(struct compiler *c, stmt_ty s)
2089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 /* The Import node stores a module name like a.b.c as a single
2091 string. This is convenient for all cases except
2092 import a.b.c as d
2093 where we need to parse that string to extract the individual
2094 module names.
2095 XXX Perhaps change the representation to make this case simpler?
2096 */
2097 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 for (i = 0; i < n; i++) {
2100 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2101 int r;
2102 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 level = PyLong_FromLong(0);
2105 if (level == NULL)
2106 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 ADDOP_O(c, LOAD_CONST, level, consts);
2109 Py_DECREF(level);
2110 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2111 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (alias->asname) {
2114 r = compiler_import_as(c, alias->name, alias->asname);
2115 if (!r)
2116 return r;
2117 }
2118 else {
2119 identifier tmp = alias->name;
2120 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2121 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
2122 if (dot)
2123 tmp = PyUnicode_FromUnicode(base,
2124 dot - base);
2125 r = compiler_nameop(c, tmp, Store);
2126 if (dot) {
2127 Py_DECREF(tmp);
2128 }
2129 if (!r)
2130 return r;
2131 }
2132 }
2133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134}
2135
2136static int
2137compiler_from_import(struct compiler *c, stmt_ty s)
2138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 PyObject *names = PyTuple_New(n);
2142 PyObject *level;
2143 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (!empty_string) {
2146 empty_string = PyUnicode_FromString("");
2147 if (!empty_string)
2148 return 0;
2149 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (!names)
2152 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 level = PyLong_FromLong(s->v.ImportFrom.level);
2155 if (!level) {
2156 Py_DECREF(names);
2157 return 0;
2158 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* build up the names */
2161 for (i = 0; i < n; i++) {
2162 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2163 Py_INCREF(alias->name);
2164 PyTuple_SET_ITEM(names, i, alias->name);
2165 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2168 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2169 Py_DECREF(level);
2170 Py_DECREF(names);
2171 return compiler_error(c, "from __future__ imports must occur "
2172 "at the beginning of the file");
2173 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 ADDOP_O(c, LOAD_CONST, level, consts);
2176 Py_DECREF(level);
2177 ADDOP_O(c, LOAD_CONST, names, consts);
2178 Py_DECREF(names);
2179 if (s->v.ImportFrom.module) {
2180 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2181 }
2182 else {
2183 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2184 }
2185 for (i = 0; i < n; i++) {
2186 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2187 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
2190 assert(n == 1);
2191 ADDOP(c, IMPORT_STAR);
2192 return 1;
2193 }
2194
2195 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2196 store_name = alias->name;
2197 if (alias->asname)
2198 store_name = alias->asname;
2199
2200 if (!compiler_nameop(c, store_name, Store)) {
2201 Py_DECREF(names);
2202 return 0;
2203 }
2204 }
2205 /* remove imported module */
2206 ADDOP(c, POP_TOP);
2207 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208}
2209
2210static int
2211compiler_assert(struct compiler *c, stmt_ty s)
2212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 static PyObject *assertion_error = NULL;
2214 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002215
Georg Brandl8334fd92010-12-04 10:26:46 +00002216 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 return 1;
2218 if (assertion_error == NULL) {
2219 assertion_error = PyUnicode_InternFromString("AssertionError");
2220 if (assertion_error == NULL)
2221 return 0;
2222 }
2223 if (s->v.Assert.test->kind == Tuple_kind &&
2224 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2225 const char* msg =
2226 "assertion is always true, perhaps remove parentheses?";
2227 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2228 c->u->u_lineno, NULL, NULL) == -1)
2229 return 0;
2230 }
2231 VISIT(c, expr, s->v.Assert.test);
2232 end = compiler_new_block(c);
2233 if (end == NULL)
2234 return 0;
2235 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2236 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2237 if (s->v.Assert.msg) {
2238 VISIT(c, expr, s->v.Assert.msg);
2239 ADDOP_I(c, CALL_FUNCTION, 1);
2240 }
2241 ADDOP_I(c, RAISE_VARARGS, 1);
2242 compiler_use_next_block(c, end);
2243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244}
2245
2246static int
2247compiler_visit_stmt(struct compiler *c, stmt_ty s)
2248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* Always assign a lineno to the next instruction for a stmt. */
2252 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002253 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 switch (s->kind) {
2257 case FunctionDef_kind:
2258 return compiler_function(c, s);
2259 case ClassDef_kind:
2260 return compiler_class(c, s);
2261 case Return_kind:
2262 if (c->u->u_ste->ste_type != FunctionBlock)
2263 return compiler_error(c, "'return' outside function");
2264 if (s->v.Return.value) {
2265 VISIT(c, expr, s->v.Return.value);
2266 }
2267 else
2268 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2269 ADDOP(c, RETURN_VALUE);
2270 break;
2271 case Delete_kind:
2272 VISIT_SEQ(c, expr, s->v.Delete.targets)
2273 break;
2274 case Assign_kind:
2275 n = asdl_seq_LEN(s->v.Assign.targets);
2276 VISIT(c, expr, s->v.Assign.value);
2277 for (i = 0; i < n; i++) {
2278 if (i < n - 1)
2279 ADDOP(c, DUP_TOP);
2280 VISIT(c, expr,
2281 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2282 }
2283 break;
2284 case AugAssign_kind:
2285 return compiler_augassign(c, s);
2286 case For_kind:
2287 return compiler_for(c, s);
2288 case While_kind:
2289 return compiler_while(c, s);
2290 case If_kind:
2291 return compiler_if(c, s);
2292 case Raise_kind:
2293 n = 0;
2294 if (s->v.Raise.exc) {
2295 VISIT(c, expr, s->v.Raise.exc);
2296 n++;
2297 if (s->v.Raise.cause) {
2298 VISIT(c, expr, s->v.Raise.cause);
2299 n++;
2300 }
2301 }
2302 ADDOP_I(c, RAISE_VARARGS, n);
2303 break;
2304 case TryExcept_kind:
2305 return compiler_try_except(c, s);
2306 case TryFinally_kind:
2307 return compiler_try_finally(c, s);
2308 case Assert_kind:
2309 return compiler_assert(c, s);
2310 case Import_kind:
2311 return compiler_import(c, s);
2312 case ImportFrom_kind:
2313 return compiler_from_import(c, s);
2314 case Global_kind:
2315 case Nonlocal_kind:
2316 break;
2317 case Expr_kind:
2318 if (c->c_interactive && c->c_nestlevel <= 1) {
2319 VISIT(c, expr, s->v.Expr.value);
2320 ADDOP(c, PRINT_EXPR);
2321 }
2322 else if (s->v.Expr.value->kind != Str_kind &&
2323 s->v.Expr.value->kind != Num_kind) {
2324 VISIT(c, expr, s->v.Expr.value);
2325 ADDOP(c, POP_TOP);
2326 }
2327 break;
2328 case Pass_kind:
2329 break;
2330 case Break_kind:
2331 if (!compiler_in_loop(c))
2332 return compiler_error(c, "'break' outside loop");
2333 ADDOP(c, BREAK_LOOP);
2334 break;
2335 case Continue_kind:
2336 return compiler_continue(c);
2337 case With_kind:
2338 return compiler_with(c, s);
2339 }
2340 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341}
2342
2343static int
2344unaryop(unaryop_ty op)
2345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 switch (op) {
2347 case Invert:
2348 return UNARY_INVERT;
2349 case Not:
2350 return UNARY_NOT;
2351 case UAdd:
2352 return UNARY_POSITIVE;
2353 case USub:
2354 return UNARY_NEGATIVE;
2355 default:
2356 PyErr_Format(PyExc_SystemError,
2357 "unary op %d should not be possible", op);
2358 return 0;
2359 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360}
2361
2362static int
2363binop(struct compiler *c, operator_ty op)
2364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 switch (op) {
2366 case Add:
2367 return BINARY_ADD;
2368 case Sub:
2369 return BINARY_SUBTRACT;
2370 case Mult:
2371 return BINARY_MULTIPLY;
2372 case Div:
2373 return BINARY_TRUE_DIVIDE;
2374 case Mod:
2375 return BINARY_MODULO;
2376 case Pow:
2377 return BINARY_POWER;
2378 case LShift:
2379 return BINARY_LSHIFT;
2380 case RShift:
2381 return BINARY_RSHIFT;
2382 case BitOr:
2383 return BINARY_OR;
2384 case BitXor:
2385 return BINARY_XOR;
2386 case BitAnd:
2387 return BINARY_AND;
2388 case FloorDiv:
2389 return BINARY_FLOOR_DIVIDE;
2390 default:
2391 PyErr_Format(PyExc_SystemError,
2392 "binary op %d should not be possible", op);
2393 return 0;
2394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395}
2396
2397static int
2398cmpop(cmpop_ty op)
2399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 switch (op) {
2401 case Eq:
2402 return PyCmp_EQ;
2403 case NotEq:
2404 return PyCmp_NE;
2405 case Lt:
2406 return PyCmp_LT;
2407 case LtE:
2408 return PyCmp_LE;
2409 case Gt:
2410 return PyCmp_GT;
2411 case GtE:
2412 return PyCmp_GE;
2413 case Is:
2414 return PyCmp_IS;
2415 case IsNot:
2416 return PyCmp_IS_NOT;
2417 case In:
2418 return PyCmp_IN;
2419 case NotIn:
2420 return PyCmp_NOT_IN;
2421 default:
2422 return PyCmp_BAD;
2423 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002424}
2425
2426static int
2427inplace_binop(struct compiler *c, operator_ty op)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 switch (op) {
2430 case Add:
2431 return INPLACE_ADD;
2432 case Sub:
2433 return INPLACE_SUBTRACT;
2434 case Mult:
2435 return INPLACE_MULTIPLY;
2436 case Div:
2437 return INPLACE_TRUE_DIVIDE;
2438 case Mod:
2439 return INPLACE_MODULO;
2440 case Pow:
2441 return INPLACE_POWER;
2442 case LShift:
2443 return INPLACE_LSHIFT;
2444 case RShift:
2445 return INPLACE_RSHIFT;
2446 case BitOr:
2447 return INPLACE_OR;
2448 case BitXor:
2449 return INPLACE_XOR;
2450 case BitAnd:
2451 return INPLACE_AND;
2452 case FloorDiv:
2453 return INPLACE_FLOOR_DIVIDE;
2454 default:
2455 PyErr_Format(PyExc_SystemError,
2456 "inplace binary op %d should not be possible", op);
2457 return 0;
2458 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459}
2460
2461static int
2462compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 int op, scope, arg;
2465 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 PyObject *dict = c->u->u_names;
2468 PyObject *mangled;
2469 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 mangled = _Py_Mangle(c->u->u_private, name);
2472 if (!mangled)
2473 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 op = 0;
2476 optype = OP_NAME;
2477 scope = PyST_GetScope(c->u->u_ste, mangled);
2478 switch (scope) {
2479 case FREE:
2480 dict = c->u->u_freevars;
2481 optype = OP_DEREF;
2482 break;
2483 case CELL:
2484 dict = c->u->u_cellvars;
2485 optype = OP_DEREF;
2486 break;
2487 case LOCAL:
2488 if (c->u->u_ste->ste_type == FunctionBlock)
2489 optype = OP_FAST;
2490 break;
2491 case GLOBAL_IMPLICIT:
2492 if (c->u->u_ste->ste_type == FunctionBlock &&
2493 !c->u->u_ste->ste_unoptimized)
2494 optype = OP_GLOBAL;
2495 break;
2496 case GLOBAL_EXPLICIT:
2497 optype = OP_GLOBAL;
2498 break;
2499 default:
2500 /* scope can be 0 */
2501 break;
2502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* XXX Leave assert here, but handle __doc__ and the like better */
2505 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 switch (optype) {
2508 case OP_DEREF:
2509 switch (ctx) {
2510 case Load: op = LOAD_DEREF; break;
2511 case Store: op = STORE_DEREF; break;
2512 case AugLoad:
2513 case AugStore:
2514 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002515 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 case Param:
2517 default:
2518 PyErr_SetString(PyExc_SystemError,
2519 "param invalid for deref variable");
2520 return 0;
2521 }
2522 break;
2523 case OP_FAST:
2524 switch (ctx) {
2525 case Load: op = LOAD_FAST; break;
2526 case Store: op = STORE_FAST; break;
2527 case Del: op = DELETE_FAST; break;
2528 case AugLoad:
2529 case AugStore:
2530 break;
2531 case Param:
2532 default:
2533 PyErr_SetString(PyExc_SystemError,
2534 "param invalid for local variable");
2535 return 0;
2536 }
2537 ADDOP_O(c, op, mangled, varnames);
2538 Py_DECREF(mangled);
2539 return 1;
2540 case OP_GLOBAL:
2541 switch (ctx) {
2542 case Load: op = LOAD_GLOBAL; break;
2543 case Store: op = STORE_GLOBAL; break;
2544 case Del: op = DELETE_GLOBAL; break;
2545 case AugLoad:
2546 case AugStore:
2547 break;
2548 case Param:
2549 default:
2550 PyErr_SetString(PyExc_SystemError,
2551 "param invalid for global variable");
2552 return 0;
2553 }
2554 break;
2555 case OP_NAME:
2556 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002557 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 case Store: op = STORE_NAME; break;
2559 case Del: op = DELETE_NAME; break;
2560 case AugLoad:
2561 case AugStore:
2562 break;
2563 case Param:
2564 default:
2565 PyErr_SetString(PyExc_SystemError,
2566 "param invalid for name variable");
2567 return 0;
2568 }
2569 break;
2570 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 assert(op);
2573 arg = compiler_add_o(c, dict, mangled);
2574 Py_DECREF(mangled);
2575 if (arg < 0)
2576 return 0;
2577 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578}
2579
2580static int
2581compiler_boolop(struct compiler *c, expr_ty e)
2582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 basicblock *end;
2584 int jumpi, i, n;
2585 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 assert(e->kind == BoolOp_kind);
2588 if (e->v.BoolOp.op == And)
2589 jumpi = JUMP_IF_FALSE_OR_POP;
2590 else
2591 jumpi = JUMP_IF_TRUE_OR_POP;
2592 end = compiler_new_block(c);
2593 if (end == NULL)
2594 return 0;
2595 s = e->v.BoolOp.values;
2596 n = asdl_seq_LEN(s) - 1;
2597 assert(n >= 0);
2598 for (i = 0; i < n; ++i) {
2599 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2600 ADDOP_JABS(c, jumpi, end);
2601 }
2602 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2603 compiler_use_next_block(c, end);
2604 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002605}
2606
2607static int
2608compiler_list(struct compiler *c, expr_ty e)
2609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 int n = asdl_seq_LEN(e->v.List.elts);
2611 if (e->v.List.ctx == Store) {
2612 int i, seen_star = 0;
2613 for (i = 0; i < n; i++) {
2614 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2615 if (elt->kind == Starred_kind && !seen_star) {
2616 if ((i >= (1 << 8)) ||
2617 (n-i-1 >= (INT_MAX >> 8)))
2618 return compiler_error(c,
2619 "too many expressions in "
2620 "star-unpacking assignment");
2621 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2622 seen_star = 1;
2623 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2624 } else if (elt->kind == Starred_kind) {
2625 return compiler_error(c,
2626 "two starred expressions in assignment");
2627 }
2628 }
2629 if (!seen_star) {
2630 ADDOP_I(c, UNPACK_SEQUENCE, n);
2631 }
2632 }
2633 VISIT_SEQ(c, expr, e->v.List.elts);
2634 if (e->v.List.ctx == Load) {
2635 ADDOP_I(c, BUILD_LIST, n);
2636 }
2637 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638}
2639
2640static int
2641compiler_tuple(struct compiler *c, expr_ty e)
2642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 int n = asdl_seq_LEN(e->v.Tuple.elts);
2644 if (e->v.Tuple.ctx == Store) {
2645 int i, seen_star = 0;
2646 for (i = 0; i < n; i++) {
2647 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2648 if (elt->kind == Starred_kind && !seen_star) {
2649 if ((i >= (1 << 8)) ||
2650 (n-i-1 >= (INT_MAX >> 8)))
2651 return compiler_error(c,
2652 "too many expressions in "
2653 "star-unpacking assignment");
2654 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2655 seen_star = 1;
2656 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2657 } else if (elt->kind == Starred_kind) {
2658 return compiler_error(c,
2659 "two starred expressions in assignment");
2660 }
2661 }
2662 if (!seen_star) {
2663 ADDOP_I(c, UNPACK_SEQUENCE, n);
2664 }
2665 }
2666 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2667 if (e->v.Tuple.ctx == Load) {
2668 ADDOP_I(c, BUILD_TUPLE, n);
2669 }
2670 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671}
2672
2673static int
2674compiler_compare(struct compiler *c, expr_ty e)
2675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 int i, n;
2677 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2680 VISIT(c, expr, e->v.Compare.left);
2681 n = asdl_seq_LEN(e->v.Compare.ops);
2682 assert(n > 0);
2683 if (n > 1) {
2684 cleanup = compiler_new_block(c);
2685 if (cleanup == NULL)
2686 return 0;
2687 VISIT(c, expr,
2688 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2689 }
2690 for (i = 1; i < n; i++) {
2691 ADDOP(c, DUP_TOP);
2692 ADDOP(c, ROT_THREE);
2693 ADDOP_I(c, COMPARE_OP,
2694 cmpop((cmpop_ty)(asdl_seq_GET(
2695 e->v.Compare.ops, i - 1))));
2696 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2697 NEXT_BLOCK(c);
2698 if (i < (n - 1))
2699 VISIT(c, expr,
2700 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2701 }
2702 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2703 ADDOP_I(c, COMPARE_OP,
2704 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2705 if (n > 1) {
2706 basicblock *end = compiler_new_block(c);
2707 if (end == NULL)
2708 return 0;
2709 ADDOP_JREL(c, JUMP_FORWARD, end);
2710 compiler_use_next_block(c, cleanup);
2711 ADDOP(c, ROT_TWO);
2712 ADDOP(c, POP_TOP);
2713 compiler_use_next_block(c, end);
2714 }
2715 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716}
2717
2718static int
2719compiler_call(struct compiler *c, expr_ty e)
2720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 VISIT(c, expr, e->v.Call.func);
2722 return compiler_call_helper(c, 0,
2723 e->v.Call.args,
2724 e->v.Call.keywords,
2725 e->v.Call.starargs,
2726 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002727}
2728
2729/* shared code between compiler_call and compiler_class */
2730static int
2731compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 int n, /* Args already pushed */
2733 asdl_seq *args,
2734 asdl_seq *keywords,
2735 expr_ty starargs,
2736 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 n += asdl_seq_LEN(args);
2741 VISIT_SEQ(c, expr, args);
2742 if (keywords) {
2743 VISIT_SEQ(c, keyword, keywords);
2744 n |= asdl_seq_LEN(keywords) << 8;
2745 }
2746 if (starargs) {
2747 VISIT(c, expr, starargs);
2748 code |= 1;
2749 }
2750 if (kwargs) {
2751 VISIT(c, expr, kwargs);
2752 code |= 2;
2753 }
2754 switch (code) {
2755 case 0:
2756 ADDOP_I(c, CALL_FUNCTION, n);
2757 break;
2758 case 1:
2759 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2760 break;
2761 case 2:
2762 ADDOP_I(c, CALL_FUNCTION_KW, n);
2763 break;
2764 case 3:
2765 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2766 break;
2767 }
2768 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769}
2770
Nick Coghlan650f0d02007-04-15 12:05:43 +00002771
2772/* List and set comprehensions and generator expressions work by creating a
2773 nested function to perform the actual iteration. This means that the
2774 iteration variables don't leak into the current scope.
2775 The defined function is called immediately following its definition, with the
2776 result of that call being the result of the expression.
2777 The LC/SC version returns the populated container, while the GE version is
2778 flagged in symtable.c as a generator, so it returns the generator object
2779 when the function is called.
2780 This code *knows* that the loop cannot contain break, continue, or return,
2781 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2782
2783 Possible cleanups:
2784 - iterate over the generator sequence instead of using recursion
2785*/
2786
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788compiler_comprehension_generator(struct compiler *c,
2789 asdl_seq *generators, int gen_index,
2790 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 /* generate code for the iterator, then each of the ifs,
2793 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 comprehension_ty gen;
2796 basicblock *start, *anchor, *skip, *if_cleanup;
2797 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 start = compiler_new_block(c);
2800 skip = compiler_new_block(c);
2801 if_cleanup = compiler_new_block(c);
2802 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2805 anchor == NULL)
2806 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 if (gen_index == 0) {
2811 /* Receive outermost iter as an implicit argument */
2812 c->u->u_argcount = 1;
2813 ADDOP_I(c, LOAD_FAST, 0);
2814 }
2815 else {
2816 /* Sub-iter - calculate on the fly */
2817 VISIT(c, expr, gen->iter);
2818 ADDOP(c, GET_ITER);
2819 }
2820 compiler_use_next_block(c, start);
2821 ADDOP_JREL(c, FOR_ITER, anchor);
2822 NEXT_BLOCK(c);
2823 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* XXX this needs to be cleaned up...a lot! */
2826 n = asdl_seq_LEN(gen->ifs);
2827 for (i = 0; i < n; i++) {
2828 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2829 VISIT(c, expr, e);
2830 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2831 NEXT_BLOCK(c);
2832 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 if (++gen_index < asdl_seq_LEN(generators))
2835 if (!compiler_comprehension_generator(c,
2836 generators, gen_index,
2837 elt, val, type))
2838 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 /* only append after the last for generator */
2841 if (gen_index >= asdl_seq_LEN(generators)) {
2842 /* comprehension specific code */
2843 switch (type) {
2844 case COMP_GENEXP:
2845 VISIT(c, expr, elt);
2846 ADDOP(c, YIELD_VALUE);
2847 ADDOP(c, POP_TOP);
2848 break;
2849 case COMP_LISTCOMP:
2850 VISIT(c, expr, elt);
2851 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2852 break;
2853 case COMP_SETCOMP:
2854 VISIT(c, expr, elt);
2855 ADDOP_I(c, SET_ADD, gen_index + 1);
2856 break;
2857 case COMP_DICTCOMP:
2858 /* With 'd[k] = v', v is evaluated before k, so we do
2859 the same. */
2860 VISIT(c, expr, val);
2861 VISIT(c, expr, elt);
2862 ADDOP_I(c, MAP_ADD, gen_index + 1);
2863 break;
2864 default:
2865 return 0;
2866 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 compiler_use_next_block(c, skip);
2869 }
2870 compiler_use_next_block(c, if_cleanup);
2871 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2872 compiler_use_next_block(c, anchor);
2873
2874 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875}
2876
2877static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002878compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 PyCodeObject *co = NULL;
2882 expr_ty outermost_iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 outermost_iter = ((comprehension_ty)
2885 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2888 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 if (type != COMP_GENEXP) {
2891 int op;
2892 switch (type) {
2893 case COMP_LISTCOMP:
2894 op = BUILD_LIST;
2895 break;
2896 case COMP_SETCOMP:
2897 op = BUILD_SET;
2898 break;
2899 case COMP_DICTCOMP:
2900 op = BUILD_MAP;
2901 break;
2902 default:
2903 PyErr_Format(PyExc_SystemError,
2904 "unknown comprehension type %d", type);
2905 goto error_in_scope;
2906 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 ADDOP_I(c, op, 0);
2909 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 if (!compiler_comprehension_generator(c, generators, 0, elt,
2912 val, type))
2913 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 if (type != COMP_GENEXP) {
2916 ADDOP(c, RETURN_VALUE);
2917 }
2918
2919 co = assemble(c, 1);
2920 compiler_exit_scope(c);
2921 if (co == NULL)
2922 goto error;
2923
2924 if (!compiler_make_closure(c, co, 0))
2925 goto error;
2926 Py_DECREF(co);
2927
2928 VISIT(c, expr, outermost_iter);
2929 ADDOP(c, GET_ITER);
2930 ADDOP_I(c, CALL_FUNCTION, 1);
2931 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002932error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002934error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 Py_XDECREF(co);
2936 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002937}
2938
2939static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940compiler_genexp(struct compiler *c, expr_ty e)
2941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 static identifier name;
2943 if (!name) {
2944 name = PyUnicode_FromString("<genexpr>");
2945 if (!name)
2946 return 0;
2947 }
2948 assert(e->kind == GeneratorExp_kind);
2949 return compiler_comprehension(c, e, COMP_GENEXP, name,
2950 e->v.GeneratorExp.generators,
2951 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952}
2953
2954static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002955compiler_listcomp(struct compiler *c, expr_ty e)
2956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 static identifier name;
2958 if (!name) {
2959 name = PyUnicode_FromString("<listcomp>");
2960 if (!name)
2961 return 0;
2962 }
2963 assert(e->kind == ListComp_kind);
2964 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2965 e->v.ListComp.generators,
2966 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002967}
2968
2969static int
2970compiler_setcomp(struct compiler *c, expr_ty e)
2971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 static identifier name;
2973 if (!name) {
2974 name = PyUnicode_FromString("<setcomp>");
2975 if (!name)
2976 return 0;
2977 }
2978 assert(e->kind == SetComp_kind);
2979 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2980 e->v.SetComp.generators,
2981 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002982}
2983
2984
2985static int
2986compiler_dictcomp(struct compiler *c, expr_ty e)
2987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 static identifier name;
2989 if (!name) {
2990 name = PyUnicode_FromString("<dictcomp>");
2991 if (!name)
2992 return 0;
2993 }
2994 assert(e->kind == DictComp_kind);
2995 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2996 e->v.DictComp.generators,
2997 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002998}
2999
3000
3001static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003002compiler_visit_keyword(struct compiler *c, keyword_ty k)
3003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3005 VISIT(c, expr, k->value);
3006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007}
3008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010 whether they are true or false.
3011
3012 Return values: 1 for true, 0 for false, -1 for non-constant.
3013 */
3014
3015static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003016expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 char *id;
3019 switch (e->kind) {
3020 case Ellipsis_kind:
3021 return 1;
3022 case Num_kind:
3023 return PyObject_IsTrue(e->v.Num.n);
3024 case Str_kind:
3025 return PyObject_IsTrue(e->v.Str.s);
3026 case Name_kind:
3027 /* optimize away names that can't be reassigned */
3028 id = PyBytes_AS_STRING(
3029 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
3030 if (strcmp(id, "True") == 0) return 1;
3031 if (strcmp(id, "False") == 0) return 0;
3032 if (strcmp(id, "None") == 0) return 0;
3033 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003034 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 /* fall through */
3036 default:
3037 return -1;
3038 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039}
3040
Guido van Rossumc2e20742006-02-27 22:32:47 +00003041/*
3042 Implements the with statement from PEP 343.
3043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003045
3046 with EXPR as VAR:
3047 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048
Guido van Rossumc2e20742006-02-27 22:32:47 +00003049 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050
Thomas Wouters477c8d52006-05-27 19:21:47 +00003051 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003052 exit = context.__exit__ # not calling it
3053 value = context.__enter__()
3054 try:
3055 VAR = value # if VAR present in the syntax
3056 BLOCK
3057 finally:
3058 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003060 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003062 exit(*exc)
3063 */
3064static int
3065compiler_with(struct compiler *c, stmt_ty s)
3066{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003067 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003068
3069 assert(s->kind == With_kind);
3070
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 block = compiler_new_block(c);
3072 finally = compiler_new_block(c);
3073 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003074 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075
Thomas Wouters477c8d52006-05-27 19:21:47 +00003076 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003077 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003078 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003080 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 compiler_use_next_block(c, block);
3082 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003083 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003084 }
3085
3086 if (s->v.With.optional_vars) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003087 VISIT(c, expr, s->v.With.optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003088 }
3089 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003091 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003092 }
3093
3094 /* BLOCK code */
3095 VISIT_SEQ(c, stmt, s->v.With.body);
3096
3097 /* End of try block; start the finally block */
3098 ADDOP(c, POP_BLOCK);
3099 compiler_pop_fblock(c, FINALLY_TRY, block);
3100
3101 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3102 compiler_use_next_block(c, finally);
3103 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003104 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003105
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003106 /* Finally block starts; context.__exit__ is on the stack under
3107 the exception or return information. Just issue our magic
3108 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003109 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003110
3111 /* Finally block ends. */
3112 ADDOP(c, END_FINALLY);
3113 compiler_pop_fblock(c, FINALLY_END, finally);
3114 return 1;
3115}
3116
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117static int
3118compiler_visit_expr(struct compiler *c, expr_ty e)
3119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 /* If expr e has a different line number than the last expr/stmt,
3123 set a new line number for the next instruction.
3124 */
3125 if (e->lineno > c->u->u_lineno) {
3126 c->u->u_lineno = e->lineno;
3127 c->u->u_lineno_set = 0;
3128 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003129 /* Updating the column offset is always harmless. */
3130 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 switch (e->kind) {
3132 case BoolOp_kind:
3133 return compiler_boolop(c, e);
3134 case BinOp_kind:
3135 VISIT(c, expr, e->v.BinOp.left);
3136 VISIT(c, expr, e->v.BinOp.right);
3137 ADDOP(c, binop(c, e->v.BinOp.op));
3138 break;
3139 case UnaryOp_kind:
3140 VISIT(c, expr, e->v.UnaryOp.operand);
3141 ADDOP(c, unaryop(e->v.UnaryOp.op));
3142 break;
3143 case Lambda_kind:
3144 return compiler_lambda(c, e);
3145 case IfExp_kind:
3146 return compiler_ifexp(c, e);
3147 case Dict_kind:
3148 n = asdl_seq_LEN(e->v.Dict.values);
3149 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3150 for (i = 0; i < n; i++) {
3151 VISIT(c, expr,
3152 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3153 VISIT(c, expr,
3154 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3155 ADDOP(c, STORE_MAP);
3156 }
3157 break;
3158 case Set_kind:
3159 n = asdl_seq_LEN(e->v.Set.elts);
3160 VISIT_SEQ(c, expr, e->v.Set.elts);
3161 ADDOP_I(c, BUILD_SET, n);
3162 break;
3163 case GeneratorExp_kind:
3164 return compiler_genexp(c, e);
3165 case ListComp_kind:
3166 return compiler_listcomp(c, e);
3167 case SetComp_kind:
3168 return compiler_setcomp(c, e);
3169 case DictComp_kind:
3170 return compiler_dictcomp(c, e);
3171 case Yield_kind:
3172 if (c->u->u_ste->ste_type != FunctionBlock)
3173 return compiler_error(c, "'yield' outside function");
3174 if (e->v.Yield.value) {
3175 VISIT(c, expr, e->v.Yield.value);
3176 }
3177 else {
3178 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3179 }
3180 ADDOP(c, YIELD_VALUE);
3181 break;
3182 case Compare_kind:
3183 return compiler_compare(c, e);
3184 case Call_kind:
3185 return compiler_call(c, e);
3186 case Num_kind:
3187 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3188 break;
3189 case Str_kind:
3190 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3191 break;
3192 case Bytes_kind:
3193 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3194 break;
3195 case Ellipsis_kind:
3196 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3197 break;
3198 /* The following exprs can be assignment targets. */
3199 case Attribute_kind:
3200 if (e->v.Attribute.ctx != AugStore)
3201 VISIT(c, expr, e->v.Attribute.value);
3202 switch (e->v.Attribute.ctx) {
3203 case AugLoad:
3204 ADDOP(c, DUP_TOP);
3205 /* Fall through to load */
3206 case Load:
3207 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3208 break;
3209 case AugStore:
3210 ADDOP(c, ROT_TWO);
3211 /* Fall through to save */
3212 case Store:
3213 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3214 break;
3215 case Del:
3216 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3217 break;
3218 case Param:
3219 default:
3220 PyErr_SetString(PyExc_SystemError,
3221 "param invalid in attribute expression");
3222 return 0;
3223 }
3224 break;
3225 case Subscript_kind:
3226 switch (e->v.Subscript.ctx) {
3227 case AugLoad:
3228 VISIT(c, expr, e->v.Subscript.value);
3229 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3230 break;
3231 case Load:
3232 VISIT(c, expr, e->v.Subscript.value);
3233 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3234 break;
3235 case AugStore:
3236 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3237 break;
3238 case Store:
3239 VISIT(c, expr, e->v.Subscript.value);
3240 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3241 break;
3242 case Del:
3243 VISIT(c, expr, e->v.Subscript.value);
3244 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3245 break;
3246 case Param:
3247 default:
3248 PyErr_SetString(PyExc_SystemError,
3249 "param invalid in subscript expression");
3250 return 0;
3251 }
3252 break;
3253 case Starred_kind:
3254 switch (e->v.Starred.ctx) {
3255 case Store:
3256 /* In all legitimate cases, the Starred node was already replaced
3257 * by compiler_list/compiler_tuple. XXX: is that okay? */
3258 return compiler_error(c,
3259 "starred assignment target must be in a list or tuple");
3260 default:
3261 return compiler_error(c,
3262 "can use starred expression only as assignment target");
3263 }
3264 break;
3265 case Name_kind:
3266 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3267 /* child nodes of List and Tuple will have expr_context set */
3268 case List_kind:
3269 return compiler_list(c, e);
3270 case Tuple_kind:
3271 return compiler_tuple(c, e);
3272 }
3273 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274}
3275
3276static int
3277compiler_augassign(struct compiler *c, stmt_ty s)
3278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 expr_ty e = s->v.AugAssign.target;
3280 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 switch (e->kind) {
3285 case Attribute_kind:
3286 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3287 AugLoad, e->lineno, e->col_offset, c->c_arena);
3288 if (auge == NULL)
3289 return 0;
3290 VISIT(c, expr, auge);
3291 VISIT(c, expr, s->v.AugAssign.value);
3292 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3293 auge->v.Attribute.ctx = AugStore;
3294 VISIT(c, expr, auge);
3295 break;
3296 case Subscript_kind:
3297 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3298 AugLoad, e->lineno, e->col_offset, c->c_arena);
3299 if (auge == NULL)
3300 return 0;
3301 VISIT(c, expr, auge);
3302 VISIT(c, expr, s->v.AugAssign.value);
3303 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3304 auge->v.Subscript.ctx = AugStore;
3305 VISIT(c, expr, auge);
3306 break;
3307 case Name_kind:
3308 if (!compiler_nameop(c, e->v.Name.id, Load))
3309 return 0;
3310 VISIT(c, expr, s->v.AugAssign.value);
3311 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3312 return compiler_nameop(c, e->v.Name.id, Store);
3313 default:
3314 PyErr_Format(PyExc_SystemError,
3315 "invalid node type (%d) for augmented assignment",
3316 e->kind);
3317 return 0;
3318 }
3319 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003320}
3321
3322static int
3323compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 struct fblockinfo *f;
3326 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3327 PyErr_SetString(PyExc_SystemError,
3328 "too many statically nested blocks");
3329 return 0;
3330 }
3331 f = &c->u->u_fblock[c->u->u_nfblocks++];
3332 f->fb_type = t;
3333 f->fb_block = b;
3334 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335}
3336
3337static void
3338compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 struct compiler_unit *u = c->u;
3341 assert(u->u_nfblocks > 0);
3342 u->u_nfblocks--;
3343 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3344 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345}
3346
Thomas Wouters89f507f2006-12-13 04:49:30 +00003347static int
3348compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 int i;
3350 struct compiler_unit *u = c->u;
3351 for (i = 0; i < u->u_nfblocks; ++i) {
3352 if (u->u_fblock[i].fb_type == LOOP)
3353 return 1;
3354 }
3355 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003356}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357/* Raises a SyntaxError and returns 0.
3358 If something goes wrong, a different exception may be raised.
3359*/
3360
3361static int
3362compiler_error(struct compiler *c, const char *errstr)
3363{
Victor Stinnerc0499822010-10-17 19:16:33 +00003364 PyObject *loc, *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3368 if (!loc) {
3369 Py_INCREF(Py_None);
3370 loc = Py_None;
3371 }
Victor Stinnerc0499822010-10-17 19:16:33 +00003372 if (c->c_filename != NULL) {
3373 filename = PyUnicode_DecodeFSDefault(c->c_filename);
3374 if (!filename)
3375 goto exit;
3376 }
3377 else {
3378 Py_INCREF(Py_None);
3379 filename = Py_None;
3380 }
3381 u = Py_BuildValue("(NiiO)", filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003382 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 if (!u)
3384 goto exit;
3385 v = Py_BuildValue("(zO)", errstr, u);
3386 if (!v)
3387 goto exit;
3388 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003389 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 Py_DECREF(loc);
3391 Py_XDECREF(u);
3392 Py_XDECREF(v);
3393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394}
3395
3396static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397compiler_handle_subscr(struct compiler *c, const char *kind,
3398 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 /* XXX this code is duplicated */
3403 switch (ctx) {
3404 case AugLoad: /* fall through to Load */
3405 case Load: op = BINARY_SUBSCR; break;
3406 case AugStore:/* fall through to Store */
3407 case Store: op = STORE_SUBSCR; break;
3408 case Del: op = DELETE_SUBSCR; break;
3409 case Param:
3410 PyErr_Format(PyExc_SystemError,
3411 "invalid %s kind %d in subscript\n",
3412 kind, ctx);
3413 return 0;
3414 }
3415 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003416 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 }
3418 else if (ctx == AugStore) {
3419 ADDOP(c, ROT_THREE);
3420 }
3421 ADDOP(c, op);
3422 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423}
3424
3425static int
3426compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 int n = 2;
3429 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 /* only handles the cases where BUILD_SLICE is emitted */
3432 if (s->v.Slice.lower) {
3433 VISIT(c, expr, s->v.Slice.lower);
3434 }
3435 else {
3436 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3437 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 if (s->v.Slice.upper) {
3440 VISIT(c, expr, s->v.Slice.upper);
3441 }
3442 else {
3443 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3444 }
3445
3446 if (s->v.Slice.step) {
3447 n++;
3448 VISIT(c, expr, s->v.Slice.step);
3449 }
3450 ADDOP_I(c, BUILD_SLICE, n);
3451 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452}
3453
3454static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3456 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 switch (s->kind) {
3459 case Slice_kind:
3460 return compiler_slice(c, s, ctx);
3461 case Index_kind:
3462 VISIT(c, expr, s->v.Index.value);
3463 break;
3464 case ExtSlice_kind:
3465 default:
3466 PyErr_SetString(PyExc_SystemError,
3467 "extended slice invalid in nested slice");
3468 return 0;
3469 }
3470 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003471}
3472
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473static int
3474compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 char * kindname = NULL;
3477 switch (s->kind) {
3478 case Index_kind:
3479 kindname = "index";
3480 if (ctx != AugStore) {
3481 VISIT(c, expr, s->v.Index.value);
3482 }
3483 break;
3484 case Slice_kind:
3485 kindname = "slice";
3486 if (ctx != AugStore) {
3487 if (!compiler_slice(c, s, ctx))
3488 return 0;
3489 }
3490 break;
3491 case ExtSlice_kind:
3492 kindname = "extended slice";
3493 if (ctx != AugStore) {
3494 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3495 for (i = 0; i < n; i++) {
3496 slice_ty sub = (slice_ty)asdl_seq_GET(
3497 s->v.ExtSlice.dims, i);
3498 if (!compiler_visit_nested_slice(c, sub, ctx))
3499 return 0;
3500 }
3501 ADDOP_I(c, BUILD_TUPLE, n);
3502 }
3503 break;
3504 default:
3505 PyErr_Format(PyExc_SystemError,
3506 "invalid subscript kind %d", s->kind);
3507 return 0;
3508 }
3509 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510}
3511
Thomas Wouters89f507f2006-12-13 04:49:30 +00003512/* End of the compiler section, beginning of the assembler section */
3513
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514/* do depth-first search of basic block graph, starting with block.
3515 post records the block indices in post-order.
3516
3517 XXX must handle implicit jumps from one block to next
3518*/
3519
Thomas Wouters89f507f2006-12-13 04:49:30 +00003520struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 PyObject *a_bytecode; /* string containing bytecode */
3522 int a_offset; /* offset into bytecode */
3523 int a_nblocks; /* number of reachable blocks */
3524 basicblock **a_postorder; /* list of blocks in dfs postorder */
3525 PyObject *a_lnotab; /* string containing lnotab */
3526 int a_lnotab_off; /* offset into lnotab */
3527 int a_lineno; /* last lineno of emitted instruction */
3528 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003529};
3530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531static void
3532dfs(struct compiler *c, basicblock *b, struct assembler *a)
3533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 int i;
3535 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 if (b->b_seen)
3538 return;
3539 b->b_seen = 1;
3540 if (b->b_next != NULL)
3541 dfs(c, b->b_next, a);
3542 for (i = 0; i < b->b_iused; i++) {
3543 instr = &b->b_instr[i];
3544 if (instr->i_jrel || instr->i_jabs)
3545 dfs(c, instr->i_target, a);
3546 }
3547 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548}
3549
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003550static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 int i, target_depth;
3554 struct instr *instr;
3555 if (b->b_seen || b->b_startdepth >= depth)
3556 return maxdepth;
3557 b->b_seen = 1;
3558 b->b_startdepth = depth;
3559 for (i = 0; i < b->b_iused; i++) {
3560 instr = &b->b_instr[i];
3561 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3562 if (depth > maxdepth)
3563 maxdepth = depth;
3564 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3565 if (instr->i_jrel || instr->i_jabs) {
3566 target_depth = depth;
3567 if (instr->i_opcode == FOR_ITER) {
3568 target_depth = depth-2;
3569 } else if (instr->i_opcode == SETUP_FINALLY ||
3570 instr->i_opcode == SETUP_EXCEPT) {
3571 target_depth = depth+3;
3572 if (target_depth > maxdepth)
3573 maxdepth = target_depth;
3574 }
3575 maxdepth = stackdepth_walk(c, instr->i_target,
3576 target_depth, maxdepth);
3577 if (instr->i_opcode == JUMP_ABSOLUTE ||
3578 instr->i_opcode == JUMP_FORWARD) {
3579 goto out; /* remaining code is dead */
3580 }
3581 }
3582 }
3583 if (b->b_next)
3584 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 b->b_seen = 0;
3587 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588}
3589
3590/* Find the flow path that needs the largest stack. We assume that
3591 * cycles in the flow graph have no net effect on the stack depth.
3592 */
3593static int
3594stackdepth(struct compiler *c)
3595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 basicblock *b, *entryblock;
3597 entryblock = NULL;
3598 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3599 b->b_seen = 0;
3600 b->b_startdepth = INT_MIN;
3601 entryblock = b;
3602 }
3603 if (!entryblock)
3604 return 0;
3605 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606}
3607
3608static int
3609assemble_init(struct assembler *a, int nblocks, int firstlineno)
3610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 memset(a, 0, sizeof(struct assembler));
3612 a->a_lineno = firstlineno;
3613 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3614 if (!a->a_bytecode)
3615 return 0;
3616 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3617 if (!a->a_lnotab)
3618 return 0;
3619 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3620 PyErr_NoMemory();
3621 return 0;
3622 }
3623 a->a_postorder = (basicblock **)PyObject_Malloc(
3624 sizeof(basicblock *) * nblocks);
3625 if (!a->a_postorder) {
3626 PyErr_NoMemory();
3627 return 0;
3628 }
3629 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
3632static void
3633assemble_free(struct assembler *a)
3634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 Py_XDECREF(a->a_bytecode);
3636 Py_XDECREF(a->a_lnotab);
3637 if (a->a_postorder)
3638 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639}
3640
3641/* Return the size of a basic block in bytes. */
3642
3643static int
3644instrsize(struct instr *instr)
3645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 if (!instr->i_hasarg)
3647 return 1; /* 1 byte for the opcode*/
3648 if (instr->i_oparg > 0xffff)
3649 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3650 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651}
3652
3653static int
3654blocksize(basicblock *b)
3655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 int i;
3657 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 for (i = 0; i < b->b_iused; i++)
3660 size += instrsize(&b->b_instr[i]);
3661 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662}
3663
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003664/* Appends a pair to the end of the line number table, a_lnotab, representing
3665 the instruction's bytecode offset and line number. See
3666 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003667
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003668static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 int d_bytecode, d_lineno;
3672 int len;
3673 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 d_bytecode = a->a_offset - a->a_lineno_off;
3676 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 assert(d_bytecode >= 0);
3679 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 if(d_bytecode == 0 && d_lineno == 0)
3682 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 if (d_bytecode > 255) {
3685 int j, nbytes, ncodes = d_bytecode / 255;
3686 nbytes = a->a_lnotab_off + 2 * ncodes;
3687 len = PyBytes_GET_SIZE(a->a_lnotab);
3688 if (nbytes >= len) {
3689 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3690 len = nbytes;
3691 else if (len <= INT_MAX / 2)
3692 len *= 2;
3693 else {
3694 PyErr_NoMemory();
3695 return 0;
3696 }
3697 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3698 return 0;
3699 }
3700 lnotab = (unsigned char *)
3701 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3702 for (j = 0; j < ncodes; j++) {
3703 *lnotab++ = 255;
3704 *lnotab++ = 0;
3705 }
3706 d_bytecode -= ncodes * 255;
3707 a->a_lnotab_off += ncodes * 2;
3708 }
3709 assert(d_bytecode <= 255);
3710 if (d_lineno > 255) {
3711 int j, nbytes, ncodes = d_lineno / 255;
3712 nbytes = a->a_lnotab_off + 2 * ncodes;
3713 len = PyBytes_GET_SIZE(a->a_lnotab);
3714 if (nbytes >= len) {
3715 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3716 len = nbytes;
3717 else if (len <= INT_MAX / 2)
3718 len *= 2;
3719 else {
3720 PyErr_NoMemory();
3721 return 0;
3722 }
3723 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3724 return 0;
3725 }
3726 lnotab = (unsigned char *)
3727 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3728 *lnotab++ = d_bytecode;
3729 *lnotab++ = 255;
3730 d_bytecode = 0;
3731 for (j = 1; j < ncodes; j++) {
3732 *lnotab++ = 0;
3733 *lnotab++ = 255;
3734 }
3735 d_lineno -= ncodes * 255;
3736 a->a_lnotab_off += ncodes * 2;
3737 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 len = PyBytes_GET_SIZE(a->a_lnotab);
3740 if (a->a_lnotab_off + 2 >= len) {
3741 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3742 return 0;
3743 }
3744 lnotab = (unsigned char *)
3745 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 a->a_lnotab_off += 2;
3748 if (d_bytecode) {
3749 *lnotab++ = d_bytecode;
3750 *lnotab++ = d_lineno;
3751 }
3752 else { /* First line of a block; def stmt, etc. */
3753 *lnotab++ = 0;
3754 *lnotab++ = d_lineno;
3755 }
3756 a->a_lineno = i->i_lineno;
3757 a->a_lineno_off = a->a_offset;
3758 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003759}
3760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761/* assemble_emit()
3762 Extend the bytecode with a new instruction.
3763 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003764*/
3765
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003766static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 int size, arg = 0, ext = 0;
3770 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3771 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 size = instrsize(i);
3774 if (i->i_hasarg) {
3775 arg = i->i_oparg;
3776 ext = arg >> 16;
3777 }
3778 if (i->i_lineno && !assemble_lnotab(a, i))
3779 return 0;
3780 if (a->a_offset + size >= len) {
3781 if (len > PY_SSIZE_T_MAX / 2)
3782 return 0;
3783 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3784 return 0;
3785 }
3786 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3787 a->a_offset += size;
3788 if (size == 6) {
3789 assert(i->i_hasarg);
3790 *code++ = (char)EXTENDED_ARG;
3791 *code++ = ext & 0xff;
3792 *code++ = ext >> 8;
3793 arg &= 0xffff;
3794 }
3795 *code++ = i->i_opcode;
3796 if (i->i_hasarg) {
3797 assert(size == 3 || size == 6);
3798 *code++ = arg & 0xff;
3799 *code++ = arg >> 8;
3800 }
3801 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003802}
3803
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003804static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 basicblock *b;
3808 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3809 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 /* Compute the size of each block and fixup jump args.
3812 Replace block pointer with position in bytecode. */
3813 do {
3814 totsize = 0;
3815 for (i = a->a_nblocks - 1; i >= 0; i--) {
3816 b = a->a_postorder[i];
3817 bsize = blocksize(b);
3818 b->b_offset = totsize;
3819 totsize += bsize;
3820 }
3821 last_extended_arg_count = extended_arg_count;
3822 extended_arg_count = 0;
3823 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3824 bsize = b->b_offset;
3825 for (i = 0; i < b->b_iused; i++) {
3826 struct instr *instr = &b->b_instr[i];
3827 /* Relative jumps are computed relative to
3828 the instruction pointer after fetching
3829 the jump instruction.
3830 */
3831 bsize += instrsize(instr);
3832 if (instr->i_jabs)
3833 instr->i_oparg = instr->i_target->b_offset;
3834 else if (instr->i_jrel) {
3835 int delta = instr->i_target->b_offset - bsize;
3836 instr->i_oparg = delta;
3837 }
3838 else
3839 continue;
3840 if (instr->i_oparg > 0xffff)
3841 extended_arg_count++;
3842 }
3843 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 /* XXX: This is an awful hack that could hurt performance, but
3846 on the bright side it should work until we come up
3847 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 The issue is that in the first loop blocksize() is called
3850 which calls instrsize() which requires i_oparg be set
3851 appropriately. There is a bootstrap problem because
3852 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 So we loop until we stop seeing new EXTENDED_ARGs.
3855 The only EXTENDED_ARGs that could be popping up are
3856 ones in jump instructions. So this should converge
3857 fairly quickly.
3858 */
3859 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003860}
3861
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003862static PyObject *
3863dict_keys_inorder(PyObject *dict, int offset)
3864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 PyObject *tuple, *k, *v;
3866 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 tuple = PyTuple_New(size);
3869 if (tuple == NULL)
3870 return NULL;
3871 while (PyDict_Next(dict, &pos, &k, &v)) {
3872 i = PyLong_AS_LONG(v);
3873 /* The keys of the dictionary are tuples. (see compiler_add_o)
3874 The object we want is always first, though. */
3875 k = PyTuple_GET_ITEM(k, 0);
3876 Py_INCREF(k);
3877 assert((i - offset) < size);
3878 assert((i - offset) >= 0);
3879 PyTuple_SET_ITEM(tuple, i - offset, k);
3880 }
3881 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003882}
3883
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003884static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 PySTEntryObject *ste = c->u->u_ste;
3888 int flags = 0, n;
3889 if (ste->ste_type != ModuleBlock)
3890 flags |= CO_NEWLOCALS;
3891 if (ste->ste_type == FunctionBlock) {
3892 if (!ste->ste_unoptimized)
3893 flags |= CO_OPTIMIZED;
3894 if (ste->ste_nested)
3895 flags |= CO_NESTED;
3896 if (ste->ste_generator)
3897 flags |= CO_GENERATOR;
3898 if (ste->ste_varargs)
3899 flags |= CO_VARARGS;
3900 if (ste->ste_varkeywords)
3901 flags |= CO_VARKEYWORDS;
3902 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 /* (Only) inherit compilerflags in PyCF_MASK */
3905 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 n = PyDict_Size(c->u->u_freevars);
3908 if (n < 0)
3909 return -1;
3910 if (n == 0) {
3911 n = PyDict_Size(c->u->u_cellvars);
3912 if (n < 0)
3913 return -1;
3914 if (n == 0) {
3915 flags |= CO_NOFREE;
3916 }
3917 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003920}
3921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922static PyCodeObject *
3923makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 PyObject *tmp;
3926 PyCodeObject *co = NULL;
3927 PyObject *consts = NULL;
3928 PyObject *names = NULL;
3929 PyObject *varnames = NULL;
3930 PyObject *filename = NULL;
3931 PyObject *name = NULL;
3932 PyObject *freevars = NULL;
3933 PyObject *cellvars = NULL;
3934 PyObject *bytecode = NULL;
3935 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 tmp = dict_keys_inorder(c->u->u_consts, 0);
3938 if (!tmp)
3939 goto error;
3940 consts = PySequence_List(tmp); /* optimize_code requires a list */
3941 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 names = dict_keys_inorder(c->u->u_names, 0);
3944 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3945 if (!consts || !names || !varnames)
3946 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3949 if (!cellvars)
3950 goto error;
3951 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3952 if (!freevars)
3953 goto error;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00003954 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 if (!filename)
3956 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 nlocals = PyDict_Size(c->u->u_varnames);
3959 flags = compute_code_flags(c);
3960 if (flags < 0)
3961 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3964 if (!bytecode)
3965 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3968 if (!tmp)
3969 goto error;
3970 Py_DECREF(consts);
3971 consts = tmp;
3972
3973 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3974 nlocals, stackdepth(c), flags,
3975 bytecode, consts, names, varnames,
3976 freevars, cellvars,
3977 filename, c->u->u_name,
3978 c->u->u_firstlineno,
3979 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 Py_XDECREF(consts);
3982 Py_XDECREF(names);
3983 Py_XDECREF(varnames);
3984 Py_XDECREF(filename);
3985 Py_XDECREF(name);
3986 Py_XDECREF(freevars);
3987 Py_XDECREF(cellvars);
3988 Py_XDECREF(bytecode);
3989 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003990}
3991
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003992
3993/* For debugging purposes only */
3994#if 0
3995static void
3996dump_instr(const struct instr *i)
3997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 const char *jrel = i->i_jrel ? "jrel " : "";
3999 const char *jabs = i->i_jabs ? "jabs " : "";
4000 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 *arg = '\0';
4003 if (i->i_hasarg)
4004 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4007 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004008}
4009
4010static void
4011dump_basicblock(const basicblock *b)
4012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 const char *seen = b->b_seen ? "seen " : "";
4014 const char *b_return = b->b_return ? "return " : "";
4015 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4016 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4017 if (b->b_instr) {
4018 int i;
4019 for (i = 0; i < b->b_iused; i++) {
4020 fprintf(stderr, " [%02d] ", i);
4021 dump_instr(b->b_instr + i);
4022 }
4023 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004024}
4025#endif
4026
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004027static PyCodeObject *
4028assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 basicblock *b, *entryblock;
4031 struct assembler a;
4032 int i, j, nblocks;
4033 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 /* Make sure every block that falls off the end returns None.
4036 XXX NEXT_BLOCK() isn't quite right, because if the last
4037 block ends with a jump or return b_next shouldn't set.
4038 */
4039 if (!c->u->u_curblock->b_return) {
4040 NEXT_BLOCK(c);
4041 if (addNone)
4042 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4043 ADDOP(c, RETURN_VALUE);
4044 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 nblocks = 0;
4047 entryblock = NULL;
4048 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4049 nblocks++;
4050 entryblock = b;
4051 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 /* Set firstlineno if it wasn't explicitly set. */
4054 if (!c->u->u_firstlineno) {
4055 if (entryblock && entryblock->b_instr)
4056 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4057 else
4058 c->u->u_firstlineno = 1;
4059 }
4060 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4061 goto error;
4062 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 /* Can't modify the bytecode after computing jump offsets. */
4065 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 /* Emit code in reverse postorder from dfs. */
4068 for (i = a.a_nblocks - 1; i >= 0; i--) {
4069 b = a.a_postorder[i];
4070 for (j = 0; j < b->b_iused; j++)
4071 if (!assemble_emit(&a, &b->b_instr[j]))
4072 goto error;
4073 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4076 goto error;
4077 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4078 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004081 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 assemble_free(&a);
4083 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004084}
Georg Brandl8334fd92010-12-04 10:26:46 +00004085
4086#undef PyAST_Compile
4087PyAPI_FUNC(PyCodeObject *)
4088PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4089 PyArena *arena)
4090{
4091 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4092}
4093
4094