blob: 32465f71692941a929e96068fa2bfb9499a109f1 [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
Antoine Pitrou86a36b52011-11-25 18:56:07 +010093enum {
94 COMPILER_SCOPE_MODULE,
95 COMPILER_SCOPE_CLASS,
96 COMPILER_SCOPE_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040097 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010098 COMPILER_SCOPE_COMPREHENSION,
99};
100
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000101/* The following items change on entry and exit of code blocks.
102 They must be saved and restored when returning to a block.
103*/
104struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400108 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100109 int u_scope_type;
110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 /* The following fields are dicts that map objects to
112 the index of them in co_XXX. The index is used as
113 the argument for opcodes that refer to those collections.
114 */
115 PyObject *u_consts; /* all constants */
116 PyObject *u_names; /* all names */
117 PyObject *u_varnames; /* local variables */
118 PyObject *u_cellvars; /* cell variables */
119 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 int u_argcount; /* number of arguments for block */
124 int u_kwonlyargcount; /* number of keyword only arguments for block */
125 /* Pointer to the most recently allocated block. By following b_list
126 members, you can reach all early allocated blocks. */
127 basicblock *u_blocks;
128 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 int u_nfblocks;
131 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int u_firstlineno; /* the first lineno of the block */
134 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000135 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 int u_lineno_set; /* boolean to indicate whether instr
137 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138};
139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000145
146Note that we don't track recursion levels during compilation - the
147task of detecting and rejecting excessive levels of nesting is
148handled by the symbol analysis pass.
149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150*/
151
152struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200153 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 struct symtable *c_st;
155 PyFutureFeatures *c_future; /* pointer to module's __future__ */
156 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157
Georg Brandl8334fd92010-12-04 10:26:46 +0000158 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 int c_interactive; /* true if in interactive mode */
160 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 struct compiler_unit *u; /* compiler state for current block */
163 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
164 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000165};
166
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100167static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168static void compiler_free(struct compiler *);
169static basicblock *compiler_new_block(struct compiler *);
170static int compiler_next_instr(struct compiler *, basicblock *);
171static int compiler_addop(struct compiler *, int);
172static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
173static int compiler_addop_i(struct compiler *, int, int);
174static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175static basicblock *compiler_use_new_block(struct compiler *);
176static int compiler_error(struct compiler *, const char *);
177static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
178
179static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
180static int compiler_visit_stmt(struct compiler *, stmt_ty);
181static int compiler_visit_keyword(struct compiler *, keyword_ty);
182static int compiler_visit_expr(struct compiler *, expr_ty);
183static int compiler_augassign(struct compiler *, stmt_ty);
184static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186
187static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191/* Returns true if there is a loop on the fblock stack. */
192static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193
194static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000195static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500197static int compiler_with(struct compiler *, stmt_ty, int);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000198static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 asdl_seq *args,
200 asdl_seq *keywords,
201 expr_ty starargs,
202 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500203static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400204static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000205
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206static PyCodeObject *assemble(struct compiler *, int addNone);
207static PyObject *__doc__;
208
Benjamin Petersonb173f782009-05-05 22:31:58 +0000209#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 /* Name mangling: __private becomes _classname__private.
215 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200216 PyObject *result;
217 size_t nlen, plen, ipriv;
218 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200220 PyUnicode_READ_CHAR(ident, 0) != '_' ||
221 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 Py_INCREF(ident);
223 return ident;
224 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 nlen = PyUnicode_GET_LENGTH(ident);
226 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 The only time a name with a dot can occur is when
230 we are compiling an import statement that has a
231 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 TODO(jhylton): Decide whether we want to support
234 mangling of the module name, e.g. __M.X.
235 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200236 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
237 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
238 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_INCREF(ident);
240 return ident; /* Don't mangle __whatever__ */
241 }
242 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200243 ipriv = 0;
244 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
245 ipriv++;
246 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 Py_INCREF(ident);
248 return ident; /* Don't mangle if class is just underscores */
249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200250 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000251
Antoine Pitrou55bff892013-04-06 21:21:04 +0200252 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
253 PyErr_SetString(PyExc_OverflowError,
254 "private identifier too large to be mangled");
255 return NULL;
256 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200258 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
259 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
260 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
261
262 result = PyUnicode_New(1 + nlen + plen, maxchar);
263 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200265 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
266 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200267 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
268 Py_DECREF(result);
269 return NULL;
270 }
271 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
272 Py_DECREF(result);
273 return NULL;
274 }
Victor Stinner8f825062012-04-27 13:55:39 +0200275 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200276 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000277}
278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279static int
280compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 c->c_stack = PyList_New(0);
285 if (!c->c_stack)
286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289}
290
291PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200292PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
293 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 struct compiler c;
296 PyCodeObject *co = NULL;
297 PyCompilerFlags local_flags;
298 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (!__doc__) {
301 __doc__ = PyUnicode_InternFromString("__doc__");
302 if (!__doc__)
303 return NULL;
304 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (!compiler_init(&c))
307 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200308 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 c.c_filename = filename;
310 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200311 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (c.c_future == NULL)
313 goto finally;
314 if (!flags) {
315 local_flags.cf_flags = 0;
316 flags = &local_flags;
317 }
318 merged = c.c_future->ff_features | flags->cf_flags;
319 c.c_future->ff_features = merged;
320 flags->cf_flags = merged;
321 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000322 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324
Victor Stinner14e461d2013-08-26 22:28:21 +0200325 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (c.c_st == NULL) {
327 if (!PyErr_Occurred())
328 PyErr_SetString(PyExc_SystemError, "no symtable");
329 goto finally;
330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Thomas Wouters1175c432006-02-27 22:49:54 +0000334 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 compiler_free(&c);
336 assert(co || PyErr_Occurred());
337 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338}
339
340PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200341PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
342 int optimize, PyArena *arena)
343{
344 PyObject *filename;
345 PyCodeObject *co;
346 filename = PyUnicode_DecodeFSDefault(filename_str);
347 if (filename == NULL)
348 return NULL;
349 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
350 Py_DECREF(filename);
351 return co;
352
353}
354
355PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356PyNode_Compile(struct _node *n, const char *filename)
357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 PyCodeObject *co = NULL;
359 mod_ty mod;
360 PyArena *arena = PyArena_New();
361 if (!arena)
362 return NULL;
363 mod = PyAST_FromNode(n, NULL, filename, arena);
364 if (mod)
365 co = PyAST_Compile(mod, filename, NULL, arena);
366 PyArena_Free(arena);
367 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000368}
369
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (c->c_st)
374 PySymtable_Free(c->c_st);
375 if (c->c_future)
376 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200377 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000379}
380
Guido van Rossum79f25d91997-04-29 20:08:16 +0000381static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_ssize_t i, n;
385 PyObject *v, *k;
386 PyObject *dict = PyDict_New();
387 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 n = PyList_Size(list);
390 for (i = 0; i < n; i++) {
391 v = PyLong_FromLong(i);
392 if (!v) {
393 Py_DECREF(dict);
394 return NULL;
395 }
396 k = PyList_GET_ITEM(list, i);
397 k = PyTuple_Pack(2, k, k->ob_type);
398 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
399 Py_XDECREF(k);
400 Py_DECREF(v);
401 Py_DECREF(dict);
402 return NULL;
403 }
404 Py_DECREF(k);
405 Py_DECREF(v);
406 }
407 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000408}
409
410/* Return new dict containing names from src that match scope(s).
411
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000414values are integers, starting at offset and increasing by one for
415each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000416*/
417
418static PyObject *
419dictbytype(PyObject *src, int scope_type, int flag, int offset)
420{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700421 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500423 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 assert(offset >= 0);
426 if (dest == NULL)
427 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000428
Meador Inge2ca63152012-07-18 14:20:11 -0500429 /* Sort the keys so that we have a deterministic order on the indexes
430 saved in the returned dictionary. These indexes are used as indexes
431 into the free and cell var storage. Therefore if they aren't
432 deterministic, then the generated bytecode is not deterministic.
433 */
434 sorted_keys = PyDict_Keys(src);
435 if (sorted_keys == NULL)
436 return NULL;
437 if (PyList_Sort(sorted_keys) != 0) {
438 Py_DECREF(sorted_keys);
439 return NULL;
440 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500441 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500442
443 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 /* XXX this should probably be a macro in symtable.h */
445 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500446 k = PyList_GET_ITEM(sorted_keys, key_i);
447 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 assert(PyLong_Check(v));
449 vi = PyLong_AS_LONG(v);
450 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (scope == scope_type || vi & flag) {
453 PyObject *tuple, *item = PyLong_FromLong(i);
454 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500455 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_DECREF(dest);
457 return NULL;
458 }
459 i++;
460 tuple = PyTuple_Pack(2, k, k->ob_type);
461 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500462 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 Py_DECREF(item);
464 Py_DECREF(dest);
465 Py_XDECREF(tuple);
466 return NULL;
467 }
468 Py_DECREF(item);
469 Py_DECREF(tuple);
470 }
471 }
Meador Inge2ca63152012-07-18 14:20:11 -0500472 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000474}
475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000476static void
477compiler_unit_check(struct compiler_unit *u)
478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 basicblock *block;
480 for (block = u->u_blocks; block != NULL; block = block->b_list) {
481 assert((void *)block != (void *)0xcbcbcbcb);
482 assert((void *)block != (void *)0xfbfbfbfb);
483 assert((void *)block != (void *)0xdbdbdbdb);
484 if (block->b_instr != NULL) {
485 assert(block->b_ialloc > 0);
486 assert(block->b_iused > 0);
487 assert(block->b_ialloc >= block->b_iused);
488 }
489 else {
490 assert (block->b_iused == 0);
491 assert (block->b_ialloc == 0);
492 }
493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000494}
495
496static void
497compiler_unit_free(struct compiler_unit *u)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 compiler_unit_check(u);
502 b = u->u_blocks;
503 while (b != NULL) {
504 if (b->b_instr)
505 PyObject_Free((void *)b->b_instr);
506 next = b->b_list;
507 PyObject_Free((void *)b);
508 b = next;
509 }
510 Py_CLEAR(u->u_ste);
511 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400512 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 Py_CLEAR(u->u_consts);
514 Py_CLEAR(u->u_names);
515 Py_CLEAR(u->u_varnames);
516 Py_CLEAR(u->u_freevars);
517 Py_CLEAR(u->u_cellvars);
518 Py_CLEAR(u->u_private);
519 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520}
521
522static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100523compiler_enter_scope(struct compiler *c, identifier name,
524 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
529 struct compiler_unit));
530 if (!u) {
531 PyErr_NoMemory();
532 return 0;
533 }
534 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100535 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 u->u_argcount = 0;
537 u->u_kwonlyargcount = 0;
538 u->u_ste = PySymtable_Lookup(c->c_st, key);
539 if (!u->u_ste) {
540 compiler_unit_free(u);
541 return 0;
542 }
543 Py_INCREF(name);
544 u->u_name = name;
545 u->u_varnames = list2dict(u->u_ste->ste_varnames);
546 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
547 if (!u->u_varnames || !u->u_cellvars) {
548 compiler_unit_free(u);
549 return 0;
550 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500551 if (u->u_ste->ste_needs_class_closure) {
552 /* Cook up a implicit __class__ cell. */
553 _Py_IDENTIFIER(__class__);
554 PyObject *tuple, *name, *zero;
555 int res;
556 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
557 assert(PyDict_Size(u->u_cellvars) == 0);
558 name = _PyUnicode_FromId(&PyId___class__);
559 if (!name) {
560 compiler_unit_free(u);
561 return 0;
562 }
563 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
564 if (!tuple) {
565 compiler_unit_free(u);
566 return 0;
567 }
568 zero = PyLong_FromLong(0);
569 if (!zero) {
570 Py_DECREF(tuple);
571 compiler_unit_free(u);
572 return 0;
573 }
574 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
575 Py_DECREF(tuple);
576 Py_DECREF(zero);
577 if (res < 0) {
578 compiler_unit_free(u);
579 return 0;
580 }
581 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
584 PyDict_Size(u->u_cellvars));
585 if (!u->u_freevars) {
586 compiler_unit_free(u);
587 return 0;
588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_blocks = NULL;
591 u->u_nfblocks = 0;
592 u->u_firstlineno = lineno;
593 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000594 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 u->u_lineno_set = 0;
596 u->u_consts = PyDict_New();
597 if (!u->u_consts) {
598 compiler_unit_free(u);
599 return 0;
600 }
601 u->u_names = PyDict_New();
602 if (!u->u_names) {
603 compiler_unit_free(u);
604 return 0;
605 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* Push the old compiler_unit on the stack. */
610 if (c->u) {
611 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
612 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
613 Py_XDECREF(capsule);
614 compiler_unit_free(u);
615 return 0;
616 }
617 Py_DECREF(capsule);
618 u->u_private = c->u->u_private;
619 Py_XINCREF(u->u_private);
620 }
621 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 c->c_nestlevel++;
624 if (compiler_use_new_block(c) == NULL)
625 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400627 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
628 if (!compiler_set_qualname(c))
629 return 0;
630 }
631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633}
634
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000635static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636compiler_exit_scope(struct compiler *c)
637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 int n;
639 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 c->c_nestlevel--;
642 compiler_unit_free(c->u);
643 /* Restore c->u to the parent unit. */
644 n = PyList_GET_SIZE(c->c_stack) - 1;
645 if (n >= 0) {
646 capsule = PyList_GET_ITEM(c->c_stack, n);
647 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
648 assert(c->u);
649 /* we are deleting from a list so this really shouldn't fail */
650 if (PySequence_DelItem(c->c_stack, n) < 0)
651 Py_FatalError("compiler_exit_scope()");
652 compiler_unit_check(c->u);
653 }
654 else
655 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657}
658
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400659static int
660compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100661{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100662 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400663 _Py_static_string(dot_locals, ".<locals>");
664 Py_ssize_t stack_size;
665 struct compiler_unit *u = c->u;
666 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400668 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400670 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400671 if (stack_size > 1) {
672 int scope, force_global = 0;
673 struct compiler_unit *parent;
674 PyObject *mangled, *capsule;
675
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400676 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
678 assert(parent);
679
680 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION || u->u_scope_type == COMPILER_SCOPE_CLASS) {
681 assert(u->u_name);
682 mangled = _Py_Mangle(parent->u_private, u->u_name);
683 if (!mangled)
684 return 0;
685 scope = PyST_GetScope(parent->u_ste, mangled);
686 Py_DECREF(mangled);
687 assert(scope != GLOBAL_IMPLICIT);
688 if (scope == GLOBAL_EXPLICIT)
689 force_global = 1;
690 }
691
692 if (!force_global) {
693 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
694 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
695 dot_locals_str = _PyUnicode_FromId(&dot_locals);
696 if (dot_locals_str == NULL)
697 return 0;
698 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
699 if (base == NULL)
700 return 0;
701 }
702 else {
703 Py_INCREF(parent->u_qualname);
704 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400705 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 }
707 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 if (base != NULL) {
710 dot_str = _PyUnicode_FromId(&dot);
711 if (dot_str == NULL) {
712 Py_DECREF(base);
713 return 0;
714 }
715 name = PyUnicode_Concat(base, dot_str);
716 Py_DECREF(base);
717 if (name == NULL)
718 return 0;
719 PyUnicode_Append(&name, u->u_name);
720 if (name == NULL)
721 return 0;
722 }
723 else {
724 Py_INCREF(u->u_name);
725 name = u->u_name;
726 }
727 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400729 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730}
731
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732/* Allocate a new block and return a pointer to it.
733 Returns NULL on error.
734*/
735
736static basicblock *
737compiler_new_block(struct compiler *c)
738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 basicblock *b;
740 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 u = c->u;
743 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
744 if (b == NULL) {
745 PyErr_NoMemory();
746 return NULL;
747 }
748 memset((void *)b, 0, sizeof(basicblock));
749 /* Extend the singly linked list of blocks with new block. */
750 b->b_list = u->u_blocks;
751 u->u_blocks = b;
752 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753}
754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755static basicblock *
756compiler_use_new_block(struct compiler *c)
757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 basicblock *block = compiler_new_block(c);
759 if (block == NULL)
760 return NULL;
761 c->u->u_curblock = block;
762 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
764
765static basicblock *
766compiler_next_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *block = compiler_new_block(c);
769 if (block == NULL)
770 return NULL;
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776static basicblock *
777compiler_use_next_block(struct compiler *c, basicblock *block)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(block != NULL);
780 c->u->u_curblock->b_next = block;
781 c->u->u_curblock = block;
782 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
785/* Returns the offset of the next instruction in the current block's
786 b_instr array. Resizes the b_instr as necessary.
787 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000788*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789
790static int
791compiler_next_instr(struct compiler *c, basicblock *b)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(b != NULL);
794 if (b->b_instr == NULL) {
795 b->b_instr = (struct instr *)PyObject_Malloc(
796 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
797 if (b->b_instr == NULL) {
798 PyErr_NoMemory();
799 return -1;
800 }
801 b->b_ialloc = DEFAULT_BLOCK_SIZE;
802 memset((char *)b->b_instr, 0,
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 }
805 else if (b->b_iused == b->b_ialloc) {
806 struct instr *tmp;
807 size_t oldsize, newsize;
808 oldsize = b->b_ialloc * sizeof(struct instr);
809 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (oldsize > (PY_SIZE_MAX >> 1)) {
812 PyErr_NoMemory();
813 return -1;
814 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (newsize == 0) {
817 PyErr_NoMemory();
818 return -1;
819 }
820 b->b_ialloc <<= 1;
821 tmp = (struct instr *)PyObject_Realloc(
822 (void *)b->b_instr, newsize);
823 if (tmp == NULL) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_instr = tmp;
828 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
829 }
830 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831}
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833/* Set the i_lineno member of the instruction at offset off if the
834 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835 already been set. If it has been set, the call has no effect.
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837 The line number is reset in the following cases:
838 - when entering a new scope
839 - on each statement
840 - on each expression that start a new line
841 - before the "except" clause
842 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000843*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845static void
846compiler_set_lineno(struct compiler *c, int off)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 basicblock *b;
849 if (c->u->u_lineno_set)
850 return;
851 c->u->u_lineno_set = 1;
852 b = c->u->u_curblock;
853 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854}
855
856static int
857opcode_stack_effect(int opcode, int oparg)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 switch (opcode) {
860 case POP_TOP:
861 return -1;
862 case ROT_TWO:
863 case ROT_THREE:
864 return 0;
865 case DUP_TOP:
866 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000867 case DUP_TOP_TWO:
868 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case UNARY_POSITIVE:
871 case UNARY_NEGATIVE:
872 case UNARY_NOT:
873 case UNARY_INVERT:
874 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case SET_ADD:
877 case LIST_APPEND:
878 return -1;
879 case MAP_ADD:
880 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case BINARY_POWER:
883 case BINARY_MULTIPLY:
884 case BINARY_MODULO:
885 case BINARY_ADD:
886 case BINARY_SUBTRACT:
887 case BINARY_SUBSCR:
888 case BINARY_FLOOR_DIVIDE:
889 case BINARY_TRUE_DIVIDE:
890 return -1;
891 case INPLACE_FLOOR_DIVIDE:
892 case INPLACE_TRUE_DIVIDE:
893 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case INPLACE_ADD:
896 case INPLACE_SUBTRACT:
897 case INPLACE_MULTIPLY:
898 case INPLACE_MODULO:
899 return -1;
900 case STORE_SUBSCR:
901 return -3;
902 case STORE_MAP:
903 return -2;
904 case DELETE_SUBSCR:
905 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_LSHIFT:
908 case BINARY_RSHIFT:
909 case BINARY_AND:
910 case BINARY_XOR:
911 case BINARY_OR:
912 return -1;
913 case INPLACE_POWER:
914 return -1;
915 case GET_ITER:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case PRINT_EXPR:
919 return -1;
920 case LOAD_BUILD_CLASS:
921 return 1;
922 case INPLACE_LSHIFT:
923 case INPLACE_RSHIFT:
924 case INPLACE_AND:
925 case INPLACE_XOR:
926 case INPLACE_OR:
927 return -1;
928 case BREAK_LOOP:
929 return 0;
930 case SETUP_WITH:
931 return 7;
932 case WITH_CLEANUP:
933 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case RETURN_VALUE:
935 return -1;
936 case IMPORT_STAR:
937 return -1;
938 case YIELD_VALUE:
939 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500940 case YIELD_FROM:
941 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case POP_BLOCK:
943 return 0;
944 case POP_EXCEPT:
945 return 0; /* -3 except if bad bytecode */
946 case END_FINALLY:
947 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case STORE_NAME:
950 return -1;
951 case DELETE_NAME:
952 return 0;
953 case UNPACK_SEQUENCE:
954 return oparg-1;
955 case UNPACK_EX:
956 return (oparg&0xFF) + (oparg>>8);
957 case FOR_ITER:
958 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case STORE_ATTR:
961 return -2;
962 case DELETE_ATTR:
963 return -1;
964 case STORE_GLOBAL:
965 return -1;
966 case DELETE_GLOBAL:
967 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 case LOAD_CONST:
969 return 1;
970 case LOAD_NAME:
971 return 1;
972 case BUILD_TUPLE:
973 case BUILD_LIST:
974 case BUILD_SET:
975 return 1-oparg;
976 case BUILD_MAP:
977 return 1;
978 case LOAD_ATTR:
979 return 0;
980 case COMPARE_OP:
981 return -1;
982 case IMPORT_NAME:
983 return -1;
984 case IMPORT_FROM:
985 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case JUMP_FORWARD:
988 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
989 case JUMP_IF_FALSE_OR_POP: /* "" */
990 case JUMP_ABSOLUTE:
991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case POP_JUMP_IF_FALSE:
994 case POP_JUMP_IF_TRUE:
995 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case LOAD_GLOBAL:
998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case CONTINUE_LOOP:
1001 return 0;
1002 case SETUP_LOOP:
1003 return 0;
1004 case SETUP_EXCEPT:
1005 case SETUP_FINALLY:
1006 return 6; /* can push 3 values for the new exception
1007 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 case LOAD_FAST:
1010 return 1;
1011 case STORE_FAST:
1012 return -1;
1013 case DELETE_FAST:
1014 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case RAISE_VARARGS:
1017 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001018#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case CALL_FUNCTION:
1020 return -NARGS(oparg);
1021 case CALL_FUNCTION_VAR:
1022 case CALL_FUNCTION_KW:
1023 return -NARGS(oparg)-1;
1024 case CALL_FUNCTION_VAR_KW:
1025 return -NARGS(oparg)-2;
1026 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001027 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001029 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001030#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case BUILD_SLICE:
1032 if (oparg == 3)
1033 return -2;
1034 else
1035 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case LOAD_CLOSURE:
1038 return 1;
1039 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001040 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 return 1;
1042 case STORE_DEREF:
1043 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001044 case DELETE_DEREF:
1045 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 default:
1047 fprintf(stderr, "opcode = %d\n", opcode);
1048 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 }
1051 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052}
1053
1054/* Add an opcode with no argument.
1055 Returns 0 on failure, 1 on success.
1056*/
1057
1058static int
1059compiler_addop(struct compiler *c, int opcode)
1060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 basicblock *b;
1062 struct instr *i;
1063 int off;
1064 off = compiler_next_instr(c, c->u->u_curblock);
1065 if (off < 0)
1066 return 0;
1067 b = c->u->u_curblock;
1068 i = &b->b_instr[off];
1069 i->i_opcode = opcode;
1070 i->i_hasarg = 0;
1071 if (opcode == RETURN_VALUE)
1072 b->b_return = 1;
1073 compiler_set_lineno(c, off);
1074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075}
1076
1077static int
1078compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyObject *t, *v;
1081 Py_ssize_t arg;
1082 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083
Serhiy Storchaka95949422013-08-27 19:40:23 +03001084 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1086 if (PyFloat_Check(o)) {
1087 d = PyFloat_AS_DOUBLE(o);
1088 /* all we need is to make the tuple different in either the 0.0
1089 * or -0.0 case from all others, just to avoid the "coercion".
1090 */
1091 if (d == 0.0 && copysign(1.0, d) < 0.0)
1092 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1093 else
1094 t = PyTuple_Pack(2, o, o->ob_type);
1095 }
1096 else if (PyComplex_Check(o)) {
1097 Py_complex z;
1098 int real_negzero, imag_negzero;
1099 /* For the complex case we must make complex(x, 0.)
1100 different from complex(x, -0.) and complex(0., y)
1101 different from complex(-0., y), for any x and y.
1102 All four complex zeros must be distinguished.*/
1103 z = PyComplex_AsCComplex(o);
1104 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1105 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1106 if (real_negzero && imag_negzero) {
1107 t = PyTuple_Pack(5, o, o->ob_type,
1108 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 else if (imag_negzero) {
1111 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001112 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 else if (real_negzero) {
1114 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1115 }
1116 else {
1117 t = PyTuple_Pack(2, o, o->ob_type);
1118 }
1119 }
1120 else {
1121 t = PyTuple_Pack(2, o, o->ob_type);
1122 }
1123 if (t == NULL)
1124 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 v = PyDict_GetItem(dict, t);
1127 if (!v) {
1128 if (PyErr_Occurred())
1129 return -1;
1130 arg = PyDict_Size(dict);
1131 v = PyLong_FromLong(arg);
1132 if (!v) {
1133 Py_DECREF(t);
1134 return -1;
1135 }
1136 if (PyDict_SetItem(dict, t, v) < 0) {
1137 Py_DECREF(t);
1138 Py_DECREF(v);
1139 return -1;
1140 }
1141 Py_DECREF(v);
1142 }
1143 else
1144 arg = PyLong_AsLong(v);
1145 Py_DECREF(t);
1146 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147}
1148
1149static int
1150compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152{
1153 int arg = compiler_add_o(c, dict, o);
1154 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return compiler_addop_i(c, opcode, arg);
1157}
1158
1159static int
1160compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162{
1163 int arg;
1164 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1165 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001166 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 arg = compiler_add_o(c, dict, mangled);
1168 Py_DECREF(mangled);
1169 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001170 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171 return compiler_addop_i(c, opcode, arg);
1172}
1173
1174/* Add an opcode with an integer argument.
1175 Returns 0 on failure, 1 on success.
1176*/
1177
1178static int
1179compiler_addop_i(struct compiler *c, int opcode, int oparg)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 struct instr *i;
1182 int off;
1183 off = compiler_next_instr(c, c->u->u_curblock);
1184 if (off < 0)
1185 return 0;
1186 i = &c->u->u_curblock->b_instr[off];
1187 i->i_opcode = opcode;
1188 i->i_oparg = oparg;
1189 i->i_hasarg = 1;
1190 compiler_set_lineno(c, off);
1191 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192}
1193
1194static int
1195compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 struct instr *i;
1198 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 assert(b != NULL);
1201 off = compiler_next_instr(c, c->u->u_curblock);
1202 if (off < 0)
1203 return 0;
1204 i = &c->u->u_curblock->b_instr[off];
1205 i->i_opcode = opcode;
1206 i->i_target = b;
1207 i->i_hasarg = 1;
1208 if (absolute)
1209 i->i_jabs = 1;
1210 else
1211 i->i_jrel = 1;
1212 compiler_set_lineno(c, off);
1213 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214}
1215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1217 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 it as the current block. NEXT_BLOCK() also creates an implicit jump
1219 from the current block to the new block.
1220*/
1221
Thomas Wouters89f507f2006-12-13 04:49:30 +00001222/* The returns inside these macros make it impossible to decref objects
1223 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224*/
1225
1226
1227#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (compiler_use_new_block((C)) == NULL) \
1229 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230}
1231
1232#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (compiler_next_block((C)) == NULL) \
1234 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
1237#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (!compiler_addop((C), (OP))) \
1239 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001240}
1241
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001242#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (!compiler_addop((C), (OP))) { \
1244 compiler_exit_scope(c); \
1245 return 0; \
1246 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001247}
1248
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1251 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1256 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (!compiler_addop_i((C), (OP), (O))) \
1261 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262}
1263
1264#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!compiler_addop_j((C), (OP), (O), 1)) \
1266 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
1269#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (!compiler_addop_j((C), (OP), (O), 0)) \
1271 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272}
1273
1274/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1275 the ASDL name to synthesize the name of the C type and the visit function.
1276*/
1277
1278#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!compiler_visit_ ## TYPE((C), (V))) \
1280 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001283#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!compiler_visit_ ## TYPE((C), (V))) { \
1285 compiler_exit_scope(c); \
1286 return 0; \
1287 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001288}
1289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (!compiler_visit_slice((C), (V), (CTX))) \
1292 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293}
1294
1295#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 int _i; \
1297 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1298 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1299 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1300 if (!compiler_visit_ ## TYPE((C), elt)) \
1301 return 0; \
1302 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303}
1304
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001305#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 int _i; \
1307 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1308 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1309 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1310 if (!compiler_visit_ ## TYPE((C), elt)) { \
1311 compiler_exit_scope(c); \
1312 return 0; \
1313 } \
1314 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001315}
1316
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317static int
1318compiler_isdocstring(stmt_ty s)
1319{
1320 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001321 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322 return s->v.Expr.value->kind == Str_kind;
1323}
1324
1325/* Compile a sequence of statements, checking for a docstring. */
1326
1327static int
1328compiler_body(struct compiler *c, asdl_seq *stmts)
1329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 int i = 0;
1331 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (!asdl_seq_LEN(stmts))
1334 return 1;
1335 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001336 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* don't generate docstrings if -OO */
1338 i = 1;
1339 VISIT(c, expr, st->v.Expr.value);
1340 if (!compiler_nameop(c, __doc__, Store))
1341 return 0;
1342 }
1343 for (; i < asdl_seq_LEN(stmts); i++)
1344 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1345 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346}
1347
1348static PyCodeObject *
1349compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyCodeObject *co;
1352 int addNone = 1;
1353 static PyObject *module;
1354 if (!module) {
1355 module = PyUnicode_InternFromString("<module>");
1356 if (!module)
1357 return NULL;
1358 }
1359 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001360 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 return NULL;
1362 switch (mod->kind) {
1363 case Module_kind:
1364 if (!compiler_body(c, mod->v.Module.body)) {
1365 compiler_exit_scope(c);
1366 return 0;
1367 }
1368 break;
1369 case Interactive_kind:
1370 c->c_interactive = 1;
1371 VISIT_SEQ_IN_SCOPE(c, stmt,
1372 mod->v.Interactive.body);
1373 break;
1374 case Expression_kind:
1375 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1376 addNone = 0;
1377 break;
1378 case Suite_kind:
1379 PyErr_SetString(PyExc_SystemError,
1380 "suite should not be possible");
1381 return 0;
1382 default:
1383 PyErr_Format(PyExc_SystemError,
1384 "module kind %d should not be possible",
1385 mod->kind);
1386 return 0;
1387 }
1388 co = assemble(c, addNone);
1389 compiler_exit_scope(c);
1390 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001391}
1392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393/* The test for LOCAL must come before the test for FREE in order to
1394 handle classes where name is both local and free. The local var is
1395 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001396*/
1397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398static int
1399get_ref_type(struct compiler *c, PyObject *name)
1400{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001401 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001402 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1403 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1404 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001405 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (scope == 0) {
1407 char buf[350];
1408 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001409 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 "symbols: %s\nlocals: %s\nglobals: %s",
1411 PyBytes_AS_STRING(name),
1412 PyBytes_AS_STRING(c->u->u_name),
1413 PyObject_REPR(c->u->u_ste->ste_id),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyObject_REPR(c->u->u_ste->ste_symbols),
1415 PyObject_REPR(c->u->u_varnames),
1416 PyObject_REPR(c->u->u_names)
1417 );
1418 Py_FatalError(buf);
1419 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422}
1423
1424static int
1425compiler_lookup_arg(PyObject *dict, PyObject *name)
1426{
1427 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001428 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001430 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001432 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001434 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001435 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436}
1437
1438static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001439compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001442 if (qualname == NULL)
1443 qualname = co->co_name;
1444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (free == 0) {
1446 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001447 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 ADDOP_I(c, MAKE_FUNCTION, args);
1449 return 1;
1450 }
1451 for (i = 0; i < free; ++i) {
1452 /* Bypass com_addop_varname because it will generate
1453 LOAD_DEREF but LOAD_CLOSURE is needed.
1454 */
1455 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1456 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 /* Special case: If a class contains a method with a
1459 free variable that has the same name as a method,
1460 the name will be considered free *and* local in the
1461 class. It should be handled by the closure, as
1462 well as by the normal name loookup logic.
1463 */
1464 reftype = get_ref_type(c, name);
1465 if (reftype == CELL)
1466 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1467 else /* (reftype == FREE) */
1468 arg = compiler_lookup_arg(c->u->u_freevars, name);
1469 if (arg == -1) {
1470 fprintf(stderr,
1471 "lookup %s in %s %d %d\n"
1472 "freevars of %s: %s\n",
1473 PyObject_REPR(name),
1474 PyBytes_AS_STRING(c->u->u_name),
1475 reftype, arg,
1476 _PyUnicode_AsString(co->co_name),
1477 PyObject_REPR(co->co_freevars));
1478 Py_FatalError("compiler_make_closure()");
1479 }
1480 ADDOP_I(c, LOAD_CLOSURE, arg);
1481 }
1482 ADDOP_I(c, BUILD_TUPLE, free);
1483 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001484 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 ADDOP_I(c, MAKE_CLOSURE, args);
1486 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487}
1488
1489static int
1490compiler_decorators(struct compiler *c, asdl_seq* decos)
1491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (!decos)
1495 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1498 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1499 }
1500 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501}
1502
1503static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001504compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 int i, default_count = 0;
1508 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1509 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1510 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1511 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001512 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1513 if (!mangled)
1514 return -1;
1515 ADDOP_O(c, LOAD_CONST, mangled, consts);
1516 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (!compiler_visit_expr(c, default_)) {
1518 return -1;
1519 }
1520 default_count++;
1521 }
1522 }
1523 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001524}
1525
1526static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001527compiler_visit_argannotation(struct compiler *c, identifier id,
1528 expr_ty annotation, PyObject *names)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (annotation) {
1531 VISIT(c, expr, annotation);
1532 if (PyList_Append(names, id))
1533 return -1;
1534 }
1535 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001536}
1537
1538static int
1539compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1540 PyObject *names)
1541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 int i, error;
1543 for (i = 0; i < asdl_seq_LEN(args); i++) {
1544 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1545 error = compiler_visit_argannotation(
1546 c,
1547 arg->arg,
1548 arg->annotation,
1549 names);
1550 if (error)
1551 return error;
1552 }
1553 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001554}
1555
1556static int
1557compiler_visit_annotations(struct compiler *c, arguments_ty args,
1558 expr_ty returns)
1559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 /* Push arg annotations and a list of the argument names. Return the #
1561 of items pushed. The expressions are evaluated out-of-order wrt the
1562 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1565 */
1566 static identifier return_str;
1567 PyObject *names;
1568 int len;
1569 names = PyList_New(0);
1570 if (!names)
1571 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (compiler_visit_argannotations(c, args->args, names))
1574 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001575 if (args->vararg && args->vararg->annotation &&
1576 compiler_visit_argannotation(c, args->vararg->arg,
1577 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 goto error;
1579 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1580 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001581 if (args->kwarg && args->kwarg->annotation &&
1582 compiler_visit_argannotation(c, args->kwarg->arg,
1583 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (!return_str) {
1587 return_str = PyUnicode_InternFromString("return");
1588 if (!return_str)
1589 goto error;
1590 }
1591 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1592 goto error;
1593 }
1594
1595 len = PyList_GET_SIZE(names);
1596 if (len > 65534) {
1597 /* len must fit in 16 bits, and len is incremented below */
1598 PyErr_SetString(PyExc_SyntaxError,
1599 "too many annotations");
1600 goto error;
1601 }
1602 if (len) {
1603 /* convert names to a tuple and place on stack */
1604 PyObject *elt;
1605 int i;
1606 PyObject *s = PyTuple_New(len);
1607 if (!s)
1608 goto error;
1609 for (i = 0; i < len; i++) {
1610 elt = PyList_GET_ITEM(names, i);
1611 Py_INCREF(elt);
1612 PyTuple_SET_ITEM(s, i, elt);
1613 }
1614 ADDOP_O(c, LOAD_CONST, s, consts);
1615 Py_DECREF(s);
1616 len++; /* include the just-pushed tuple */
1617 }
1618 Py_DECREF(names);
1619 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001620
1621error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_DECREF(names);
1623 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001624}
1625
1626static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001627compiler_function(struct compiler *c, stmt_ty s)
1628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001630 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 arguments_ty args = s->v.FunctionDef.args;
1632 expr_ty returns = s->v.FunctionDef.returns;
1633 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1634 stmt_ty st;
1635 int i, n, docstring, kw_default_count = 0, arglength;
1636 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (!compiler_decorators(c, decos))
1641 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001642 if (args->defaults)
1643 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 if (args->kwonlyargs) {
1645 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1646 args->kw_defaults);
1647 if (res < 0)
1648 return 0;
1649 kw_default_count = res;
1650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 num_annotations = compiler_visit_annotations(c, args, returns);
1652 if (num_annotations < 0)
1653 return 0;
1654 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001655
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001656 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1657 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 s->lineno))
1659 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1662 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001663 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 first_const = st->v.Expr.value->v.Str.s;
1665 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1666 compiler_exit_scope(c);
1667 return 0;
1668 }
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 n = asdl_seq_LEN(s->v.FunctionDef.body);
1673 /* if there was a docstring, we need to skip the first statement */
1674 for (i = docstring; i < n; i++) {
1675 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1676 VISIT_IN_SCOPE(c, stmt, st);
1677 }
1678 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001679 qualname = c->u->u_qualname;
1680 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001682 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001683 Py_XDECREF(qualname);
1684 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001686 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 arglength = asdl_seq_LEN(args->defaults);
1689 arglength |= kw_default_count << 8;
1690 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001691 compiler_make_closure(c, co, arglength, qualname);
1692 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 /* decorators */
1696 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1697 ADDOP_I(c, CALL_FUNCTION, 1);
1698 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701}
1702
1703static int
1704compiler_class(struct compiler *c, stmt_ty s)
1705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyCodeObject *co;
1707 PyObject *str;
1708 int i;
1709 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (!compiler_decorators(c, decos))
1712 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 /* ultimately generate code for:
1715 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1716 where:
1717 <func> is a function/closure created from the class body;
1718 it has a single argument (__locals__) where the dict
1719 (or MutableSequence) representing the locals is passed
1720 <name> is the class name
1721 <bases> is the positional arguments and *varargs argument
1722 <keywords> is the keyword arguments and **kwds argument
1723 This borrows from compiler_call.
1724 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001727 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1728 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return 0;
1730 /* this block represents what we do in the new scope */
1731 {
1732 /* use the class name for name mangling */
1733 Py_INCREF(s->v.ClassDef.name);
1734 Py_XDECREF(c->u->u_private);
1735 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* load (global) __name__ ... */
1737 str = PyUnicode_InternFromString("__name__");
1738 if (!str || !compiler_nameop(c, str, Load)) {
1739 Py_XDECREF(str);
1740 compiler_exit_scope(c);
1741 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 Py_DECREF(str);
1744 /* ... and store it as __module__ */
1745 str = PyUnicode_InternFromString("__module__");
1746 if (!str || !compiler_nameop(c, str, Store)) {
1747 Py_XDECREF(str);
1748 compiler_exit_scope(c);
1749 return 0;
1750 }
1751 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001752 assert(c->u->u_qualname);
1753 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001754 str = PyUnicode_InternFromString("__qualname__");
1755 if (!str || !compiler_nameop(c, str, Store)) {
1756 Py_XDECREF(str);
1757 compiler_exit_scope(c);
1758 return 0;
1759 }
1760 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* compile the body proper */
1762 if (!compiler_body(c, s->v.ClassDef.body)) {
1763 compiler_exit_scope(c);
1764 return 0;
1765 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001766 if (c->u->u_ste->ste_needs_class_closure) {
1767 /* return the (empty) __class__ cell */
1768 str = PyUnicode_InternFromString("__class__");
1769 if (str == NULL) {
1770 compiler_exit_scope(c);
1771 return 0;
1772 }
1773 i = compiler_lookup_arg(c->u->u_cellvars, str);
1774 Py_DECREF(str);
1775 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* Return the cell where to store __class__ */
1777 ADDOP_I(c, LOAD_CLOSURE, i);
1778 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001779 else {
1780 assert(PyDict_Size(c->u->u_cellvars) == 0);
1781 /* This happens when nobody references the cell. Return None. */
1782 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1783 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1785 /* create the code object */
1786 co = assemble(c, 1);
1787 }
1788 /* leave the new scope */
1789 compiler_exit_scope(c);
1790 if (co == NULL)
1791 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 /* 2. load the 'build_class' function */
1794 ADDOP(c, LOAD_BUILD_CLASS);
1795
1796 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001797 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 Py_DECREF(co);
1799
1800 /* 4. load class name */
1801 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1802
1803 /* 5. generate the rest of the code for the call */
1804 if (!compiler_call_helper(c, 2,
1805 s->v.ClassDef.bases,
1806 s->v.ClassDef.keywords,
1807 s->v.ClassDef.starargs,
1808 s->v.ClassDef.kwargs))
1809 return 0;
1810
1811 /* 6. apply decorators */
1812 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1813 ADDOP_I(c, CALL_FUNCTION, 1);
1814 }
1815
1816 /* 7. store into <name> */
1817 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1818 return 0;
1819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820}
1821
1822static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001823compiler_ifexp(struct compiler *c, expr_ty e)
1824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 basicblock *end, *next;
1826
1827 assert(e->kind == IfExp_kind);
1828 end = compiler_new_block(c);
1829 if (end == NULL)
1830 return 0;
1831 next = compiler_new_block(c);
1832 if (next == NULL)
1833 return 0;
1834 VISIT(c, expr, e->v.IfExp.test);
1835 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1836 VISIT(c, expr, e->v.IfExp.body);
1837 ADDOP_JREL(c, JUMP_FORWARD, end);
1838 compiler_use_next_block(c, next);
1839 VISIT(c, expr, e->v.IfExp.orelse);
1840 compiler_use_next_block(c, end);
1841 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001842}
1843
1844static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845compiler_lambda(struct compiler *c, expr_ty e)
1846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001848 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 static identifier name;
1850 int kw_default_count = 0, arglength;
1851 arguments_ty args = e->v.Lambda.args;
1852 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 if (!name) {
1855 name = PyUnicode_InternFromString("<lambda>");
1856 if (!name)
1857 return 0;
1858 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001860 if (args->defaults)
1861 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (args->kwonlyargs) {
1863 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1864 args->kw_defaults);
1865 if (res < 0) return 0;
1866 kw_default_count = res;
1867 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001868 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001869 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 /* Make None the first constant, so the lambda can't have a
1873 docstring. */
1874 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1875 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 c->u->u_argcount = asdl_seq_LEN(args->args);
1878 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1879 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1880 if (c->u->u_ste->ste_generator) {
1881 ADDOP_IN_SCOPE(c, POP_TOP);
1882 }
1883 else {
1884 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1885 }
1886 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001887 qualname = c->u->u_qualname;
1888 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001890 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 arglength = asdl_seq_LEN(args->defaults);
1894 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001895 compiler_make_closure(c, co, arglength, qualname);
1896 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 Py_DECREF(co);
1898
1899 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001900}
1901
1902static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903compiler_if(struct compiler *c, stmt_ty s)
1904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 basicblock *end, *next;
1906 int constant;
1907 assert(s->kind == If_kind);
1908 end = compiler_new_block(c);
1909 if (end == NULL)
1910 return 0;
1911
Georg Brandl8334fd92010-12-04 10:26:46 +00001912 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* constant = 0: "if 0"
1914 * constant = 1: "if 1", "if 2", ...
1915 * constant = -1: rest */
1916 if (constant == 0) {
1917 if (s->v.If.orelse)
1918 VISIT_SEQ(c, stmt, s->v.If.orelse);
1919 } else if (constant == 1) {
1920 VISIT_SEQ(c, stmt, s->v.If.body);
1921 } else {
1922 if (s->v.If.orelse) {
1923 next = compiler_new_block(c);
1924 if (next == NULL)
1925 return 0;
1926 }
1927 else
1928 next = end;
1929 VISIT(c, expr, s->v.If.test);
1930 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1931 VISIT_SEQ(c, stmt, s->v.If.body);
1932 ADDOP_JREL(c, JUMP_FORWARD, end);
1933 if (s->v.If.orelse) {
1934 compiler_use_next_block(c, next);
1935 VISIT_SEQ(c, stmt, s->v.If.orelse);
1936 }
1937 }
1938 compiler_use_next_block(c, end);
1939 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940}
1941
1942static int
1943compiler_for(struct compiler *c, stmt_ty s)
1944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 start = compiler_new_block(c);
1948 cleanup = compiler_new_block(c);
1949 end = compiler_new_block(c);
1950 if (start == NULL || end == NULL || cleanup == NULL)
1951 return 0;
1952 ADDOP_JREL(c, SETUP_LOOP, end);
1953 if (!compiler_push_fblock(c, LOOP, start))
1954 return 0;
1955 VISIT(c, expr, s->v.For.iter);
1956 ADDOP(c, GET_ITER);
1957 compiler_use_next_block(c, start);
1958 ADDOP_JREL(c, FOR_ITER, cleanup);
1959 VISIT(c, expr, s->v.For.target);
1960 VISIT_SEQ(c, stmt, s->v.For.body);
1961 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1962 compiler_use_next_block(c, cleanup);
1963 ADDOP(c, POP_BLOCK);
1964 compiler_pop_fblock(c, LOOP, start);
1965 VISIT_SEQ(c, stmt, s->v.For.orelse);
1966 compiler_use_next_block(c, end);
1967 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968}
1969
1970static int
1971compiler_while(struct compiler *c, stmt_ty s)
1972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001974 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (constant == 0) {
1977 if (s->v.While.orelse)
1978 VISIT_SEQ(c, stmt, s->v.While.orelse);
1979 return 1;
1980 }
1981 loop = compiler_new_block(c);
1982 end = compiler_new_block(c);
1983 if (constant == -1) {
1984 anchor = compiler_new_block(c);
1985 if (anchor == NULL)
1986 return 0;
1987 }
1988 if (loop == NULL || end == NULL)
1989 return 0;
1990 if (s->v.While.orelse) {
1991 orelse = compiler_new_block(c);
1992 if (orelse == NULL)
1993 return 0;
1994 }
1995 else
1996 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 ADDOP_JREL(c, SETUP_LOOP, end);
1999 compiler_use_next_block(c, loop);
2000 if (!compiler_push_fblock(c, LOOP, loop))
2001 return 0;
2002 if (constant == -1) {
2003 VISIT(c, expr, s->v.While.test);
2004 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2005 }
2006 VISIT_SEQ(c, stmt, s->v.While.body);
2007 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 /* XXX should the two POP instructions be in a separate block
2010 if there is no else clause ?
2011 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (constant == -1) {
2014 compiler_use_next_block(c, anchor);
2015 ADDOP(c, POP_BLOCK);
2016 }
2017 compiler_pop_fblock(c, LOOP, loop);
2018 if (orelse != NULL) /* what if orelse is just pass? */
2019 VISIT_SEQ(c, stmt, s->v.While.orelse);
2020 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023}
2024
2025static int
2026compiler_continue(struct compiler *c)
2027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2029 static const char IN_FINALLY_ERROR_MSG[] =
2030 "'continue' not supported inside 'finally' clause";
2031 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (!c->u->u_nfblocks)
2034 return compiler_error(c, LOOP_ERROR_MSG);
2035 i = c->u->u_nfblocks - 1;
2036 switch (c->u->u_fblock[i].fb_type) {
2037 case LOOP:
2038 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2039 break;
2040 case EXCEPT:
2041 case FINALLY_TRY:
2042 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2043 /* Prevent continue anywhere under a finally
2044 even if hidden in a sub-try or except. */
2045 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2046 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2047 }
2048 if (i == -1)
2049 return compiler_error(c, LOOP_ERROR_MSG);
2050 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2051 break;
2052 case FINALLY_END:
2053 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2054 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057}
2058
2059/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060
2061 SETUP_FINALLY L
2062 <code for body>
2063 POP_BLOCK
2064 LOAD_CONST <None>
2065 L: <code for finalbody>
2066 END_FINALLY
2067
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 The special instructions use the block stack. Each block
2069 stack entry contains the instruction that created it (here
2070 SETUP_FINALLY), the level of the value stack at the time the
2071 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 Pushes the current value stack level and the label
2075 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 Pops en entry from the block stack, and pops the value
2078 stack until its level is the same as indicated on the
2079 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 Pops a variable number of entries from the *value* stack
2082 and re-raises the exception they specify. The number of
2083 entries popped depends on the (pseudo) exception type.
2084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 The block stack is unwound when an exception is raised:
2086 when a SETUP_FINALLY entry is found, the exception is pushed
2087 onto the value stack (and the exception condition is cleared),
2088 and the interpreter jumps to the label gotten from the block
2089 stack.
2090*/
2091
2092static int
2093compiler_try_finally(struct compiler *c, stmt_ty s)
2094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 basicblock *body, *end;
2096 body = compiler_new_block(c);
2097 end = compiler_new_block(c);
2098 if (body == NULL || end == NULL)
2099 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 ADDOP_JREL(c, SETUP_FINALLY, end);
2102 compiler_use_next_block(c, body);
2103 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2104 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002105 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2106 if (!compiler_try_except(c, s))
2107 return 0;
2108 }
2109 else {
2110 VISIT_SEQ(c, stmt, s->v.Try.body);
2111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 ADDOP(c, POP_BLOCK);
2113 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2116 compiler_use_next_block(c, end);
2117 if (!compiler_push_fblock(c, FINALLY_END, end))
2118 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002119 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 ADDOP(c, END_FINALLY);
2121 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124}
2125
2126/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002127 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 (The contents of the value stack is shown in [], with the top
2129 at the right; 'tb' is trace-back info, 'val' the exception's
2130 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131
2132 Value stack Label Instruction Argument
2133 [] SETUP_EXCEPT L1
2134 [] <code for S>
2135 [] POP_BLOCK
2136 [] JUMP_FORWARD L0
2137
2138 [tb, val, exc] L1: DUP )
2139 [tb, val, exc, exc] <evaluate E1> )
2140 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2141 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2142 [tb, val, exc] POP
2143 [tb, val] <assign to V1> (or POP if no V1)
2144 [tb] POP
2145 [] <code for S1>
2146 JUMP_FORWARD L0
2147
2148 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 .............................etc.......................
2150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2152
2153 [] L0: <next statement>
2154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155 Of course, parts are not generated if Vi or Ei is not present.
2156*/
2157static int
2158compiler_try_except(struct compiler *c, stmt_ty s)
2159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 basicblock *body, *orelse, *except, *end;
2161 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 body = compiler_new_block(c);
2164 except = compiler_new_block(c);
2165 orelse = compiler_new_block(c);
2166 end = compiler_new_block(c);
2167 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2168 return 0;
2169 ADDOP_JREL(c, SETUP_EXCEPT, except);
2170 compiler_use_next_block(c, body);
2171 if (!compiler_push_fblock(c, EXCEPT, body))
2172 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002173 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 ADDOP(c, POP_BLOCK);
2175 compiler_pop_fblock(c, EXCEPT, body);
2176 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002177 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 compiler_use_next_block(c, except);
2179 for (i = 0; i < n; i++) {
2180 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002181 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (!handler->v.ExceptHandler.type && i < n-1)
2183 return compiler_error(c, "default 'except:' must be last");
2184 c->u->u_lineno_set = 0;
2185 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002186 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 except = compiler_new_block(c);
2188 if (except == NULL)
2189 return 0;
2190 if (handler->v.ExceptHandler.type) {
2191 ADDOP(c, DUP_TOP);
2192 VISIT(c, expr, handler->v.ExceptHandler.type);
2193 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2194 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2195 }
2196 ADDOP(c, POP_TOP);
2197 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002198 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002199
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002200 cleanup_end = compiler_new_block(c);
2201 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002202 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002203 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002204
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002205 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2206 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002208 /*
2209 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002210 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002211 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002212 try:
2213 # body
2214 finally:
2215 name = None
2216 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002217 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002219 /* second try: */
2220 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2221 compiler_use_next_block(c, cleanup_body);
2222 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2223 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002225 /* second # body */
2226 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2227 ADDOP(c, POP_BLOCK);
2228 ADDOP(c, POP_EXCEPT);
2229 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002231 /* finally: */
2232 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2233 compiler_use_next_block(c, cleanup_end);
2234 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2235 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002237 /* name = None */
2238 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2239 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002241 /* del name */
2242 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002244 ADDOP(c, END_FINALLY);
2245 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 }
2247 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002248 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002250 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002251 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002252 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253
Guido van Rossumb940e112007-01-10 16:19:56 +00002254 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002255 ADDOP(c, POP_TOP);
2256 compiler_use_next_block(c, cleanup_body);
2257 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2258 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002260 ADDOP(c, POP_EXCEPT);
2261 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 }
2263 ADDOP_JREL(c, JUMP_FORWARD, end);
2264 compiler_use_next_block(c, except);
2265 }
2266 ADDOP(c, END_FINALLY);
2267 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002268 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 compiler_use_next_block(c, end);
2270 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271}
2272
2273static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002274compiler_try(struct compiler *c, stmt_ty s) {
2275 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2276 return compiler_try_finally(c, s);
2277 else
2278 return compiler_try_except(c, s);
2279}
2280
2281
2282static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283compiler_import_as(struct compiler *c, identifier name, identifier asname)
2284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* The IMPORT_NAME opcode was already generated. This function
2286 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 If there is a dot in name, we need to split it and emit a
2289 LOAD_ATTR for each name.
2290 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002291 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2292 PyUnicode_GET_LENGTH(name), 1);
2293 if (dot == -2)
2294 return -1;
2295 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002297 Py_ssize_t pos = dot + 1;
2298 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300 dot = PyUnicode_FindChar(name, '.', pos,
2301 PyUnicode_GET_LENGTH(name), 1);
2302 if (dot == -2)
2303 return -1;
2304 attr = PyUnicode_Substring(name, pos,
2305 (dot != -1) ? dot :
2306 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (!attr)
2308 return -1;
2309 ADDOP_O(c, LOAD_ATTR, attr, names);
2310 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002311 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 }
2313 }
2314 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315}
2316
2317static int
2318compiler_import(struct compiler *c, stmt_ty s)
2319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* The Import node stores a module name like a.b.c as a single
2321 string. This is convenient for all cases except
2322 import a.b.c as d
2323 where we need to parse that string to extract the individual
2324 module names.
2325 XXX Perhaps change the representation to make this case simpler?
2326 */
2327 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 for (i = 0; i < n; i++) {
2330 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2331 int r;
2332 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 level = PyLong_FromLong(0);
2335 if (level == NULL)
2336 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 ADDOP_O(c, LOAD_CONST, level, consts);
2339 Py_DECREF(level);
2340 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2341 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 if (alias->asname) {
2344 r = compiler_import_as(c, alias->name, alias->asname);
2345 if (!r)
2346 return r;
2347 }
2348 else {
2349 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002350 Py_ssize_t dot = PyUnicode_FindChar(
2351 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002352 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002353 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002354 if (tmp == NULL)
2355 return 0;
2356 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002358 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 Py_DECREF(tmp);
2360 }
2361 if (!r)
2362 return r;
2363 }
2364 }
2365 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366}
2367
2368static int
2369compiler_from_import(struct compiler *c, stmt_ty s)
2370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 PyObject *names = PyTuple_New(n);
2374 PyObject *level;
2375 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (!empty_string) {
2378 empty_string = PyUnicode_FromString("");
2379 if (!empty_string)
2380 return 0;
2381 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 if (!names)
2384 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 level = PyLong_FromLong(s->v.ImportFrom.level);
2387 if (!level) {
2388 Py_DECREF(names);
2389 return 0;
2390 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* build up the names */
2393 for (i = 0; i < n; i++) {
2394 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2395 Py_INCREF(alias->name);
2396 PyTuple_SET_ITEM(names, i, alias->name);
2397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2400 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2401 Py_DECREF(level);
2402 Py_DECREF(names);
2403 return compiler_error(c, "from __future__ imports must occur "
2404 "at the beginning of the file");
2405 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 ADDOP_O(c, LOAD_CONST, level, consts);
2408 Py_DECREF(level);
2409 ADDOP_O(c, LOAD_CONST, names, consts);
2410 Py_DECREF(names);
2411 if (s->v.ImportFrom.module) {
2412 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2413 }
2414 else {
2415 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2416 }
2417 for (i = 0; i < n; i++) {
2418 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2419 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002421 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 assert(n == 1);
2423 ADDOP(c, IMPORT_STAR);
2424 return 1;
2425 }
2426
2427 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2428 store_name = alias->name;
2429 if (alias->asname)
2430 store_name = alias->asname;
2431
2432 if (!compiler_nameop(c, store_name, Store)) {
2433 Py_DECREF(names);
2434 return 0;
2435 }
2436 }
2437 /* remove imported module */
2438 ADDOP(c, POP_TOP);
2439 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440}
2441
2442static int
2443compiler_assert(struct compiler *c, stmt_ty s)
2444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 static PyObject *assertion_error = NULL;
2446 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002447 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448
Georg Brandl8334fd92010-12-04 10:26:46 +00002449 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 return 1;
2451 if (assertion_error == NULL) {
2452 assertion_error = PyUnicode_InternFromString("AssertionError");
2453 if (assertion_error == NULL)
2454 return 0;
2455 }
2456 if (s->v.Assert.test->kind == Tuple_kind &&
2457 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002458 msg = PyUnicode_FromString("assertion is always true, "
2459 "perhaps remove parentheses?");
2460 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002462 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2463 c->c_filename, c->u->u_lineno,
2464 NULL, NULL) == -1) {
2465 Py_DECREF(msg);
2466 return 0;
2467 }
2468 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 }
2470 VISIT(c, expr, s->v.Assert.test);
2471 end = compiler_new_block(c);
2472 if (end == NULL)
2473 return 0;
2474 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2475 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2476 if (s->v.Assert.msg) {
2477 VISIT(c, expr, s->v.Assert.msg);
2478 ADDOP_I(c, CALL_FUNCTION, 1);
2479 }
2480 ADDOP_I(c, RAISE_VARARGS, 1);
2481 compiler_use_next_block(c, end);
2482 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483}
2484
2485static int
2486compiler_visit_stmt(struct compiler *c, stmt_ty s)
2487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* Always assign a lineno to the next instruction for a stmt. */
2491 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002492 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 switch (s->kind) {
2496 case FunctionDef_kind:
2497 return compiler_function(c, s);
2498 case ClassDef_kind:
2499 return compiler_class(c, s);
2500 case Return_kind:
2501 if (c->u->u_ste->ste_type != FunctionBlock)
2502 return compiler_error(c, "'return' outside function");
2503 if (s->v.Return.value) {
2504 VISIT(c, expr, s->v.Return.value);
2505 }
2506 else
2507 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2508 ADDOP(c, RETURN_VALUE);
2509 break;
2510 case Delete_kind:
2511 VISIT_SEQ(c, expr, s->v.Delete.targets)
2512 break;
2513 case Assign_kind:
2514 n = asdl_seq_LEN(s->v.Assign.targets);
2515 VISIT(c, expr, s->v.Assign.value);
2516 for (i = 0; i < n; i++) {
2517 if (i < n - 1)
2518 ADDOP(c, DUP_TOP);
2519 VISIT(c, expr,
2520 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2521 }
2522 break;
2523 case AugAssign_kind:
2524 return compiler_augassign(c, s);
2525 case For_kind:
2526 return compiler_for(c, s);
2527 case While_kind:
2528 return compiler_while(c, s);
2529 case If_kind:
2530 return compiler_if(c, s);
2531 case Raise_kind:
2532 n = 0;
2533 if (s->v.Raise.exc) {
2534 VISIT(c, expr, s->v.Raise.exc);
2535 n++;
2536 if (s->v.Raise.cause) {
2537 VISIT(c, expr, s->v.Raise.cause);
2538 n++;
2539 }
2540 }
2541 ADDOP_I(c, RAISE_VARARGS, n);
2542 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002543 case Try_kind:
2544 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 case Assert_kind:
2546 return compiler_assert(c, s);
2547 case Import_kind:
2548 return compiler_import(c, s);
2549 case ImportFrom_kind:
2550 return compiler_from_import(c, s);
2551 case Global_kind:
2552 case Nonlocal_kind:
2553 break;
2554 case Expr_kind:
2555 if (c->c_interactive && c->c_nestlevel <= 1) {
2556 VISIT(c, expr, s->v.Expr.value);
2557 ADDOP(c, PRINT_EXPR);
2558 }
2559 else if (s->v.Expr.value->kind != Str_kind &&
2560 s->v.Expr.value->kind != Num_kind) {
2561 VISIT(c, expr, s->v.Expr.value);
2562 ADDOP(c, POP_TOP);
2563 }
2564 break;
2565 case Pass_kind:
2566 break;
2567 case Break_kind:
2568 if (!compiler_in_loop(c))
2569 return compiler_error(c, "'break' outside loop");
2570 ADDOP(c, BREAK_LOOP);
2571 break;
2572 case Continue_kind:
2573 return compiler_continue(c);
2574 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002575 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 }
2577 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578}
2579
2580static int
2581unaryop(unaryop_ty op)
2582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 switch (op) {
2584 case Invert:
2585 return UNARY_INVERT;
2586 case Not:
2587 return UNARY_NOT;
2588 case UAdd:
2589 return UNARY_POSITIVE;
2590 case USub:
2591 return UNARY_NEGATIVE;
2592 default:
2593 PyErr_Format(PyExc_SystemError,
2594 "unary op %d should not be possible", op);
2595 return 0;
2596 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597}
2598
2599static int
2600binop(struct compiler *c, operator_ty op)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 switch (op) {
2603 case Add:
2604 return BINARY_ADD;
2605 case Sub:
2606 return BINARY_SUBTRACT;
2607 case Mult:
2608 return BINARY_MULTIPLY;
2609 case Div:
2610 return BINARY_TRUE_DIVIDE;
2611 case Mod:
2612 return BINARY_MODULO;
2613 case Pow:
2614 return BINARY_POWER;
2615 case LShift:
2616 return BINARY_LSHIFT;
2617 case RShift:
2618 return BINARY_RSHIFT;
2619 case BitOr:
2620 return BINARY_OR;
2621 case BitXor:
2622 return BINARY_XOR;
2623 case BitAnd:
2624 return BINARY_AND;
2625 case FloorDiv:
2626 return BINARY_FLOOR_DIVIDE;
2627 default:
2628 PyErr_Format(PyExc_SystemError,
2629 "binary op %d should not be possible", op);
2630 return 0;
2631 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632}
2633
2634static int
2635cmpop(cmpop_ty op)
2636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 switch (op) {
2638 case Eq:
2639 return PyCmp_EQ;
2640 case NotEq:
2641 return PyCmp_NE;
2642 case Lt:
2643 return PyCmp_LT;
2644 case LtE:
2645 return PyCmp_LE;
2646 case Gt:
2647 return PyCmp_GT;
2648 case GtE:
2649 return PyCmp_GE;
2650 case Is:
2651 return PyCmp_IS;
2652 case IsNot:
2653 return PyCmp_IS_NOT;
2654 case In:
2655 return PyCmp_IN;
2656 case NotIn:
2657 return PyCmp_NOT_IN;
2658 default:
2659 return PyCmp_BAD;
2660 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661}
2662
2663static int
2664inplace_binop(struct compiler *c, operator_ty op)
2665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 switch (op) {
2667 case Add:
2668 return INPLACE_ADD;
2669 case Sub:
2670 return INPLACE_SUBTRACT;
2671 case Mult:
2672 return INPLACE_MULTIPLY;
2673 case Div:
2674 return INPLACE_TRUE_DIVIDE;
2675 case Mod:
2676 return INPLACE_MODULO;
2677 case Pow:
2678 return INPLACE_POWER;
2679 case LShift:
2680 return INPLACE_LSHIFT;
2681 case RShift:
2682 return INPLACE_RSHIFT;
2683 case BitOr:
2684 return INPLACE_OR;
2685 case BitXor:
2686 return INPLACE_XOR;
2687 case BitAnd:
2688 return INPLACE_AND;
2689 case FloorDiv:
2690 return INPLACE_FLOOR_DIVIDE;
2691 default:
2692 PyErr_Format(PyExc_SystemError,
2693 "inplace binary op %d should not be possible", op);
2694 return 0;
2695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696}
2697
2698static int
2699compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 int op, scope, arg;
2702 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 PyObject *dict = c->u->u_names;
2705 PyObject *mangled;
2706 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 mangled = _Py_Mangle(c->u->u_private, name);
2709 if (!mangled)
2710 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002711
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002712 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2713 PyUnicode_CompareWithASCIIString(name, "True") &&
2714 PyUnicode_CompareWithASCIIString(name, "False"));
2715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 op = 0;
2717 optype = OP_NAME;
2718 scope = PyST_GetScope(c->u->u_ste, mangled);
2719 switch (scope) {
2720 case FREE:
2721 dict = c->u->u_freevars;
2722 optype = OP_DEREF;
2723 break;
2724 case CELL:
2725 dict = c->u->u_cellvars;
2726 optype = OP_DEREF;
2727 break;
2728 case LOCAL:
2729 if (c->u->u_ste->ste_type == FunctionBlock)
2730 optype = OP_FAST;
2731 break;
2732 case GLOBAL_IMPLICIT:
2733 if (c->u->u_ste->ste_type == FunctionBlock &&
2734 !c->u->u_ste->ste_unoptimized)
2735 optype = OP_GLOBAL;
2736 break;
2737 case GLOBAL_EXPLICIT:
2738 optype = OP_GLOBAL;
2739 break;
2740 default:
2741 /* scope can be 0 */
2742 break;
2743 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002746 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 switch (optype) {
2749 case OP_DEREF:
2750 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002751 case Load:
2752 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2753 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 case Store: op = STORE_DEREF; break;
2755 case AugLoad:
2756 case AugStore:
2757 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002758 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 case Param:
2760 default:
2761 PyErr_SetString(PyExc_SystemError,
2762 "param invalid for deref variable");
2763 return 0;
2764 }
2765 break;
2766 case OP_FAST:
2767 switch (ctx) {
2768 case Load: op = LOAD_FAST; break;
2769 case Store: op = STORE_FAST; break;
2770 case Del: op = DELETE_FAST; break;
2771 case AugLoad:
2772 case AugStore:
2773 break;
2774 case Param:
2775 default:
2776 PyErr_SetString(PyExc_SystemError,
2777 "param invalid for local variable");
2778 return 0;
2779 }
2780 ADDOP_O(c, op, mangled, varnames);
2781 Py_DECREF(mangled);
2782 return 1;
2783 case OP_GLOBAL:
2784 switch (ctx) {
2785 case Load: op = LOAD_GLOBAL; break;
2786 case Store: op = STORE_GLOBAL; break;
2787 case Del: op = DELETE_GLOBAL; break;
2788 case AugLoad:
2789 case AugStore:
2790 break;
2791 case Param:
2792 default:
2793 PyErr_SetString(PyExc_SystemError,
2794 "param invalid for global variable");
2795 return 0;
2796 }
2797 break;
2798 case OP_NAME:
2799 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002800 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 case Store: op = STORE_NAME; break;
2802 case Del: op = DELETE_NAME; break;
2803 case AugLoad:
2804 case AugStore:
2805 break;
2806 case Param:
2807 default:
2808 PyErr_SetString(PyExc_SystemError,
2809 "param invalid for name variable");
2810 return 0;
2811 }
2812 break;
2813 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 assert(op);
2816 arg = compiler_add_o(c, dict, mangled);
2817 Py_DECREF(mangled);
2818 if (arg < 0)
2819 return 0;
2820 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821}
2822
2823static int
2824compiler_boolop(struct compiler *c, expr_ty e)
2825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 basicblock *end;
2827 int jumpi, i, n;
2828 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 assert(e->kind == BoolOp_kind);
2831 if (e->v.BoolOp.op == And)
2832 jumpi = JUMP_IF_FALSE_OR_POP;
2833 else
2834 jumpi = JUMP_IF_TRUE_OR_POP;
2835 end = compiler_new_block(c);
2836 if (end == NULL)
2837 return 0;
2838 s = e->v.BoolOp.values;
2839 n = asdl_seq_LEN(s) - 1;
2840 assert(n >= 0);
2841 for (i = 0; i < n; ++i) {
2842 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2843 ADDOP_JABS(c, jumpi, end);
2844 }
2845 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2846 compiler_use_next_block(c, end);
2847 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848}
2849
2850static int
2851compiler_list(struct compiler *c, expr_ty e)
2852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 int n = asdl_seq_LEN(e->v.List.elts);
2854 if (e->v.List.ctx == Store) {
2855 int i, seen_star = 0;
2856 for (i = 0; i < n; i++) {
2857 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2858 if (elt->kind == Starred_kind && !seen_star) {
2859 if ((i >= (1 << 8)) ||
2860 (n-i-1 >= (INT_MAX >> 8)))
2861 return compiler_error(c,
2862 "too many expressions in "
2863 "star-unpacking assignment");
2864 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2865 seen_star = 1;
2866 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2867 } else if (elt->kind == Starred_kind) {
2868 return compiler_error(c,
2869 "two starred expressions in assignment");
2870 }
2871 }
2872 if (!seen_star) {
2873 ADDOP_I(c, UNPACK_SEQUENCE, n);
2874 }
2875 }
2876 VISIT_SEQ(c, expr, e->v.List.elts);
2877 if (e->v.List.ctx == Load) {
2878 ADDOP_I(c, BUILD_LIST, n);
2879 }
2880 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881}
2882
2883static int
2884compiler_tuple(struct compiler *c, expr_ty e)
2885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 int n = asdl_seq_LEN(e->v.Tuple.elts);
2887 if (e->v.Tuple.ctx == Store) {
2888 int i, seen_star = 0;
2889 for (i = 0; i < n; i++) {
2890 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2891 if (elt->kind == Starred_kind && !seen_star) {
2892 if ((i >= (1 << 8)) ||
2893 (n-i-1 >= (INT_MAX >> 8)))
2894 return compiler_error(c,
2895 "too many expressions in "
2896 "star-unpacking assignment");
2897 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2898 seen_star = 1;
2899 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2900 } else if (elt->kind == Starred_kind) {
2901 return compiler_error(c,
2902 "two starred expressions in assignment");
2903 }
2904 }
2905 if (!seen_star) {
2906 ADDOP_I(c, UNPACK_SEQUENCE, n);
2907 }
2908 }
2909 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2910 if (e->v.Tuple.ctx == Load) {
2911 ADDOP_I(c, BUILD_TUPLE, n);
2912 }
2913 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914}
2915
2916static int
2917compiler_compare(struct compiler *c, expr_ty e)
2918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 int i, n;
2920 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2923 VISIT(c, expr, e->v.Compare.left);
2924 n = asdl_seq_LEN(e->v.Compare.ops);
2925 assert(n > 0);
2926 if (n > 1) {
2927 cleanup = compiler_new_block(c);
2928 if (cleanup == NULL)
2929 return 0;
2930 VISIT(c, expr,
2931 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2932 }
2933 for (i = 1; i < n; i++) {
2934 ADDOP(c, DUP_TOP);
2935 ADDOP(c, ROT_THREE);
2936 ADDOP_I(c, COMPARE_OP,
2937 cmpop((cmpop_ty)(asdl_seq_GET(
2938 e->v.Compare.ops, i - 1))));
2939 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2940 NEXT_BLOCK(c);
2941 if (i < (n - 1))
2942 VISIT(c, expr,
2943 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2944 }
2945 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2946 ADDOP_I(c, COMPARE_OP,
2947 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2948 if (n > 1) {
2949 basicblock *end = compiler_new_block(c);
2950 if (end == NULL)
2951 return 0;
2952 ADDOP_JREL(c, JUMP_FORWARD, end);
2953 compiler_use_next_block(c, cleanup);
2954 ADDOP(c, ROT_TWO);
2955 ADDOP(c, POP_TOP);
2956 compiler_use_next_block(c, end);
2957 }
2958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959}
2960
2961static int
2962compiler_call(struct compiler *c, expr_ty e)
2963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 VISIT(c, expr, e->v.Call.func);
2965 return compiler_call_helper(c, 0,
2966 e->v.Call.args,
2967 e->v.Call.keywords,
2968 e->v.Call.starargs,
2969 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002970}
2971
2972/* shared code between compiler_call and compiler_class */
2973static int
2974compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 int n, /* Args already pushed */
2976 asdl_seq *args,
2977 asdl_seq *keywords,
2978 expr_ty starargs,
2979 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 n += asdl_seq_LEN(args);
2984 VISIT_SEQ(c, expr, args);
2985 if (keywords) {
2986 VISIT_SEQ(c, keyword, keywords);
2987 n |= asdl_seq_LEN(keywords) << 8;
2988 }
2989 if (starargs) {
2990 VISIT(c, expr, starargs);
2991 code |= 1;
2992 }
2993 if (kwargs) {
2994 VISIT(c, expr, kwargs);
2995 code |= 2;
2996 }
2997 switch (code) {
2998 case 0:
2999 ADDOP_I(c, CALL_FUNCTION, n);
3000 break;
3001 case 1:
3002 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3003 break;
3004 case 2:
3005 ADDOP_I(c, CALL_FUNCTION_KW, n);
3006 break;
3007 case 3:
3008 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3009 break;
3010 }
3011 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012}
3013
Nick Coghlan650f0d02007-04-15 12:05:43 +00003014
3015/* List and set comprehensions and generator expressions work by creating a
3016 nested function to perform the actual iteration. This means that the
3017 iteration variables don't leak into the current scope.
3018 The defined function is called immediately following its definition, with the
3019 result of that call being the result of the expression.
3020 The LC/SC version returns the populated container, while the GE version is
3021 flagged in symtable.c as a generator, so it returns the generator object
3022 when the function is called.
3023 This code *knows* that the loop cannot contain break, continue, or return,
3024 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3025
3026 Possible cleanups:
3027 - iterate over the generator sequence instead of using recursion
3028*/
3029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031compiler_comprehension_generator(struct compiler *c,
3032 asdl_seq *generators, int gen_index,
3033 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 /* generate code for the iterator, then each of the ifs,
3036 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 comprehension_ty gen;
3039 basicblock *start, *anchor, *skip, *if_cleanup;
3040 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 start = compiler_new_block(c);
3043 skip = compiler_new_block(c);
3044 if_cleanup = compiler_new_block(c);
3045 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3048 anchor == NULL)
3049 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 if (gen_index == 0) {
3054 /* Receive outermost iter as an implicit argument */
3055 c->u->u_argcount = 1;
3056 ADDOP_I(c, LOAD_FAST, 0);
3057 }
3058 else {
3059 /* Sub-iter - calculate on the fly */
3060 VISIT(c, expr, gen->iter);
3061 ADDOP(c, GET_ITER);
3062 }
3063 compiler_use_next_block(c, start);
3064 ADDOP_JREL(c, FOR_ITER, anchor);
3065 NEXT_BLOCK(c);
3066 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 /* XXX this needs to be cleaned up...a lot! */
3069 n = asdl_seq_LEN(gen->ifs);
3070 for (i = 0; i < n; i++) {
3071 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3072 VISIT(c, expr, e);
3073 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3074 NEXT_BLOCK(c);
3075 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 if (++gen_index < asdl_seq_LEN(generators))
3078 if (!compiler_comprehension_generator(c,
3079 generators, gen_index,
3080 elt, val, type))
3081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 /* only append after the last for generator */
3084 if (gen_index >= asdl_seq_LEN(generators)) {
3085 /* comprehension specific code */
3086 switch (type) {
3087 case COMP_GENEXP:
3088 VISIT(c, expr, elt);
3089 ADDOP(c, YIELD_VALUE);
3090 ADDOP(c, POP_TOP);
3091 break;
3092 case COMP_LISTCOMP:
3093 VISIT(c, expr, elt);
3094 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3095 break;
3096 case COMP_SETCOMP:
3097 VISIT(c, expr, elt);
3098 ADDOP_I(c, SET_ADD, gen_index + 1);
3099 break;
3100 case COMP_DICTCOMP:
3101 /* With 'd[k] = v', v is evaluated before k, so we do
3102 the same. */
3103 VISIT(c, expr, val);
3104 VISIT(c, expr, elt);
3105 ADDOP_I(c, MAP_ADD, gen_index + 1);
3106 break;
3107 default:
3108 return 0;
3109 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 compiler_use_next_block(c, skip);
3112 }
3113 compiler_use_next_block(c, if_cleanup);
3114 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3115 compiler_use_next_block(c, anchor);
3116
3117 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118}
3119
3120static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003121compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 PyCodeObject *co = NULL;
3125 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003126 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 outermost_iter = ((comprehension_ty)
3129 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003130
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003131 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3132 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 if (type != COMP_GENEXP) {
3136 int op;
3137 switch (type) {
3138 case COMP_LISTCOMP:
3139 op = BUILD_LIST;
3140 break;
3141 case COMP_SETCOMP:
3142 op = BUILD_SET;
3143 break;
3144 case COMP_DICTCOMP:
3145 op = BUILD_MAP;
3146 break;
3147 default:
3148 PyErr_Format(PyExc_SystemError,
3149 "unknown comprehension type %d", type);
3150 goto error_in_scope;
3151 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 ADDOP_I(c, op, 0);
3154 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 if (!compiler_comprehension_generator(c, generators, 0, elt,
3157 val, type))
3158 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 if (type != COMP_GENEXP) {
3161 ADDOP(c, RETURN_VALUE);
3162 }
3163
3164 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003165 qualname = c->u->u_qualname;
3166 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003168 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 goto error;
3170
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003171 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003173 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 Py_DECREF(co);
3175
3176 VISIT(c, expr, outermost_iter);
3177 ADDOP(c, GET_ITER);
3178 ADDOP_I(c, CALL_FUNCTION, 1);
3179 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003180error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003182error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003183 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 Py_XDECREF(co);
3185 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003186}
3187
3188static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189compiler_genexp(struct compiler *c, expr_ty e)
3190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 static identifier name;
3192 if (!name) {
3193 name = PyUnicode_FromString("<genexpr>");
3194 if (!name)
3195 return 0;
3196 }
3197 assert(e->kind == GeneratorExp_kind);
3198 return compiler_comprehension(c, e, COMP_GENEXP, name,
3199 e->v.GeneratorExp.generators,
3200 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201}
3202
3203static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003204compiler_listcomp(struct compiler *c, expr_ty e)
3205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 static identifier name;
3207 if (!name) {
3208 name = PyUnicode_FromString("<listcomp>");
3209 if (!name)
3210 return 0;
3211 }
3212 assert(e->kind == ListComp_kind);
3213 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3214 e->v.ListComp.generators,
3215 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003216}
3217
3218static int
3219compiler_setcomp(struct compiler *c, expr_ty e)
3220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 static identifier name;
3222 if (!name) {
3223 name = PyUnicode_FromString("<setcomp>");
3224 if (!name)
3225 return 0;
3226 }
3227 assert(e->kind == SetComp_kind);
3228 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3229 e->v.SetComp.generators,
3230 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003231}
3232
3233
3234static int
3235compiler_dictcomp(struct compiler *c, expr_ty e)
3236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 static identifier name;
3238 if (!name) {
3239 name = PyUnicode_FromString("<dictcomp>");
3240 if (!name)
3241 return 0;
3242 }
3243 assert(e->kind == DictComp_kind);
3244 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3245 e->v.DictComp.generators,
3246 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003247}
3248
3249
3250static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251compiler_visit_keyword(struct compiler *c, keyword_ty k)
3252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3254 VISIT(c, expr, k->value);
3255 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256}
3257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259 whether they are true or false.
3260
3261 Return values: 1 for true, 0 for false, -1 for non-constant.
3262 */
3263
3264static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003265expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 char *id;
3268 switch (e->kind) {
3269 case Ellipsis_kind:
3270 return 1;
3271 case Num_kind:
3272 return PyObject_IsTrue(e->v.Num.n);
3273 case Str_kind:
3274 return PyObject_IsTrue(e->v.Str.s);
3275 case Name_kind:
3276 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003277 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003278 if (id && strcmp(id, "__debug__") == 0)
3279 return !c->c_optimize;
3280 return -1;
3281 case NameConstant_kind: {
3282 PyObject *o = e->v.NameConstant.value;
3283 if (o == Py_None)
3284 return 0;
3285 else if (o == Py_True)
3286 return 1;
3287 else if (o == Py_False)
3288 return 0;
3289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 default:
3291 return -1;
3292 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293}
3294
Guido van Rossumc2e20742006-02-27 22:32:47 +00003295/*
3296 Implements the with statement from PEP 343.
3297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003299
3300 with EXPR as VAR:
3301 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302
Guido van Rossumc2e20742006-02-27 22:32:47 +00003303 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304
Thomas Wouters477c8d52006-05-27 19:21:47 +00003305 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003306 exit = context.__exit__ # not calling it
3307 value = context.__enter__()
3308 try:
3309 VAR = value # if VAR present in the syntax
3310 BLOCK
3311 finally:
3312 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003314 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003316 exit(*exc)
3317 */
3318static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003319compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003320{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003321 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003322 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003323
3324 assert(s->kind == With_kind);
3325
Guido van Rossumc2e20742006-02-27 22:32:47 +00003326 block = compiler_new_block(c);
3327 finally = compiler_new_block(c);
3328 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003329 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003330
Thomas Wouters477c8d52006-05-27 19:21:47 +00003331 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003332 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003333 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003334
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003335 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003336 compiler_use_next_block(c, block);
3337 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003338 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003339 }
3340
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003341 if (item->optional_vars) {
3342 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003343 }
3344 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003346 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003347 }
3348
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003349 pos++;
3350 if (pos == asdl_seq_LEN(s->v.With.items))
3351 /* BLOCK code */
3352 VISIT_SEQ(c, stmt, s->v.With.body)
3353 else if (!compiler_with(c, s, pos))
3354 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003355
3356 /* End of try block; start the finally block */
3357 ADDOP(c, POP_BLOCK);
3358 compiler_pop_fblock(c, FINALLY_TRY, block);
3359
3360 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3361 compiler_use_next_block(c, finally);
3362 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003363 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003364
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003365 /* Finally block starts; context.__exit__ is on the stack under
3366 the exception or return information. Just issue our magic
3367 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003368 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003369
3370 /* Finally block ends. */
3371 ADDOP(c, END_FINALLY);
3372 compiler_pop_fblock(c, FINALLY_END, finally);
3373 return 1;
3374}
3375
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003376static int
3377compiler_visit_expr(struct compiler *c, expr_ty e)
3378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 /* If expr e has a different line number than the last expr/stmt,
3382 set a new line number for the next instruction.
3383 */
3384 if (e->lineno > c->u->u_lineno) {
3385 c->u->u_lineno = e->lineno;
3386 c->u->u_lineno_set = 0;
3387 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003388 /* Updating the column offset is always harmless. */
3389 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 switch (e->kind) {
3391 case BoolOp_kind:
3392 return compiler_boolop(c, e);
3393 case BinOp_kind:
3394 VISIT(c, expr, e->v.BinOp.left);
3395 VISIT(c, expr, e->v.BinOp.right);
3396 ADDOP(c, binop(c, e->v.BinOp.op));
3397 break;
3398 case UnaryOp_kind:
3399 VISIT(c, expr, e->v.UnaryOp.operand);
3400 ADDOP(c, unaryop(e->v.UnaryOp.op));
3401 break;
3402 case Lambda_kind:
3403 return compiler_lambda(c, e);
3404 case IfExp_kind:
3405 return compiler_ifexp(c, e);
3406 case Dict_kind:
3407 n = asdl_seq_LEN(e->v.Dict.values);
3408 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3409 for (i = 0; i < n; i++) {
3410 VISIT(c, expr,
3411 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3412 VISIT(c, expr,
3413 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3414 ADDOP(c, STORE_MAP);
3415 }
3416 break;
3417 case Set_kind:
3418 n = asdl_seq_LEN(e->v.Set.elts);
3419 VISIT_SEQ(c, expr, e->v.Set.elts);
3420 ADDOP_I(c, BUILD_SET, n);
3421 break;
3422 case GeneratorExp_kind:
3423 return compiler_genexp(c, e);
3424 case ListComp_kind:
3425 return compiler_listcomp(c, e);
3426 case SetComp_kind:
3427 return compiler_setcomp(c, e);
3428 case DictComp_kind:
3429 return compiler_dictcomp(c, e);
3430 case Yield_kind:
3431 if (c->u->u_ste->ste_type != FunctionBlock)
3432 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003433 if (e->v.Yield.value) {
3434 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 }
3436 else {
3437 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3438 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003439 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003441 case YieldFrom_kind:
3442 if (c->u->u_ste->ste_type != FunctionBlock)
3443 return compiler_error(c, "'yield' outside function");
3444 VISIT(c, expr, e->v.YieldFrom.value);
3445 ADDOP(c, GET_ITER);
3446 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3447 ADDOP(c, YIELD_FROM);
3448 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 case Compare_kind:
3450 return compiler_compare(c, e);
3451 case Call_kind:
3452 return compiler_call(c, e);
3453 case Num_kind:
3454 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3455 break;
3456 case Str_kind:
3457 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3458 break;
3459 case Bytes_kind:
3460 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3461 break;
3462 case Ellipsis_kind:
3463 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3464 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003465 case NameConstant_kind:
3466 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3467 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 /* The following exprs can be assignment targets. */
3469 case Attribute_kind:
3470 if (e->v.Attribute.ctx != AugStore)
3471 VISIT(c, expr, e->v.Attribute.value);
3472 switch (e->v.Attribute.ctx) {
3473 case AugLoad:
3474 ADDOP(c, DUP_TOP);
3475 /* Fall through to load */
3476 case Load:
3477 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3478 break;
3479 case AugStore:
3480 ADDOP(c, ROT_TWO);
3481 /* Fall through to save */
3482 case Store:
3483 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3484 break;
3485 case Del:
3486 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3487 break;
3488 case Param:
3489 default:
3490 PyErr_SetString(PyExc_SystemError,
3491 "param invalid in attribute expression");
3492 return 0;
3493 }
3494 break;
3495 case Subscript_kind:
3496 switch (e->v.Subscript.ctx) {
3497 case AugLoad:
3498 VISIT(c, expr, e->v.Subscript.value);
3499 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3500 break;
3501 case Load:
3502 VISIT(c, expr, e->v.Subscript.value);
3503 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3504 break;
3505 case AugStore:
3506 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3507 break;
3508 case Store:
3509 VISIT(c, expr, e->v.Subscript.value);
3510 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3511 break;
3512 case Del:
3513 VISIT(c, expr, e->v.Subscript.value);
3514 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3515 break;
3516 case Param:
3517 default:
3518 PyErr_SetString(PyExc_SystemError,
3519 "param invalid in subscript expression");
3520 return 0;
3521 }
3522 break;
3523 case Starred_kind:
3524 switch (e->v.Starred.ctx) {
3525 case Store:
3526 /* In all legitimate cases, the Starred node was already replaced
3527 * by compiler_list/compiler_tuple. XXX: is that okay? */
3528 return compiler_error(c,
3529 "starred assignment target must be in a list or tuple");
3530 default:
3531 return compiler_error(c,
3532 "can use starred expression only as assignment target");
3533 }
3534 break;
3535 case Name_kind:
3536 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3537 /* child nodes of List and Tuple will have expr_context set */
3538 case List_kind:
3539 return compiler_list(c, e);
3540 case Tuple_kind:
3541 return compiler_tuple(c, e);
3542 }
3543 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544}
3545
3546static int
3547compiler_augassign(struct compiler *c, stmt_ty s)
3548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 expr_ty e = s->v.AugAssign.target;
3550 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 switch (e->kind) {
3555 case Attribute_kind:
3556 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3557 AugLoad, e->lineno, e->col_offset, c->c_arena);
3558 if (auge == NULL)
3559 return 0;
3560 VISIT(c, expr, auge);
3561 VISIT(c, expr, s->v.AugAssign.value);
3562 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3563 auge->v.Attribute.ctx = AugStore;
3564 VISIT(c, expr, auge);
3565 break;
3566 case Subscript_kind:
3567 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3568 AugLoad, e->lineno, e->col_offset, c->c_arena);
3569 if (auge == NULL)
3570 return 0;
3571 VISIT(c, expr, auge);
3572 VISIT(c, expr, s->v.AugAssign.value);
3573 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3574 auge->v.Subscript.ctx = AugStore;
3575 VISIT(c, expr, auge);
3576 break;
3577 case Name_kind:
3578 if (!compiler_nameop(c, e->v.Name.id, Load))
3579 return 0;
3580 VISIT(c, expr, s->v.AugAssign.value);
3581 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3582 return compiler_nameop(c, e->v.Name.id, Store);
3583 default:
3584 PyErr_Format(PyExc_SystemError,
3585 "invalid node type (%d) for augmented assignment",
3586 e->kind);
3587 return 0;
3588 }
3589 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590}
3591
3592static int
3593compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 struct fblockinfo *f;
3596 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3597 PyErr_SetString(PyExc_SystemError,
3598 "too many statically nested blocks");
3599 return 0;
3600 }
3601 f = &c->u->u_fblock[c->u->u_nfblocks++];
3602 f->fb_type = t;
3603 f->fb_block = b;
3604 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605}
3606
3607static void
3608compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 struct compiler_unit *u = c->u;
3611 assert(u->u_nfblocks > 0);
3612 u->u_nfblocks--;
3613 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3614 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615}
3616
Thomas Wouters89f507f2006-12-13 04:49:30 +00003617static int
3618compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 int i;
3620 struct compiler_unit *u = c->u;
3621 for (i = 0; i < u->u_nfblocks; ++i) {
3622 if (u->u_fblock[i].fb_type == LOOP)
3623 return 1;
3624 }
3625 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003626}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627/* Raises a SyntaxError and returns 0.
3628 If something goes wrong, a different exception may be raised.
3629*/
3630
3631static int
3632compiler_error(struct compiler *c, const char *errstr)
3633{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003634 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636
Victor Stinner14e461d2013-08-26 22:28:21 +02003637 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 if (!loc) {
3639 Py_INCREF(Py_None);
3640 loc = Py_None;
3641 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003642 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003643 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 if (!u)
3645 goto exit;
3646 v = Py_BuildValue("(zO)", errstr, u);
3647 if (!v)
3648 goto exit;
3649 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 Py_DECREF(loc);
3652 Py_XDECREF(u);
3653 Py_XDECREF(v);
3654 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655}
3656
3657static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658compiler_handle_subscr(struct compiler *c, const char *kind,
3659 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 /* XXX this code is duplicated */
3664 switch (ctx) {
3665 case AugLoad: /* fall through to Load */
3666 case Load: op = BINARY_SUBSCR; break;
3667 case AugStore:/* fall through to Store */
3668 case Store: op = STORE_SUBSCR; break;
3669 case Del: op = DELETE_SUBSCR; break;
3670 case Param:
3671 PyErr_Format(PyExc_SystemError,
3672 "invalid %s kind %d in subscript\n",
3673 kind, ctx);
3674 return 0;
3675 }
3676 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003677 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 }
3679 else if (ctx == AugStore) {
3680 ADDOP(c, ROT_THREE);
3681 }
3682 ADDOP(c, op);
3683 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684}
3685
3686static int
3687compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 int n = 2;
3690 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 /* only handles the cases where BUILD_SLICE is emitted */
3693 if (s->v.Slice.lower) {
3694 VISIT(c, expr, s->v.Slice.lower);
3695 }
3696 else {
3697 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3698 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 if (s->v.Slice.upper) {
3701 VISIT(c, expr, s->v.Slice.upper);
3702 }
3703 else {
3704 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3705 }
3706
3707 if (s->v.Slice.step) {
3708 n++;
3709 VISIT(c, expr, s->v.Slice.step);
3710 }
3711 ADDOP_I(c, BUILD_SLICE, n);
3712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713}
3714
3715static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3717 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 switch (s->kind) {
3720 case Slice_kind:
3721 return compiler_slice(c, s, ctx);
3722 case Index_kind:
3723 VISIT(c, expr, s->v.Index.value);
3724 break;
3725 case ExtSlice_kind:
3726 default:
3727 PyErr_SetString(PyExc_SystemError,
3728 "extended slice invalid in nested slice");
3729 return 0;
3730 }
3731 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003732}
3733
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734static int
3735compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 char * kindname = NULL;
3738 switch (s->kind) {
3739 case Index_kind:
3740 kindname = "index";
3741 if (ctx != AugStore) {
3742 VISIT(c, expr, s->v.Index.value);
3743 }
3744 break;
3745 case Slice_kind:
3746 kindname = "slice";
3747 if (ctx != AugStore) {
3748 if (!compiler_slice(c, s, ctx))
3749 return 0;
3750 }
3751 break;
3752 case ExtSlice_kind:
3753 kindname = "extended slice";
3754 if (ctx != AugStore) {
3755 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3756 for (i = 0; i < n; i++) {
3757 slice_ty sub = (slice_ty)asdl_seq_GET(
3758 s->v.ExtSlice.dims, i);
3759 if (!compiler_visit_nested_slice(c, sub, ctx))
3760 return 0;
3761 }
3762 ADDOP_I(c, BUILD_TUPLE, n);
3763 }
3764 break;
3765 default:
3766 PyErr_Format(PyExc_SystemError,
3767 "invalid subscript kind %d", s->kind);
3768 return 0;
3769 }
3770 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771}
3772
Thomas Wouters89f507f2006-12-13 04:49:30 +00003773/* End of the compiler section, beginning of the assembler section */
3774
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775/* do depth-first search of basic block graph, starting with block.
3776 post records the block indices in post-order.
3777
3778 XXX must handle implicit jumps from one block to next
3779*/
3780
Thomas Wouters89f507f2006-12-13 04:49:30 +00003781struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 PyObject *a_bytecode; /* string containing bytecode */
3783 int a_offset; /* offset into bytecode */
3784 int a_nblocks; /* number of reachable blocks */
3785 basicblock **a_postorder; /* list of blocks in dfs postorder */
3786 PyObject *a_lnotab; /* string containing lnotab */
3787 int a_lnotab_off; /* offset into lnotab */
3788 int a_lineno; /* last lineno of emitted instruction */
3789 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003790};
3791
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792static void
3793dfs(struct compiler *c, basicblock *b, struct assembler *a)
3794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 int i;
3796 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 if (b->b_seen)
3799 return;
3800 b->b_seen = 1;
3801 if (b->b_next != NULL)
3802 dfs(c, b->b_next, a);
3803 for (i = 0; i < b->b_iused; i++) {
3804 instr = &b->b_instr[i];
3805 if (instr->i_jrel || instr->i_jabs)
3806 dfs(c, instr->i_target, a);
3807 }
3808 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809}
3810
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003811static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 int i, target_depth;
3815 struct instr *instr;
3816 if (b->b_seen || b->b_startdepth >= depth)
3817 return maxdepth;
3818 b->b_seen = 1;
3819 b->b_startdepth = depth;
3820 for (i = 0; i < b->b_iused; i++) {
3821 instr = &b->b_instr[i];
3822 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3823 if (depth > maxdepth)
3824 maxdepth = depth;
3825 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3826 if (instr->i_jrel || instr->i_jabs) {
3827 target_depth = depth;
3828 if (instr->i_opcode == FOR_ITER) {
3829 target_depth = depth-2;
3830 } else if (instr->i_opcode == SETUP_FINALLY ||
3831 instr->i_opcode == SETUP_EXCEPT) {
3832 target_depth = depth+3;
3833 if (target_depth > maxdepth)
3834 maxdepth = target_depth;
3835 }
3836 maxdepth = stackdepth_walk(c, instr->i_target,
3837 target_depth, maxdepth);
3838 if (instr->i_opcode == JUMP_ABSOLUTE ||
3839 instr->i_opcode == JUMP_FORWARD) {
3840 goto out; /* remaining code is dead */
3841 }
3842 }
3843 }
3844 if (b->b_next)
3845 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 b->b_seen = 0;
3848 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849}
3850
3851/* Find the flow path that needs the largest stack. We assume that
3852 * cycles in the flow graph have no net effect on the stack depth.
3853 */
3854static int
3855stackdepth(struct compiler *c)
3856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 basicblock *b, *entryblock;
3858 entryblock = NULL;
3859 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3860 b->b_seen = 0;
3861 b->b_startdepth = INT_MIN;
3862 entryblock = b;
3863 }
3864 if (!entryblock)
3865 return 0;
3866 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867}
3868
3869static int
3870assemble_init(struct assembler *a, int nblocks, int firstlineno)
3871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 memset(a, 0, sizeof(struct assembler));
3873 a->a_lineno = firstlineno;
3874 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3875 if (!a->a_bytecode)
3876 return 0;
3877 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3878 if (!a->a_lnotab)
3879 return 0;
3880 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3881 PyErr_NoMemory();
3882 return 0;
3883 }
3884 a->a_postorder = (basicblock **)PyObject_Malloc(
3885 sizeof(basicblock *) * nblocks);
3886 if (!a->a_postorder) {
3887 PyErr_NoMemory();
3888 return 0;
3889 }
3890 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891}
3892
3893static void
3894assemble_free(struct assembler *a)
3895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 Py_XDECREF(a->a_bytecode);
3897 Py_XDECREF(a->a_lnotab);
3898 if (a->a_postorder)
3899 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900}
3901
3902/* Return the size of a basic block in bytes. */
3903
3904static int
3905instrsize(struct instr *instr)
3906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 if (!instr->i_hasarg)
3908 return 1; /* 1 byte for the opcode*/
3909 if (instr->i_oparg > 0xffff)
3910 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3911 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003912}
3913
3914static int
3915blocksize(basicblock *b)
3916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 int i;
3918 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 for (i = 0; i < b->b_iused; i++)
3921 size += instrsize(&b->b_instr[i]);
3922 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923}
3924
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003925/* Appends a pair to the end of the line number table, a_lnotab, representing
3926 the instruction's bytecode offset and line number. See
3927 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003928
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003929static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 int d_bytecode, d_lineno;
3933 int len;
3934 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 d_bytecode = a->a_offset - a->a_lineno_off;
3937 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 assert(d_bytecode >= 0);
3940 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 if(d_bytecode == 0 && d_lineno == 0)
3943 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 if (d_bytecode > 255) {
3946 int j, nbytes, ncodes = d_bytecode / 255;
3947 nbytes = a->a_lnotab_off + 2 * ncodes;
3948 len = PyBytes_GET_SIZE(a->a_lnotab);
3949 if (nbytes >= len) {
3950 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3951 len = nbytes;
3952 else if (len <= INT_MAX / 2)
3953 len *= 2;
3954 else {
3955 PyErr_NoMemory();
3956 return 0;
3957 }
3958 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3959 return 0;
3960 }
3961 lnotab = (unsigned char *)
3962 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3963 for (j = 0; j < ncodes; j++) {
3964 *lnotab++ = 255;
3965 *lnotab++ = 0;
3966 }
3967 d_bytecode -= ncodes * 255;
3968 a->a_lnotab_off += ncodes * 2;
3969 }
3970 assert(d_bytecode <= 255);
3971 if (d_lineno > 255) {
3972 int j, nbytes, ncodes = d_lineno / 255;
3973 nbytes = a->a_lnotab_off + 2 * ncodes;
3974 len = PyBytes_GET_SIZE(a->a_lnotab);
3975 if (nbytes >= len) {
3976 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3977 len = nbytes;
3978 else if (len <= INT_MAX / 2)
3979 len *= 2;
3980 else {
3981 PyErr_NoMemory();
3982 return 0;
3983 }
3984 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3985 return 0;
3986 }
3987 lnotab = (unsigned char *)
3988 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3989 *lnotab++ = d_bytecode;
3990 *lnotab++ = 255;
3991 d_bytecode = 0;
3992 for (j = 1; j < ncodes; j++) {
3993 *lnotab++ = 0;
3994 *lnotab++ = 255;
3995 }
3996 d_lineno -= ncodes * 255;
3997 a->a_lnotab_off += ncodes * 2;
3998 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 len = PyBytes_GET_SIZE(a->a_lnotab);
4001 if (a->a_lnotab_off + 2 >= len) {
4002 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4003 return 0;
4004 }
4005 lnotab = (unsigned char *)
4006 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 a->a_lnotab_off += 2;
4009 if (d_bytecode) {
4010 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004011 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 }
4013 else { /* First line of a block; def stmt, etc. */
4014 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004015 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 }
4017 a->a_lineno = i->i_lineno;
4018 a->a_lineno_off = a->a_offset;
4019 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004020}
4021
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004022/* assemble_emit()
4023 Extend the bytecode with a new instruction.
4024 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004025*/
4026
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004027static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 int size, arg = 0, ext = 0;
4031 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4032 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 size = instrsize(i);
4035 if (i->i_hasarg) {
4036 arg = i->i_oparg;
4037 ext = arg >> 16;
4038 }
4039 if (i->i_lineno && !assemble_lnotab(a, i))
4040 return 0;
4041 if (a->a_offset + size >= len) {
4042 if (len > PY_SSIZE_T_MAX / 2)
4043 return 0;
4044 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4045 return 0;
4046 }
4047 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4048 a->a_offset += size;
4049 if (size == 6) {
4050 assert(i->i_hasarg);
4051 *code++ = (char)EXTENDED_ARG;
4052 *code++ = ext & 0xff;
4053 *code++ = ext >> 8;
4054 arg &= 0xffff;
4055 }
4056 *code++ = i->i_opcode;
4057 if (i->i_hasarg) {
4058 assert(size == 3 || size == 6);
4059 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004060 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 }
4062 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004063}
4064
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004065static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 basicblock *b;
4069 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4070 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 /* Compute the size of each block and fixup jump args.
4073 Replace block pointer with position in bytecode. */
4074 do {
4075 totsize = 0;
4076 for (i = a->a_nblocks - 1; i >= 0; i--) {
4077 b = a->a_postorder[i];
4078 bsize = blocksize(b);
4079 b->b_offset = totsize;
4080 totsize += bsize;
4081 }
4082 last_extended_arg_count = extended_arg_count;
4083 extended_arg_count = 0;
4084 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4085 bsize = b->b_offset;
4086 for (i = 0; i < b->b_iused; i++) {
4087 struct instr *instr = &b->b_instr[i];
4088 /* Relative jumps are computed relative to
4089 the instruction pointer after fetching
4090 the jump instruction.
4091 */
4092 bsize += instrsize(instr);
4093 if (instr->i_jabs)
4094 instr->i_oparg = instr->i_target->b_offset;
4095 else if (instr->i_jrel) {
4096 int delta = instr->i_target->b_offset - bsize;
4097 instr->i_oparg = delta;
4098 }
4099 else
4100 continue;
4101 if (instr->i_oparg > 0xffff)
4102 extended_arg_count++;
4103 }
4104 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 /* XXX: This is an awful hack that could hurt performance, but
4107 on the bright side it should work until we come up
4108 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 The issue is that in the first loop blocksize() is called
4111 which calls instrsize() which requires i_oparg be set
4112 appropriately. There is a bootstrap problem because
4113 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 So we loop until we stop seeing new EXTENDED_ARGs.
4116 The only EXTENDED_ARGs that could be popping up are
4117 ones in jump instructions. So this should converge
4118 fairly quickly.
4119 */
4120 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004121}
4122
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004123static PyObject *
4124dict_keys_inorder(PyObject *dict, int offset)
4125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 PyObject *tuple, *k, *v;
4127 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 tuple = PyTuple_New(size);
4130 if (tuple == NULL)
4131 return NULL;
4132 while (PyDict_Next(dict, &pos, &k, &v)) {
4133 i = PyLong_AS_LONG(v);
4134 /* The keys of the dictionary are tuples. (see compiler_add_o)
4135 The object we want is always first, though. */
4136 k = PyTuple_GET_ITEM(k, 0);
4137 Py_INCREF(k);
4138 assert((i - offset) < size);
4139 assert((i - offset) >= 0);
4140 PyTuple_SET_ITEM(tuple, i - offset, k);
4141 }
4142 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004143}
4144
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004145static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 PySTEntryObject *ste = c->u->u_ste;
4149 int flags = 0, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004151 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 if (!ste->ste_unoptimized)
4153 flags |= CO_OPTIMIZED;
4154 if (ste->ste_nested)
4155 flags |= CO_NESTED;
4156 if (ste->ste_generator)
4157 flags |= CO_GENERATOR;
4158 if (ste->ste_varargs)
4159 flags |= CO_VARARGS;
4160 if (ste->ste_varkeywords)
4161 flags |= CO_VARKEYWORDS;
4162 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 /* (Only) inherit compilerflags in PyCF_MASK */
4165 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 n = PyDict_Size(c->u->u_freevars);
4168 if (n < 0)
4169 return -1;
4170 if (n == 0) {
4171 n = PyDict_Size(c->u->u_cellvars);
4172 if (n < 0)
4173 return -1;
4174 if (n == 0) {
4175 flags |= CO_NOFREE;
4176 }
4177 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004180}
4181
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004182static PyCodeObject *
4183makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 PyObject *tmp;
4186 PyCodeObject *co = NULL;
4187 PyObject *consts = NULL;
4188 PyObject *names = NULL;
4189 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 PyObject *name = NULL;
4191 PyObject *freevars = NULL;
4192 PyObject *cellvars = NULL;
4193 PyObject *bytecode = NULL;
4194 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 tmp = dict_keys_inorder(c->u->u_consts, 0);
4197 if (!tmp)
4198 goto error;
4199 consts = PySequence_List(tmp); /* optimize_code requires a list */
4200 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 names = dict_keys_inorder(c->u->u_names, 0);
4203 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4204 if (!consts || !names || !varnames)
4205 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4208 if (!cellvars)
4209 goto error;
4210 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4211 if (!freevars)
4212 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 nlocals = PyDict_Size(c->u->u_varnames);
4214 flags = compute_code_flags(c);
4215 if (flags < 0)
4216 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4219 if (!bytecode)
4220 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4223 if (!tmp)
4224 goto error;
4225 Py_DECREF(consts);
4226 consts = tmp;
4227
4228 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4229 nlocals, stackdepth(c), flags,
4230 bytecode, consts, names, varnames,
4231 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004232 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 c->u->u_firstlineno,
4234 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004235 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 Py_XDECREF(consts);
4237 Py_XDECREF(names);
4238 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 Py_XDECREF(name);
4240 Py_XDECREF(freevars);
4241 Py_XDECREF(cellvars);
4242 Py_XDECREF(bytecode);
4243 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004244}
4245
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004246
4247/* For debugging purposes only */
4248#if 0
4249static void
4250dump_instr(const struct instr *i)
4251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 const char *jrel = i->i_jrel ? "jrel " : "";
4253 const char *jabs = i->i_jabs ? "jabs " : "";
4254 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 *arg = '\0';
4257 if (i->i_hasarg)
4258 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4261 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004262}
4263
4264static void
4265dump_basicblock(const basicblock *b)
4266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 const char *seen = b->b_seen ? "seen " : "";
4268 const char *b_return = b->b_return ? "return " : "";
4269 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4270 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4271 if (b->b_instr) {
4272 int i;
4273 for (i = 0; i < b->b_iused; i++) {
4274 fprintf(stderr, " [%02d] ", i);
4275 dump_instr(b->b_instr + i);
4276 }
4277 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004278}
4279#endif
4280
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004281static PyCodeObject *
4282assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 basicblock *b, *entryblock;
4285 struct assembler a;
4286 int i, j, nblocks;
4287 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 /* Make sure every block that falls off the end returns None.
4290 XXX NEXT_BLOCK() isn't quite right, because if the last
4291 block ends with a jump or return b_next shouldn't set.
4292 */
4293 if (!c->u->u_curblock->b_return) {
4294 NEXT_BLOCK(c);
4295 if (addNone)
4296 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4297 ADDOP(c, RETURN_VALUE);
4298 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 nblocks = 0;
4301 entryblock = NULL;
4302 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4303 nblocks++;
4304 entryblock = b;
4305 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 /* Set firstlineno if it wasn't explicitly set. */
4308 if (!c->u->u_firstlineno) {
4309 if (entryblock && entryblock->b_instr)
4310 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4311 else
4312 c->u->u_firstlineno = 1;
4313 }
4314 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4315 goto error;
4316 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 /* Can't modify the bytecode after computing jump offsets. */
4319 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 /* Emit code in reverse postorder from dfs. */
4322 for (i = a.a_nblocks - 1; i >= 0; i--) {
4323 b = a.a_postorder[i];
4324 for (j = 0; j < b->b_iused; j++)
4325 if (!assemble_emit(&a, &b->b_instr[j]))
4326 goto error;
4327 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4330 goto error;
4331 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4332 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004335 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 assemble_free(&a);
4337 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004338}
Georg Brandl8334fd92010-12-04 10:26:46 +00004339
4340#undef PyAST_Compile
4341PyAPI_FUNC(PyCodeObject *)
4342PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4343 PyArena *arena)
4344{
4345 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4346}
4347
4348