blob: b07c15647e4f432c5355c236dec98f2875b99de9 [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
Victor Stinnerf8e32212013-11-19 23:56:34 +0100123 Py_ssize_t u_argcount; /* number of arguments for block */
124 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 /* 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 *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100173static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static 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);
Victor Stinnerad9a0662013-11-19 22:23:20 +0100198static int compiler_call_helper(struct compiler *c, Py_ssize_t 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++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100391 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 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 *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100419dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000420{
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) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100453 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 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{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100638 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 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
Larry Hastings3a907972013-11-23 14:49:22 -0800856int
857PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858{
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:
Larry Hastings3a907972013-11-23 14:49:22 -08001047 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 }
Larry Hastings3a907972013-11-23 14:49:22 -08001049 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050}
1051
1052/* Add an opcode with no argument.
1053 Returns 0 on failure, 1 on success.
1054*/
1055
1056static int
1057compiler_addop(struct compiler *c, int opcode)
1058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 basicblock *b;
1060 struct instr *i;
1061 int off;
1062 off = compiler_next_instr(c, c->u->u_curblock);
1063 if (off < 0)
1064 return 0;
1065 b = c->u->u_curblock;
1066 i = &b->b_instr[off];
1067 i->i_opcode = opcode;
1068 i->i_hasarg = 0;
1069 if (opcode == RETURN_VALUE)
1070 b->b_return = 1;
1071 compiler_set_lineno(c, off);
1072 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
Victor Stinnerf8e32212013-11-19 23:56:34 +01001075static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyObject *t, *v;
1079 Py_ssize_t arg;
1080 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081
Serhiy Storchaka95949422013-08-27 19:40:23 +03001082 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1084 if (PyFloat_Check(o)) {
1085 d = PyFloat_AS_DOUBLE(o);
1086 /* all we need is to make the tuple different in either the 0.0
1087 * or -0.0 case from all others, just to avoid the "coercion".
1088 */
1089 if (d == 0.0 && copysign(1.0, d) < 0.0)
1090 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1091 else
1092 t = PyTuple_Pack(2, o, o->ob_type);
1093 }
1094 else if (PyComplex_Check(o)) {
1095 Py_complex z;
1096 int real_negzero, imag_negzero;
1097 /* For the complex case we must make complex(x, 0.)
1098 different from complex(x, -0.) and complex(0., y)
1099 different from complex(-0., y), for any x and y.
1100 All four complex zeros must be distinguished.*/
1101 z = PyComplex_AsCComplex(o);
1102 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1103 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1104 if (real_negzero && imag_negzero) {
1105 t = PyTuple_Pack(5, o, o->ob_type,
1106 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001107 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 else if (imag_negzero) {
1109 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 else if (real_negzero) {
1112 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1113 }
1114 else {
1115 t = PyTuple_Pack(2, o, o->ob_type);
1116 }
1117 }
1118 else {
1119 t = PyTuple_Pack(2, o, o->ob_type);
1120 }
1121 if (t == NULL)
1122 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 v = PyDict_GetItem(dict, t);
1125 if (!v) {
1126 if (PyErr_Occurred())
1127 return -1;
1128 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001129 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (!v) {
1131 Py_DECREF(t);
1132 return -1;
1133 }
1134 if (PyDict_SetItem(dict, t, v) < 0) {
1135 Py_DECREF(t);
1136 Py_DECREF(v);
1137 return -1;
1138 }
1139 Py_DECREF(v);
1140 }
1141 else
1142 arg = PyLong_AsLong(v);
1143 Py_DECREF(t);
1144 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145}
1146
1147static int
1148compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001151 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return compiler_addop_i(c, opcode, arg);
1155}
1156
1157static int
1158compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001161 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1163 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 arg = compiler_add_o(c, dict, mangled);
1166 Py_DECREF(mangled);
1167 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001168 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 return compiler_addop_i(c, opcode, arg);
1170}
1171
1172/* Add an opcode with an integer argument.
1173 Returns 0 on failure, 1 on success.
1174*/
1175
1176static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001177compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 struct instr *i;
1180 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001181
1182 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1183 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001184 assert((-2147483647-1) <= oparg);
1185 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 off = compiler_next_instr(c, c->u->u_curblock);
1188 if (off < 0)
1189 return 0;
1190 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001191 i->i_opcode = opcode;
1192 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 i->i_hasarg = 1;
1194 compiler_set_lineno(c, off);
1195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198static int
1199compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 struct instr *i;
1202 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 assert(b != NULL);
1205 off = compiler_next_instr(c, c->u->u_curblock);
1206 if (off < 0)
1207 return 0;
1208 i = &c->u->u_curblock->b_instr[off];
1209 i->i_opcode = opcode;
1210 i->i_target = b;
1211 i->i_hasarg = 1;
1212 if (absolute)
1213 i->i_jabs = 1;
1214 else
1215 i->i_jrel = 1;
1216 compiler_set_lineno(c, off);
1217 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1221 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 it as the current block. NEXT_BLOCK() also creates an implicit jump
1223 from the current block to the new block.
1224*/
1225
Thomas Wouters89f507f2006-12-13 04:49:30 +00001226/* The returns inside these macros make it impossible to decref objects
1227 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228*/
1229
1230
1231#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (compiler_use_new_block((C)) == NULL) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
1236#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (compiler_next_block((C)) == NULL) \
1238 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001239}
1240
1241#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (!compiler_addop((C), (OP))) \
1243 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244}
1245
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001246#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (!compiler_addop((C), (OP))) { \
1248 compiler_exit_scope(c); \
1249 return 0; \
1250 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001251}
1252
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1255 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256}
1257
1258#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1260 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261}
1262
1263#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_addop_i((C), (OP), (O))) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (!compiler_addop_j((C), (OP), (O), 1)) \
1270 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
1273#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (!compiler_addop_j((C), (OP), (O), 0)) \
1275 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
1278/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1279 the ASDL name to synthesize the name of the C type and the visit function.
1280*/
1281
1282#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (!compiler_visit_ ## TYPE((C), (V))) \
1284 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285}
1286
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001287#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (!compiler_visit_ ## TYPE((C), (V))) { \
1289 compiler_exit_scope(c); \
1290 return 0; \
1291 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001292}
1293
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001294#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!compiler_visit_slice((C), (V), (CTX))) \
1296 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
1299#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 int _i; \
1301 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1302 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1303 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1304 if (!compiler_visit_ ## TYPE((C), elt)) \
1305 return 0; \
1306 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307}
1308
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001309#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 int _i; \
1311 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1312 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1313 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1314 if (!compiler_visit_ ## TYPE((C), elt)) { \
1315 compiler_exit_scope(c); \
1316 return 0; \
1317 } \
1318 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001319}
1320
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321static int
1322compiler_isdocstring(stmt_ty s)
1323{
1324 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326 return s->v.Expr.value->kind == Str_kind;
1327}
1328
1329/* Compile a sequence of statements, checking for a docstring. */
1330
1331static int
1332compiler_body(struct compiler *c, asdl_seq *stmts)
1333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 int i = 0;
1335 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 if (!asdl_seq_LEN(stmts))
1338 return 1;
1339 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001340 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /* don't generate docstrings if -OO */
1342 i = 1;
1343 VISIT(c, expr, st->v.Expr.value);
1344 if (!compiler_nameop(c, __doc__, Store))
1345 return 0;
1346 }
1347 for (; i < asdl_seq_LEN(stmts); i++)
1348 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1349 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350}
1351
1352static PyCodeObject *
1353compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyCodeObject *co;
1356 int addNone = 1;
1357 static PyObject *module;
1358 if (!module) {
1359 module = PyUnicode_InternFromString("<module>");
1360 if (!module)
1361 return NULL;
1362 }
1363 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001364 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 return NULL;
1366 switch (mod->kind) {
1367 case Module_kind:
1368 if (!compiler_body(c, mod->v.Module.body)) {
1369 compiler_exit_scope(c);
1370 return 0;
1371 }
1372 break;
1373 case Interactive_kind:
1374 c->c_interactive = 1;
1375 VISIT_SEQ_IN_SCOPE(c, stmt,
1376 mod->v.Interactive.body);
1377 break;
1378 case Expression_kind:
1379 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1380 addNone = 0;
1381 break;
1382 case Suite_kind:
1383 PyErr_SetString(PyExc_SystemError,
1384 "suite should not be possible");
1385 return 0;
1386 default:
1387 PyErr_Format(PyExc_SystemError,
1388 "module kind %d should not be possible",
1389 mod->kind);
1390 return 0;
1391 }
1392 co = assemble(c, addNone);
1393 compiler_exit_scope(c);
1394 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001395}
1396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397/* The test for LOCAL must come before the test for FREE in order to
1398 handle classes where name is both local and free. The local var is
1399 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001400*/
1401
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402static int
1403get_ref_type(struct compiler *c, PyObject *name)
1404{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001405 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001406 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1407 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1408 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001409 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (scope == 0) {
1411 char buf[350];
1412 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001413 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchaka81f68a72014-11-19 00:08:38 +02001415 PyUnicode_AsUTF8(name),
1416 PyUnicode_AsUTF8(c->u->u_name),
1417 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1418 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1419 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1420 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 );
1422 Py_FatalError(buf);
1423 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426}
1427
1428static int
1429compiler_lookup_arg(PyObject *dict, PyObject *name)
1430{
1431 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001432 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001434 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001436 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001438 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001439 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
1442static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001443compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001445 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001446 if (qualname == NULL)
1447 qualname = co->co_name;
1448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (free == 0) {
1450 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001451 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 ADDOP_I(c, MAKE_FUNCTION, args);
1453 return 1;
1454 }
1455 for (i = 0; i < free; ++i) {
1456 /* Bypass com_addop_varname because it will generate
1457 LOAD_DEREF but LOAD_CLOSURE is needed.
1458 */
1459 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1460 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* Special case: If a class contains a method with a
1463 free variable that has the same name as a method,
1464 the name will be considered free *and* local in the
1465 class. It should be handled by the closure, as
1466 well as by the normal name loookup logic.
1467 */
1468 reftype = get_ref_type(c, name);
1469 if (reftype == CELL)
1470 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1471 else /* (reftype == FREE) */
1472 arg = compiler_lookup_arg(c->u->u_freevars, name);
1473 if (arg == -1) {
1474 fprintf(stderr,
1475 "lookup %s in %s %d %d\n"
1476 "freevars of %s: %s\n",
Serhiy Storchaka81f68a72014-11-19 00:08:38 +02001477 PyUnicode_AsUTF8(PyObject_Repr(name)),
1478 PyUnicode_AsUTF8(c->u->u_name),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 reftype, arg,
Serhiy Storchaka81f68a72014-11-19 00:08:38 +02001480 PyUnicode_AsUTF8(co->co_name),
1481 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 Py_FatalError("compiler_make_closure()");
1483 }
1484 ADDOP_I(c, LOAD_CLOSURE, arg);
1485 }
1486 ADDOP_I(c, BUILD_TUPLE, free);
1487 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001488 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 ADDOP_I(c, MAKE_CLOSURE, args);
1490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491}
1492
1493static int
1494compiler_decorators(struct compiler *c, asdl_seq* decos)
1495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (!decos)
1499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1502 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1503 }
1504 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505}
1506
1507static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001508compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 int i, default_count = 0;
1512 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1513 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1514 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1515 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001516 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1517 if (!mangled)
1518 return -1;
1519 ADDOP_O(c, LOAD_CONST, mangled, consts);
1520 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (!compiler_visit_expr(c, default_)) {
1522 return -1;
1523 }
1524 default_count++;
1525 }
1526 }
1527 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001528}
1529
1530static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001531compiler_visit_argannotation(struct compiler *c, identifier id,
1532 expr_ty annotation, PyObject *names)
1533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (annotation) {
Victor Stinner6acc5e12014-02-18 22:07:56 +01001535 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 VISIT(c, expr, annotation);
Victor Stinner6acc5e12014-02-18 22:07:56 +01001537 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov026019f2014-02-18 12:49:41 -05001538 if (!mangled)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 return -1;
Yury Selivanov026019f2014-02-18 12:49:41 -05001540 if (PyList_Append(names, mangled) < 0) {
1541 Py_DECREF(mangled);
1542 return -1;
1543 }
1544 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 }
1546 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001547}
1548
1549static int
1550compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1551 PyObject *names)
1552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 int i, error;
1554 for (i = 0; i < asdl_seq_LEN(args); i++) {
1555 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1556 error = compiler_visit_argannotation(
1557 c,
1558 arg->arg,
1559 arg->annotation,
1560 names);
1561 if (error)
1562 return error;
1563 }
1564 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001565}
1566
1567static int
1568compiler_visit_annotations(struct compiler *c, arguments_ty args,
1569 expr_ty returns)
1570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* Push arg annotations and a list of the argument names. Return the #
1572 of items pushed. The expressions are evaluated out-of-order wrt the
1573 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1576 */
1577 static identifier return_str;
1578 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001579 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 names = PyList_New(0);
1581 if (!names)
1582 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 if (compiler_visit_argannotations(c, args->args, names))
1585 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001586 if (args->vararg && args->vararg->annotation &&
1587 compiler_visit_argannotation(c, args->vararg->arg,
1588 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 goto error;
1590 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1591 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001592 if (args->kwarg && args->kwarg->annotation &&
1593 compiler_visit_argannotation(c, args->kwarg->arg,
1594 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 if (!return_str) {
1598 return_str = PyUnicode_InternFromString("return");
1599 if (!return_str)
1600 goto error;
1601 }
1602 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1603 goto error;
1604 }
1605
1606 len = PyList_GET_SIZE(names);
1607 if (len > 65534) {
1608 /* len must fit in 16 bits, and len is incremented below */
1609 PyErr_SetString(PyExc_SyntaxError,
1610 "too many annotations");
1611 goto error;
1612 }
1613 if (len) {
1614 /* convert names to a tuple and place on stack */
1615 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001616 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 PyObject *s = PyTuple_New(len);
1618 if (!s)
1619 goto error;
1620 for (i = 0; i < len; i++) {
1621 elt = PyList_GET_ITEM(names, i);
1622 Py_INCREF(elt);
1623 PyTuple_SET_ITEM(s, i, elt);
1624 }
1625 ADDOP_O(c, LOAD_CONST, s, consts);
1626 Py_DECREF(s);
1627 len++; /* include the just-pushed tuple */
1628 }
1629 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001630
1631 /* We just checked that len <= 65535, see above */
1632 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001633
1634error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 Py_DECREF(names);
1636 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001637}
1638
1639static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640compiler_function(struct compiler *c, stmt_ty s)
1641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001643 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 arguments_ty args = s->v.FunctionDef.args;
1645 expr_ty returns = s->v.FunctionDef.returns;
1646 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1647 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001648 Py_ssize_t i, n, arglength;
1649 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (!compiler_decorators(c, decos))
1655 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001656 if (args->defaults)
1657 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (args->kwonlyargs) {
1659 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1660 args->kw_defaults);
1661 if (res < 0)
1662 return 0;
1663 kw_default_count = res;
1664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 num_annotations = compiler_visit_annotations(c, args, returns);
1666 if (num_annotations < 0)
1667 return 0;
1668 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001669
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001670 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1671 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 s->lineno))
1673 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1676 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001677 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 first_const = st->v.Expr.value->v.Str.s;
1679 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1680 compiler_exit_scope(c);
1681 return 0;
1682 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 c->u->u_argcount = asdl_seq_LEN(args->args);
1685 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1686 n = asdl_seq_LEN(s->v.FunctionDef.body);
1687 /* if there was a docstring, we need to skip the first statement */
1688 for (i = docstring; i < n; i++) {
1689 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1690 VISIT_IN_SCOPE(c, stmt, st);
1691 }
1692 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001693 qualname = c->u->u_qualname;
1694 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001696 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001697 Py_XDECREF(qualname);
1698 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001700 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 arglength = asdl_seq_LEN(args->defaults);
1703 arglength |= kw_default_count << 8;
1704 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001705 compiler_make_closure(c, co, arglength, qualname);
1706 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 /* decorators */
1710 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1711 ADDOP_I(c, CALL_FUNCTION, 1);
1712 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715}
1716
1717static int
1718compiler_class(struct compiler *c, stmt_ty s)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyCodeObject *co;
1721 PyObject *str;
1722 int i;
1723 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 if (!compiler_decorators(c, decos))
1726 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* ultimately generate code for:
1729 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1730 where:
1731 <func> is a function/closure created from the class body;
1732 it has a single argument (__locals__) where the dict
1733 (or MutableSequence) representing the locals is passed
1734 <name> is the class name
1735 <bases> is the positional arguments and *varargs argument
1736 <keywords> is the keyword arguments and **kwds argument
1737 This borrows from compiler_call.
1738 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001741 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1742 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 return 0;
1744 /* this block represents what we do in the new scope */
1745 {
1746 /* use the class name for name mangling */
1747 Py_INCREF(s->v.ClassDef.name);
1748 Py_XDECREF(c->u->u_private);
1749 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 /* load (global) __name__ ... */
1751 str = PyUnicode_InternFromString("__name__");
1752 if (!str || !compiler_nameop(c, str, Load)) {
1753 Py_XDECREF(str);
1754 compiler_exit_scope(c);
1755 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001756 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_DECREF(str);
1758 /* ... and store it as __module__ */
1759 str = PyUnicode_InternFromString("__module__");
1760 if (!str || !compiler_nameop(c, str, Store)) {
1761 Py_XDECREF(str);
1762 compiler_exit_scope(c);
1763 return 0;
1764 }
1765 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001766 assert(c->u->u_qualname);
1767 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001768 str = PyUnicode_InternFromString("__qualname__");
1769 if (!str || !compiler_nameop(c, str, Store)) {
1770 Py_XDECREF(str);
1771 compiler_exit_scope(c);
1772 return 0;
1773 }
1774 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* compile the body proper */
1776 if (!compiler_body(c, s->v.ClassDef.body)) {
1777 compiler_exit_scope(c);
1778 return 0;
1779 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001780 if (c->u->u_ste->ste_needs_class_closure) {
1781 /* return the (empty) __class__ cell */
1782 str = PyUnicode_InternFromString("__class__");
1783 if (str == NULL) {
1784 compiler_exit_scope(c);
1785 return 0;
1786 }
1787 i = compiler_lookup_arg(c->u->u_cellvars, str);
1788 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001789 if (i < 0) {
1790 compiler_exit_scope(c);
1791 return 0;
1792 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001793 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* Return the cell where to store __class__ */
1795 ADDOP_I(c, LOAD_CLOSURE, i);
1796 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001797 else {
1798 assert(PyDict_Size(c->u->u_cellvars) == 0);
1799 /* This happens when nobody references the cell. Return None. */
1800 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1803 /* create the code object */
1804 co = assemble(c, 1);
1805 }
1806 /* leave the new scope */
1807 compiler_exit_scope(c);
1808 if (co == NULL)
1809 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 /* 2. load the 'build_class' function */
1812 ADDOP(c, LOAD_BUILD_CLASS);
1813
1814 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001815 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 Py_DECREF(co);
1817
1818 /* 4. load class name */
1819 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1820
1821 /* 5. generate the rest of the code for the call */
1822 if (!compiler_call_helper(c, 2,
1823 s->v.ClassDef.bases,
1824 s->v.ClassDef.keywords,
1825 s->v.ClassDef.starargs,
1826 s->v.ClassDef.kwargs))
1827 return 0;
1828
1829 /* 6. apply decorators */
1830 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1831 ADDOP_I(c, CALL_FUNCTION, 1);
1832 }
1833
1834 /* 7. store into <name> */
1835 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1836 return 0;
1837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838}
1839
1840static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001841compiler_ifexp(struct compiler *c, expr_ty e)
1842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 basicblock *end, *next;
1844
1845 assert(e->kind == IfExp_kind);
1846 end = compiler_new_block(c);
1847 if (end == NULL)
1848 return 0;
1849 next = compiler_new_block(c);
1850 if (next == NULL)
1851 return 0;
1852 VISIT(c, expr, e->v.IfExp.test);
1853 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1854 VISIT(c, expr, e->v.IfExp.body);
1855 ADDOP_JREL(c, JUMP_FORWARD, end);
1856 compiler_use_next_block(c, next);
1857 VISIT(c, expr, e->v.IfExp.orelse);
1858 compiler_use_next_block(c, end);
1859 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001860}
1861
1862static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863compiler_lambda(struct compiler *c, expr_ty e)
1864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001866 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001868 int kw_default_count = 0;
1869 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 arguments_ty args = e->v.Lambda.args;
1871 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (!name) {
1874 name = PyUnicode_InternFromString("<lambda>");
1875 if (!name)
1876 return 0;
1877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001879 if (args->defaults)
1880 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (args->kwonlyargs) {
1882 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1883 args->kw_defaults);
1884 if (res < 0) return 0;
1885 kw_default_count = res;
1886 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001887 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001888 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* Make None the first constant, so the lambda can't have a
1892 docstring. */
1893 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1894 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 c->u->u_argcount = asdl_seq_LEN(args->args);
1897 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1898 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1899 if (c->u->u_ste->ste_generator) {
1900 ADDOP_IN_SCOPE(c, POP_TOP);
1901 }
1902 else {
1903 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1904 }
1905 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001906 qualname = c->u->u_qualname;
1907 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001909 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 arglength = asdl_seq_LEN(args->defaults);
1913 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001914 compiler_make_closure(c, co, arglength, qualname);
1915 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 Py_DECREF(co);
1917
1918 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
1920
1921static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922compiler_if(struct compiler *c, stmt_ty s)
1923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 basicblock *end, *next;
1925 int constant;
1926 assert(s->kind == If_kind);
1927 end = compiler_new_block(c);
1928 if (end == NULL)
1929 return 0;
1930
Georg Brandl8334fd92010-12-04 10:26:46 +00001931 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 /* constant = 0: "if 0"
1933 * constant = 1: "if 1", "if 2", ...
1934 * constant = -1: rest */
1935 if (constant == 0) {
1936 if (s->v.If.orelse)
1937 VISIT_SEQ(c, stmt, s->v.If.orelse);
1938 } else if (constant == 1) {
1939 VISIT_SEQ(c, stmt, s->v.If.body);
1940 } else {
1941 if (s->v.If.orelse) {
1942 next = compiler_new_block(c);
1943 if (next == NULL)
1944 return 0;
1945 }
1946 else
1947 next = end;
1948 VISIT(c, expr, s->v.If.test);
1949 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1950 VISIT_SEQ(c, stmt, s->v.If.body);
1951 ADDOP_JREL(c, JUMP_FORWARD, end);
1952 if (s->v.If.orelse) {
1953 compiler_use_next_block(c, next);
1954 VISIT_SEQ(c, stmt, s->v.If.orelse);
1955 }
1956 }
1957 compiler_use_next_block(c, end);
1958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959}
1960
1961static int
1962compiler_for(struct compiler *c, stmt_ty s)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 start = compiler_new_block(c);
1967 cleanup = compiler_new_block(c);
1968 end = compiler_new_block(c);
1969 if (start == NULL || end == NULL || cleanup == NULL)
1970 return 0;
1971 ADDOP_JREL(c, SETUP_LOOP, end);
1972 if (!compiler_push_fblock(c, LOOP, start))
1973 return 0;
1974 VISIT(c, expr, s->v.For.iter);
1975 ADDOP(c, GET_ITER);
1976 compiler_use_next_block(c, start);
1977 ADDOP_JREL(c, FOR_ITER, cleanup);
1978 VISIT(c, expr, s->v.For.target);
1979 VISIT_SEQ(c, stmt, s->v.For.body);
1980 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1981 compiler_use_next_block(c, cleanup);
1982 ADDOP(c, POP_BLOCK);
1983 compiler_pop_fblock(c, LOOP, start);
1984 VISIT_SEQ(c, stmt, s->v.For.orelse);
1985 compiler_use_next_block(c, end);
1986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987}
1988
1989static int
1990compiler_while(struct compiler *c, stmt_ty s)
1991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001993 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (constant == 0) {
1996 if (s->v.While.orelse)
1997 VISIT_SEQ(c, stmt, s->v.While.orelse);
1998 return 1;
1999 }
2000 loop = compiler_new_block(c);
2001 end = compiler_new_block(c);
2002 if (constant == -1) {
2003 anchor = compiler_new_block(c);
2004 if (anchor == NULL)
2005 return 0;
2006 }
2007 if (loop == NULL || end == NULL)
2008 return 0;
2009 if (s->v.While.orelse) {
2010 orelse = compiler_new_block(c);
2011 if (orelse == NULL)
2012 return 0;
2013 }
2014 else
2015 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 ADDOP_JREL(c, SETUP_LOOP, end);
2018 compiler_use_next_block(c, loop);
2019 if (!compiler_push_fblock(c, LOOP, loop))
2020 return 0;
2021 if (constant == -1) {
2022 VISIT(c, expr, s->v.While.test);
2023 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2024 }
2025 VISIT_SEQ(c, stmt, s->v.While.body);
2026 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* XXX should the two POP instructions be in a separate block
2029 if there is no else clause ?
2030 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002032 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002034 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 compiler_pop_fblock(c, LOOP, loop);
2036 if (orelse != NULL) /* what if orelse is just pass? */
2037 VISIT_SEQ(c, stmt, s->v.While.orelse);
2038 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002041}
2042
2043static int
2044compiler_continue(struct compiler *c)
2045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2047 static const char IN_FINALLY_ERROR_MSG[] =
2048 "'continue' not supported inside 'finally' clause";
2049 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (!c->u->u_nfblocks)
2052 return compiler_error(c, LOOP_ERROR_MSG);
2053 i = c->u->u_nfblocks - 1;
2054 switch (c->u->u_fblock[i].fb_type) {
2055 case LOOP:
2056 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2057 break;
2058 case EXCEPT:
2059 case FINALLY_TRY:
2060 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2061 /* Prevent continue anywhere under a finally
2062 even if hidden in a sub-try or except. */
2063 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2064 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2065 }
2066 if (i == -1)
2067 return compiler_error(c, LOOP_ERROR_MSG);
2068 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2069 break;
2070 case FINALLY_END:
2071 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2072 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075}
2076
2077/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078
2079 SETUP_FINALLY L
2080 <code for body>
2081 POP_BLOCK
2082 LOAD_CONST <None>
2083 L: <code for finalbody>
2084 END_FINALLY
2085
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 The special instructions use the block stack. Each block
2087 stack entry contains the instruction that created it (here
2088 SETUP_FINALLY), the level of the value stack at the time the
2089 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 Pushes the current value stack level and the label
2093 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 Pops en entry from the block stack, and pops the value
2096 stack until its level is the same as indicated on the
2097 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 Pops a variable number of entries from the *value* stack
2100 and re-raises the exception they specify. The number of
2101 entries popped depends on the (pseudo) exception type.
2102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 The block stack is unwound when an exception is raised:
2104 when a SETUP_FINALLY entry is found, the exception is pushed
2105 onto the value stack (and the exception condition is cleared),
2106 and the interpreter jumps to the label gotten from the block
2107 stack.
2108*/
2109
2110static int
2111compiler_try_finally(struct compiler *c, stmt_ty s)
2112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 basicblock *body, *end;
2114 body = compiler_new_block(c);
2115 end = compiler_new_block(c);
2116 if (body == NULL || end == NULL)
2117 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 ADDOP_JREL(c, SETUP_FINALLY, end);
2120 compiler_use_next_block(c, body);
2121 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2122 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002123 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2124 if (!compiler_try_except(c, s))
2125 return 0;
2126 }
2127 else {
2128 VISIT_SEQ(c, stmt, s->v.Try.body);
2129 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 ADDOP(c, POP_BLOCK);
2131 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2134 compiler_use_next_block(c, end);
2135 if (!compiler_push_fblock(c, FINALLY_END, end))
2136 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002137 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 ADDOP(c, END_FINALLY);
2139 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002142}
2143
2144/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002145 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 (The contents of the value stack is shown in [], with the top
2147 at the right; 'tb' is trace-back info, 'val' the exception's
2148 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149
2150 Value stack Label Instruction Argument
2151 [] SETUP_EXCEPT L1
2152 [] <code for S>
2153 [] POP_BLOCK
2154 [] JUMP_FORWARD L0
2155
2156 [tb, val, exc] L1: DUP )
2157 [tb, val, exc, exc] <evaluate E1> )
2158 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2159 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2160 [tb, val, exc] POP
2161 [tb, val] <assign to V1> (or POP if no V1)
2162 [tb] POP
2163 [] <code for S1>
2164 JUMP_FORWARD L0
2165
2166 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 .............................etc.......................
2168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2170
2171 [] L0: <next statement>
2172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173 Of course, parts are not generated if Vi or Ei is not present.
2174*/
2175static int
2176compiler_try_except(struct compiler *c, stmt_ty s)
2177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002179 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 body = compiler_new_block(c);
2182 except = compiler_new_block(c);
2183 orelse = compiler_new_block(c);
2184 end = compiler_new_block(c);
2185 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2186 return 0;
2187 ADDOP_JREL(c, SETUP_EXCEPT, except);
2188 compiler_use_next_block(c, body);
2189 if (!compiler_push_fblock(c, EXCEPT, body))
2190 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002191 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 ADDOP(c, POP_BLOCK);
2193 compiler_pop_fblock(c, EXCEPT, body);
2194 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002195 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 compiler_use_next_block(c, except);
2197 for (i = 0; i < n; i++) {
2198 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002199 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (!handler->v.ExceptHandler.type && i < n-1)
2201 return compiler_error(c, "default 'except:' must be last");
2202 c->u->u_lineno_set = 0;
2203 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002204 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 except = compiler_new_block(c);
2206 if (except == NULL)
2207 return 0;
2208 if (handler->v.ExceptHandler.type) {
2209 ADDOP(c, DUP_TOP);
2210 VISIT(c, expr, handler->v.ExceptHandler.type);
2211 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2212 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2213 }
2214 ADDOP(c, POP_TOP);
2215 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002216 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002217
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002218 cleanup_end = compiler_new_block(c);
2219 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002220 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002221 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002222
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002223 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2224 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002226 /*
2227 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002228 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002229 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002230 try:
2231 # body
2232 finally:
2233 name = None
2234 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002235 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002237 /* second try: */
2238 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2239 compiler_use_next_block(c, cleanup_body);
2240 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2241 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002243 /* second # body */
2244 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2245 ADDOP(c, POP_BLOCK);
2246 ADDOP(c, POP_EXCEPT);
2247 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002249 /* finally: */
2250 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2251 compiler_use_next_block(c, cleanup_end);
2252 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2253 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002255 /* name = None */
2256 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2257 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002259 /* del name */
2260 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002262 ADDOP(c, END_FINALLY);
2263 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 }
2265 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002266 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002268 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002269 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002270 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271
Guido van Rossumb940e112007-01-10 16:19:56 +00002272 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002273 ADDOP(c, POP_TOP);
2274 compiler_use_next_block(c, cleanup_body);
2275 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2276 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002278 ADDOP(c, POP_EXCEPT);
2279 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 }
2281 ADDOP_JREL(c, JUMP_FORWARD, end);
2282 compiler_use_next_block(c, except);
2283 }
2284 ADDOP(c, END_FINALLY);
2285 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002286 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 compiler_use_next_block(c, end);
2288 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289}
2290
2291static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002292compiler_try(struct compiler *c, stmt_ty s) {
2293 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2294 return compiler_try_finally(c, s);
2295 else
2296 return compiler_try_except(c, s);
2297}
2298
2299
2300static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301compiler_import_as(struct compiler *c, identifier name, identifier asname)
2302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* The IMPORT_NAME opcode was already generated. This function
2304 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 If there is a dot in name, we need to split it and emit a
2307 LOAD_ATTR for each name.
2308 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002309 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2310 PyUnicode_GET_LENGTH(name), 1);
2311 if (dot == -2)
2312 return -1;
2313 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002315 Py_ssize_t pos = dot + 1;
2316 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002318 dot = PyUnicode_FindChar(name, '.', pos,
2319 PyUnicode_GET_LENGTH(name), 1);
2320 if (dot == -2)
2321 return -1;
2322 attr = PyUnicode_Substring(name, pos,
2323 (dot != -1) ? dot :
2324 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 if (!attr)
2326 return -1;
2327 ADDOP_O(c, LOAD_ATTR, attr, names);
2328 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002329 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 }
2331 }
2332 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333}
2334
2335static int
2336compiler_import(struct compiler *c, stmt_ty s)
2337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* The Import node stores a module name like a.b.c as a single
2339 string. This is convenient for all cases except
2340 import a.b.c as d
2341 where we need to parse that string to extract the individual
2342 module names.
2343 XXX Perhaps change the representation to make this case simpler?
2344 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002345 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 for (i = 0; i < n; i++) {
2348 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2349 int r;
2350 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 level = PyLong_FromLong(0);
2353 if (level == NULL)
2354 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 ADDOP_O(c, LOAD_CONST, level, consts);
2357 Py_DECREF(level);
2358 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2359 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 if (alias->asname) {
2362 r = compiler_import_as(c, alias->name, alias->asname);
2363 if (!r)
2364 return r;
2365 }
2366 else {
2367 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002368 Py_ssize_t dot = PyUnicode_FindChar(
2369 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002370 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002372 if (tmp == NULL)
2373 return 0;
2374 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002376 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 Py_DECREF(tmp);
2378 }
2379 if (!r)
2380 return r;
2381 }
2382 }
2383 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384}
2385
2386static int
2387compiler_from_import(struct compiler *c, stmt_ty s)
2388{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002389 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 PyObject *names = PyTuple_New(n);
2392 PyObject *level;
2393 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 if (!empty_string) {
2396 empty_string = PyUnicode_FromString("");
2397 if (!empty_string)
2398 return 0;
2399 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 if (!names)
2402 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 level = PyLong_FromLong(s->v.ImportFrom.level);
2405 if (!level) {
2406 Py_DECREF(names);
2407 return 0;
2408 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* build up the names */
2411 for (i = 0; i < n; i++) {
2412 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2413 Py_INCREF(alias->name);
2414 PyTuple_SET_ITEM(names, i, alias->name);
2415 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2418 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2419 Py_DECREF(level);
2420 Py_DECREF(names);
2421 return compiler_error(c, "from __future__ imports must occur "
2422 "at the beginning of the file");
2423 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 ADDOP_O(c, LOAD_CONST, level, consts);
2426 Py_DECREF(level);
2427 ADDOP_O(c, LOAD_CONST, names, consts);
2428 Py_DECREF(names);
2429 if (s->v.ImportFrom.module) {
2430 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2431 }
2432 else {
2433 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2434 }
2435 for (i = 0; i < n; i++) {
2436 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2437 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 assert(n == 1);
2441 ADDOP(c, IMPORT_STAR);
2442 return 1;
2443 }
2444
2445 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2446 store_name = alias->name;
2447 if (alias->asname)
2448 store_name = alias->asname;
2449
2450 if (!compiler_nameop(c, store_name, Store)) {
2451 Py_DECREF(names);
2452 return 0;
2453 }
2454 }
2455 /* remove imported module */
2456 ADDOP(c, POP_TOP);
2457 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458}
2459
2460static int
2461compiler_assert(struct compiler *c, stmt_ty s)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 static PyObject *assertion_error = NULL;
2464 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002465 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466
Georg Brandl8334fd92010-12-04 10:26:46 +00002467 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 return 1;
2469 if (assertion_error == NULL) {
2470 assertion_error = PyUnicode_InternFromString("AssertionError");
2471 if (assertion_error == NULL)
2472 return 0;
2473 }
2474 if (s->v.Assert.test->kind == Tuple_kind &&
2475 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002476 msg = PyUnicode_FromString("assertion is always true, "
2477 "perhaps remove parentheses?");
2478 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002480 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2481 c->c_filename, c->u->u_lineno,
2482 NULL, NULL) == -1) {
2483 Py_DECREF(msg);
2484 return 0;
2485 }
2486 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 }
2488 VISIT(c, expr, s->v.Assert.test);
2489 end = compiler_new_block(c);
2490 if (end == NULL)
2491 return 0;
2492 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2493 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2494 if (s->v.Assert.msg) {
2495 VISIT(c, expr, s->v.Assert.msg);
2496 ADDOP_I(c, CALL_FUNCTION, 1);
2497 }
2498 ADDOP_I(c, RAISE_VARARGS, 1);
2499 compiler_use_next_block(c, end);
2500 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501}
2502
2503static int
2504compiler_visit_stmt(struct compiler *c, stmt_ty s)
2505{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002506 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* Always assign a lineno to the next instruction for a stmt. */
2509 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002510 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 switch (s->kind) {
2514 case FunctionDef_kind:
2515 return compiler_function(c, s);
2516 case ClassDef_kind:
2517 return compiler_class(c, s);
2518 case Return_kind:
2519 if (c->u->u_ste->ste_type != FunctionBlock)
2520 return compiler_error(c, "'return' outside function");
2521 if (s->v.Return.value) {
2522 VISIT(c, expr, s->v.Return.value);
2523 }
2524 else
2525 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2526 ADDOP(c, RETURN_VALUE);
2527 break;
2528 case Delete_kind:
2529 VISIT_SEQ(c, expr, s->v.Delete.targets)
2530 break;
2531 case Assign_kind:
2532 n = asdl_seq_LEN(s->v.Assign.targets);
2533 VISIT(c, expr, s->v.Assign.value);
2534 for (i = 0; i < n; i++) {
2535 if (i < n - 1)
2536 ADDOP(c, DUP_TOP);
2537 VISIT(c, expr,
2538 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2539 }
2540 break;
2541 case AugAssign_kind:
2542 return compiler_augassign(c, s);
2543 case For_kind:
2544 return compiler_for(c, s);
2545 case While_kind:
2546 return compiler_while(c, s);
2547 case If_kind:
2548 return compiler_if(c, s);
2549 case Raise_kind:
2550 n = 0;
2551 if (s->v.Raise.exc) {
2552 VISIT(c, expr, s->v.Raise.exc);
2553 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002554 if (s->v.Raise.cause) {
2555 VISIT(c, expr, s->v.Raise.cause);
2556 n++;
2557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002559 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002561 case Try_kind:
2562 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 case Assert_kind:
2564 return compiler_assert(c, s);
2565 case Import_kind:
2566 return compiler_import(c, s);
2567 case ImportFrom_kind:
2568 return compiler_from_import(c, s);
2569 case Global_kind:
2570 case Nonlocal_kind:
2571 break;
2572 case Expr_kind:
2573 if (c->c_interactive && c->c_nestlevel <= 1) {
2574 VISIT(c, expr, s->v.Expr.value);
2575 ADDOP(c, PRINT_EXPR);
2576 }
2577 else if (s->v.Expr.value->kind != Str_kind &&
2578 s->v.Expr.value->kind != Num_kind) {
2579 VISIT(c, expr, s->v.Expr.value);
2580 ADDOP(c, POP_TOP);
2581 }
2582 break;
2583 case Pass_kind:
2584 break;
2585 case Break_kind:
2586 if (!compiler_in_loop(c))
2587 return compiler_error(c, "'break' outside loop");
2588 ADDOP(c, BREAK_LOOP);
2589 break;
2590 case Continue_kind:
2591 return compiler_continue(c);
2592 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002593 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 }
2595 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596}
2597
2598static int
2599unaryop(unaryop_ty op)
2600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 switch (op) {
2602 case Invert:
2603 return UNARY_INVERT;
2604 case Not:
2605 return UNARY_NOT;
2606 case UAdd:
2607 return UNARY_POSITIVE;
2608 case USub:
2609 return UNARY_NEGATIVE;
2610 default:
2611 PyErr_Format(PyExc_SystemError,
2612 "unary op %d should not be possible", op);
2613 return 0;
2614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615}
2616
2617static int
2618binop(struct compiler *c, operator_ty op)
2619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 switch (op) {
2621 case Add:
2622 return BINARY_ADD;
2623 case Sub:
2624 return BINARY_SUBTRACT;
2625 case Mult:
2626 return BINARY_MULTIPLY;
2627 case Div:
2628 return BINARY_TRUE_DIVIDE;
2629 case Mod:
2630 return BINARY_MODULO;
2631 case Pow:
2632 return BINARY_POWER;
2633 case LShift:
2634 return BINARY_LSHIFT;
2635 case RShift:
2636 return BINARY_RSHIFT;
2637 case BitOr:
2638 return BINARY_OR;
2639 case BitXor:
2640 return BINARY_XOR;
2641 case BitAnd:
2642 return BINARY_AND;
2643 case FloorDiv:
2644 return BINARY_FLOOR_DIVIDE;
2645 default:
2646 PyErr_Format(PyExc_SystemError,
2647 "binary op %d should not be possible", op);
2648 return 0;
2649 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650}
2651
2652static int
2653cmpop(cmpop_ty op)
2654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 switch (op) {
2656 case Eq:
2657 return PyCmp_EQ;
2658 case NotEq:
2659 return PyCmp_NE;
2660 case Lt:
2661 return PyCmp_LT;
2662 case LtE:
2663 return PyCmp_LE;
2664 case Gt:
2665 return PyCmp_GT;
2666 case GtE:
2667 return PyCmp_GE;
2668 case Is:
2669 return PyCmp_IS;
2670 case IsNot:
2671 return PyCmp_IS_NOT;
2672 case In:
2673 return PyCmp_IN;
2674 case NotIn:
2675 return PyCmp_NOT_IN;
2676 default:
2677 return PyCmp_BAD;
2678 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679}
2680
2681static int
2682inplace_binop(struct compiler *c, operator_ty op)
2683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 switch (op) {
2685 case Add:
2686 return INPLACE_ADD;
2687 case Sub:
2688 return INPLACE_SUBTRACT;
2689 case Mult:
2690 return INPLACE_MULTIPLY;
2691 case Div:
2692 return INPLACE_TRUE_DIVIDE;
2693 case Mod:
2694 return INPLACE_MODULO;
2695 case Pow:
2696 return INPLACE_POWER;
2697 case LShift:
2698 return INPLACE_LSHIFT;
2699 case RShift:
2700 return INPLACE_RSHIFT;
2701 case BitOr:
2702 return INPLACE_OR;
2703 case BitXor:
2704 return INPLACE_XOR;
2705 case BitAnd:
2706 return INPLACE_AND;
2707 case FloorDiv:
2708 return INPLACE_FLOOR_DIVIDE;
2709 default:
2710 PyErr_Format(PyExc_SystemError,
2711 "inplace binary op %d should not be possible", op);
2712 return 0;
2713 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714}
2715
2716static int
2717compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2718{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002719 int op, scope;
2720 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 PyObject *dict = c->u->u_names;
2724 PyObject *mangled;
2725 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 mangled = _Py_Mangle(c->u->u_private, name);
2728 if (!mangled)
2729 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002730
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002731 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2732 PyUnicode_CompareWithASCIIString(name, "True") &&
2733 PyUnicode_CompareWithASCIIString(name, "False"));
2734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 op = 0;
2736 optype = OP_NAME;
2737 scope = PyST_GetScope(c->u->u_ste, mangled);
2738 switch (scope) {
2739 case FREE:
2740 dict = c->u->u_freevars;
2741 optype = OP_DEREF;
2742 break;
2743 case CELL:
2744 dict = c->u->u_cellvars;
2745 optype = OP_DEREF;
2746 break;
2747 case LOCAL:
2748 if (c->u->u_ste->ste_type == FunctionBlock)
2749 optype = OP_FAST;
2750 break;
2751 case GLOBAL_IMPLICIT:
2752 if (c->u->u_ste->ste_type == FunctionBlock &&
2753 !c->u->u_ste->ste_unoptimized)
2754 optype = OP_GLOBAL;
2755 break;
2756 case GLOBAL_EXPLICIT:
2757 optype = OP_GLOBAL;
2758 break;
2759 default:
2760 /* scope can be 0 */
2761 break;
2762 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002765 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 switch (optype) {
2768 case OP_DEREF:
2769 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002770 case Load:
2771 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2772 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 case Store: op = STORE_DEREF; break;
2774 case AugLoad:
2775 case AugStore:
2776 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002777 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 case Param:
2779 default:
2780 PyErr_SetString(PyExc_SystemError,
2781 "param invalid for deref variable");
2782 return 0;
2783 }
2784 break;
2785 case OP_FAST:
2786 switch (ctx) {
2787 case Load: op = LOAD_FAST; break;
2788 case Store: op = STORE_FAST; break;
2789 case Del: op = DELETE_FAST; break;
2790 case AugLoad:
2791 case AugStore:
2792 break;
2793 case Param:
2794 default:
2795 PyErr_SetString(PyExc_SystemError,
2796 "param invalid for local variable");
2797 return 0;
2798 }
2799 ADDOP_O(c, op, mangled, varnames);
2800 Py_DECREF(mangled);
2801 return 1;
2802 case OP_GLOBAL:
2803 switch (ctx) {
2804 case Load: op = LOAD_GLOBAL; break;
2805 case Store: op = STORE_GLOBAL; break;
2806 case Del: op = DELETE_GLOBAL; break;
2807 case AugLoad:
2808 case AugStore:
2809 break;
2810 case Param:
2811 default:
2812 PyErr_SetString(PyExc_SystemError,
2813 "param invalid for global variable");
2814 return 0;
2815 }
2816 break;
2817 case OP_NAME:
2818 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002819 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 case Store: op = STORE_NAME; break;
2821 case Del: op = DELETE_NAME; break;
2822 case AugLoad:
2823 case AugStore:
2824 break;
2825 case Param:
2826 default:
2827 PyErr_SetString(PyExc_SystemError,
2828 "param invalid for name variable");
2829 return 0;
2830 }
2831 break;
2832 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 assert(op);
2835 arg = compiler_add_o(c, dict, mangled);
2836 Py_DECREF(mangled);
2837 if (arg < 0)
2838 return 0;
2839 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840}
2841
2842static int
2843compiler_boolop(struct compiler *c, expr_ty e)
2844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002846 int jumpi;
2847 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 assert(e->kind == BoolOp_kind);
2851 if (e->v.BoolOp.op == And)
2852 jumpi = JUMP_IF_FALSE_OR_POP;
2853 else
2854 jumpi = JUMP_IF_TRUE_OR_POP;
2855 end = compiler_new_block(c);
2856 if (end == NULL)
2857 return 0;
2858 s = e->v.BoolOp.values;
2859 n = asdl_seq_LEN(s) - 1;
2860 assert(n >= 0);
2861 for (i = 0; i < n; ++i) {
2862 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2863 ADDOP_JABS(c, jumpi, end);
2864 }
2865 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2866 compiler_use_next_block(c, end);
2867 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868}
2869
2870static int
2871compiler_list(struct compiler *c, expr_ty e)
2872{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002873 Py_ssize_t n = asdl_seq_LEN(e->v.List.elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 if (e->v.List.ctx == Store) {
2875 int i, seen_star = 0;
2876 for (i = 0; i < n; i++) {
2877 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2878 if (elt->kind == Starred_kind && !seen_star) {
2879 if ((i >= (1 << 8)) ||
2880 (n-i-1 >= (INT_MAX >> 8)))
2881 return compiler_error(c,
2882 "too many expressions in "
2883 "star-unpacking assignment");
2884 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2885 seen_star = 1;
2886 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2887 } else if (elt->kind == Starred_kind) {
2888 return compiler_error(c,
2889 "two starred expressions in assignment");
2890 }
2891 }
2892 if (!seen_star) {
2893 ADDOP_I(c, UNPACK_SEQUENCE, n);
2894 }
2895 }
2896 VISIT_SEQ(c, expr, e->v.List.elts);
2897 if (e->v.List.ctx == Load) {
2898 ADDOP_I(c, BUILD_LIST, n);
2899 }
2900 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901}
2902
2903static int
2904compiler_tuple(struct compiler *c, expr_ty e)
2905{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002906 Py_ssize_t n = asdl_seq_LEN(e->v.Tuple.elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 if (e->v.Tuple.ctx == Store) {
2908 int i, seen_star = 0;
2909 for (i = 0; i < n; i++) {
2910 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2911 if (elt->kind == Starred_kind && !seen_star) {
2912 if ((i >= (1 << 8)) ||
2913 (n-i-1 >= (INT_MAX >> 8)))
2914 return compiler_error(c,
2915 "too many expressions in "
2916 "star-unpacking assignment");
2917 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2918 seen_star = 1;
2919 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2920 } else if (elt->kind == Starred_kind) {
2921 return compiler_error(c,
2922 "two starred expressions in assignment");
2923 }
2924 }
2925 if (!seen_star) {
2926 ADDOP_I(c, UNPACK_SEQUENCE, n);
2927 }
2928 }
2929 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2930 if (e->v.Tuple.ctx == Load) {
2931 ADDOP_I(c, BUILD_TUPLE, n);
2932 }
2933 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934}
2935
2936static int
2937compiler_compare(struct compiler *c, expr_ty e)
2938{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002939 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2943 VISIT(c, expr, e->v.Compare.left);
2944 n = asdl_seq_LEN(e->v.Compare.ops);
2945 assert(n > 0);
2946 if (n > 1) {
2947 cleanup = compiler_new_block(c);
2948 if (cleanup == NULL)
2949 return 0;
2950 VISIT(c, expr,
2951 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2952 }
2953 for (i = 1; i < n; i++) {
2954 ADDOP(c, DUP_TOP);
2955 ADDOP(c, ROT_THREE);
2956 ADDOP_I(c, COMPARE_OP,
2957 cmpop((cmpop_ty)(asdl_seq_GET(
2958 e->v.Compare.ops, i - 1))));
2959 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2960 NEXT_BLOCK(c);
2961 if (i < (n - 1))
2962 VISIT(c, expr,
2963 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2964 }
2965 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2966 ADDOP_I(c, COMPARE_OP,
2967 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2968 if (n > 1) {
2969 basicblock *end = compiler_new_block(c);
2970 if (end == NULL)
2971 return 0;
2972 ADDOP_JREL(c, JUMP_FORWARD, end);
2973 compiler_use_next_block(c, cleanup);
2974 ADDOP(c, ROT_TWO);
2975 ADDOP(c, POP_TOP);
2976 compiler_use_next_block(c, end);
2977 }
2978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979}
2980
2981static int
2982compiler_call(struct compiler *c, expr_ty e)
2983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 VISIT(c, expr, e->v.Call.func);
2985 return compiler_call_helper(c, 0,
2986 e->v.Call.args,
2987 e->v.Call.keywords,
2988 e->v.Call.starargs,
2989 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002990}
2991
2992/* shared code between compiler_call and compiler_class */
2993static int
2994compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01002995 Py_ssize_t n, /* Args already pushed */
2996 asdl_seq *args,
2997 asdl_seq *keywords,
2998 expr_ty starargs,
2999 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 n += asdl_seq_LEN(args);
3004 VISIT_SEQ(c, expr, args);
3005 if (keywords) {
3006 VISIT_SEQ(c, keyword, keywords);
3007 n |= asdl_seq_LEN(keywords) << 8;
3008 }
3009 if (starargs) {
3010 VISIT(c, expr, starargs);
3011 code |= 1;
3012 }
3013 if (kwargs) {
3014 VISIT(c, expr, kwargs);
3015 code |= 2;
3016 }
3017 switch (code) {
3018 case 0:
3019 ADDOP_I(c, CALL_FUNCTION, n);
3020 break;
3021 case 1:
3022 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3023 break;
3024 case 2:
3025 ADDOP_I(c, CALL_FUNCTION_KW, n);
3026 break;
3027 case 3:
3028 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3029 break;
3030 }
3031 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032}
3033
Nick Coghlan650f0d02007-04-15 12:05:43 +00003034
3035/* List and set comprehensions and generator expressions work by creating a
3036 nested function to perform the actual iteration. This means that the
3037 iteration variables don't leak into the current scope.
3038 The defined function is called immediately following its definition, with the
3039 result of that call being the result of the expression.
3040 The LC/SC version returns the populated container, while the GE version is
3041 flagged in symtable.c as a generator, so it returns the generator object
3042 when the function is called.
3043 This code *knows* that the loop cannot contain break, continue, or return,
3044 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3045
3046 Possible cleanups:
3047 - iterate over the generator sequence instead of using recursion
3048*/
3049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051compiler_comprehension_generator(struct compiler *c,
3052 asdl_seq *generators, int gen_index,
3053 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 /* generate code for the iterator, then each of the ifs,
3056 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 comprehension_ty gen;
3059 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003060 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 start = compiler_new_block(c);
3063 skip = compiler_new_block(c);
3064 if_cleanup = compiler_new_block(c);
3065 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3068 anchor == NULL)
3069 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 if (gen_index == 0) {
3074 /* Receive outermost iter as an implicit argument */
3075 c->u->u_argcount = 1;
3076 ADDOP_I(c, LOAD_FAST, 0);
3077 }
3078 else {
3079 /* Sub-iter - calculate on the fly */
3080 VISIT(c, expr, gen->iter);
3081 ADDOP(c, GET_ITER);
3082 }
3083 compiler_use_next_block(c, start);
3084 ADDOP_JREL(c, FOR_ITER, anchor);
3085 NEXT_BLOCK(c);
3086 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 /* XXX this needs to be cleaned up...a lot! */
3089 n = asdl_seq_LEN(gen->ifs);
3090 for (i = 0; i < n; i++) {
3091 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3092 VISIT(c, expr, e);
3093 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3094 NEXT_BLOCK(c);
3095 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 if (++gen_index < asdl_seq_LEN(generators))
3098 if (!compiler_comprehension_generator(c,
3099 generators, gen_index,
3100 elt, val, type))
3101 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 /* only append after the last for generator */
3104 if (gen_index >= asdl_seq_LEN(generators)) {
3105 /* comprehension specific code */
3106 switch (type) {
3107 case COMP_GENEXP:
3108 VISIT(c, expr, elt);
3109 ADDOP(c, YIELD_VALUE);
3110 ADDOP(c, POP_TOP);
3111 break;
3112 case COMP_LISTCOMP:
3113 VISIT(c, expr, elt);
3114 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3115 break;
3116 case COMP_SETCOMP:
3117 VISIT(c, expr, elt);
3118 ADDOP_I(c, SET_ADD, gen_index + 1);
3119 break;
3120 case COMP_DICTCOMP:
3121 /* With 'd[k] = v', v is evaluated before k, so we do
3122 the same. */
3123 VISIT(c, expr, val);
3124 VISIT(c, expr, elt);
3125 ADDOP_I(c, MAP_ADD, gen_index + 1);
3126 break;
3127 default:
3128 return 0;
3129 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 compiler_use_next_block(c, skip);
3132 }
3133 compiler_use_next_block(c, if_cleanup);
3134 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3135 compiler_use_next_block(c, anchor);
3136
3137 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138}
3139
3140static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003141compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 PyCodeObject *co = NULL;
3145 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003146 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 outermost_iter = ((comprehension_ty)
3149 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003150
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003151 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3152 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 if (type != COMP_GENEXP) {
3156 int op;
3157 switch (type) {
3158 case COMP_LISTCOMP:
3159 op = BUILD_LIST;
3160 break;
3161 case COMP_SETCOMP:
3162 op = BUILD_SET;
3163 break;
3164 case COMP_DICTCOMP:
3165 op = BUILD_MAP;
3166 break;
3167 default:
3168 PyErr_Format(PyExc_SystemError,
3169 "unknown comprehension type %d", type);
3170 goto error_in_scope;
3171 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 ADDOP_I(c, op, 0);
3174 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 if (!compiler_comprehension_generator(c, generators, 0, elt,
3177 val, type))
3178 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 if (type != COMP_GENEXP) {
3181 ADDOP(c, RETURN_VALUE);
3182 }
3183
3184 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003185 qualname = c->u->u_qualname;
3186 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003188 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 goto error;
3190
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003191 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003193 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 Py_DECREF(co);
3195
3196 VISIT(c, expr, outermost_iter);
3197 ADDOP(c, GET_ITER);
3198 ADDOP_I(c, CALL_FUNCTION, 1);
3199 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003200error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003202error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003203 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 Py_XDECREF(co);
3205 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003206}
3207
3208static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209compiler_genexp(struct compiler *c, expr_ty e)
3210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 static identifier name;
3212 if (!name) {
3213 name = PyUnicode_FromString("<genexpr>");
3214 if (!name)
3215 return 0;
3216 }
3217 assert(e->kind == GeneratorExp_kind);
3218 return compiler_comprehension(c, e, COMP_GENEXP, name,
3219 e->v.GeneratorExp.generators,
3220 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221}
3222
3223static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003224compiler_listcomp(struct compiler *c, expr_ty e)
3225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 static identifier name;
3227 if (!name) {
3228 name = PyUnicode_FromString("<listcomp>");
3229 if (!name)
3230 return 0;
3231 }
3232 assert(e->kind == ListComp_kind);
3233 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3234 e->v.ListComp.generators,
3235 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003236}
3237
3238static int
3239compiler_setcomp(struct compiler *c, expr_ty e)
3240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 static identifier name;
3242 if (!name) {
3243 name = PyUnicode_FromString("<setcomp>");
3244 if (!name)
3245 return 0;
3246 }
3247 assert(e->kind == SetComp_kind);
3248 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3249 e->v.SetComp.generators,
3250 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003251}
3252
3253
3254static int
3255compiler_dictcomp(struct compiler *c, expr_ty e)
3256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 static identifier name;
3258 if (!name) {
3259 name = PyUnicode_FromString("<dictcomp>");
3260 if (!name)
3261 return 0;
3262 }
3263 assert(e->kind == DictComp_kind);
3264 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3265 e->v.DictComp.generators,
3266 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003267}
3268
3269
3270static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271compiler_visit_keyword(struct compiler *c, keyword_ty k)
3272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3274 VISIT(c, expr, k->value);
3275 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276}
3277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279 whether they are true or false.
3280
3281 Return values: 1 for true, 0 for false, -1 for non-constant.
3282 */
3283
3284static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003285expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 char *id;
3288 switch (e->kind) {
3289 case Ellipsis_kind:
3290 return 1;
3291 case Num_kind:
3292 return PyObject_IsTrue(e->v.Num.n);
3293 case Str_kind:
3294 return PyObject_IsTrue(e->v.Str.s);
3295 case Name_kind:
3296 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003297 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003298 if (id && strcmp(id, "__debug__") == 0)
3299 return !c->c_optimize;
3300 return -1;
3301 case NameConstant_kind: {
3302 PyObject *o = e->v.NameConstant.value;
3303 if (o == Py_None)
3304 return 0;
3305 else if (o == Py_True)
3306 return 1;
3307 else if (o == Py_False)
3308 return 0;
3309 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 default:
3311 return -1;
3312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313}
3314
Guido van Rossumc2e20742006-02-27 22:32:47 +00003315/*
3316 Implements the with statement from PEP 343.
3317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003319
3320 with EXPR as VAR:
3321 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322
Guido van Rossumc2e20742006-02-27 22:32:47 +00003323 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324
Thomas Wouters477c8d52006-05-27 19:21:47 +00003325 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003326 exit = context.__exit__ # not calling it
3327 value = context.__enter__()
3328 try:
3329 VAR = value # if VAR present in the syntax
3330 BLOCK
3331 finally:
3332 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003334 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003336 exit(*exc)
3337 */
3338static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003339compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003340{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003341 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003342 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003343
3344 assert(s->kind == With_kind);
3345
Guido van Rossumc2e20742006-02-27 22:32:47 +00003346 block = compiler_new_block(c);
3347 finally = compiler_new_block(c);
3348 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003349 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003350
Thomas Wouters477c8d52006-05-27 19:21:47 +00003351 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003352 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003353 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003354
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003355 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003356 compiler_use_next_block(c, block);
3357 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003358 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003359 }
3360
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003361 if (item->optional_vars) {
3362 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003363 }
3364 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003366 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003367 }
3368
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003369 pos++;
3370 if (pos == asdl_seq_LEN(s->v.With.items))
3371 /* BLOCK code */
3372 VISIT_SEQ(c, stmt, s->v.With.body)
3373 else if (!compiler_with(c, s, pos))
3374 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003375
3376 /* End of try block; start the finally block */
3377 ADDOP(c, POP_BLOCK);
3378 compiler_pop_fblock(c, FINALLY_TRY, block);
3379
3380 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3381 compiler_use_next_block(c, finally);
3382 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003383 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003384
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003385 /* Finally block starts; context.__exit__ is on the stack under
3386 the exception or return information. Just issue our magic
3387 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003388 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003389
3390 /* Finally block ends. */
3391 ADDOP(c, END_FINALLY);
3392 compiler_pop_fblock(c, FINALLY_END, finally);
3393 return 1;
3394}
3395
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396static int
3397compiler_visit_expr(struct compiler *c, expr_ty e)
3398{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003399 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* If expr e has a different line number than the last expr/stmt,
3402 set a new line number for the next instruction.
3403 */
3404 if (e->lineno > c->u->u_lineno) {
3405 c->u->u_lineno = e->lineno;
3406 c->u->u_lineno_set = 0;
3407 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003408 /* Updating the column offset is always harmless. */
3409 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 switch (e->kind) {
3411 case BoolOp_kind:
3412 return compiler_boolop(c, e);
3413 case BinOp_kind:
3414 VISIT(c, expr, e->v.BinOp.left);
3415 VISIT(c, expr, e->v.BinOp.right);
3416 ADDOP(c, binop(c, e->v.BinOp.op));
3417 break;
3418 case UnaryOp_kind:
3419 VISIT(c, expr, e->v.UnaryOp.operand);
3420 ADDOP(c, unaryop(e->v.UnaryOp.op));
3421 break;
3422 case Lambda_kind:
3423 return compiler_lambda(c, e);
3424 case IfExp_kind:
3425 return compiler_ifexp(c, e);
3426 case Dict_kind:
3427 n = asdl_seq_LEN(e->v.Dict.values);
Victor Stinnerad9a0662013-11-19 22:23:20 +01003428 /* BUILD_MAP parameter is only used to preallocate the dictionary,
3429 it doesn't need to be exact */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3431 for (i = 0; i < n; i++) {
3432 VISIT(c, expr,
3433 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3434 VISIT(c, expr,
3435 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3436 ADDOP(c, STORE_MAP);
3437 }
3438 break;
3439 case Set_kind:
3440 n = asdl_seq_LEN(e->v.Set.elts);
3441 VISIT_SEQ(c, expr, e->v.Set.elts);
3442 ADDOP_I(c, BUILD_SET, n);
3443 break;
3444 case GeneratorExp_kind:
3445 return compiler_genexp(c, e);
3446 case ListComp_kind:
3447 return compiler_listcomp(c, e);
3448 case SetComp_kind:
3449 return compiler_setcomp(c, e);
3450 case DictComp_kind:
3451 return compiler_dictcomp(c, e);
3452 case Yield_kind:
3453 if (c->u->u_ste->ste_type != FunctionBlock)
3454 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003455 if (e->v.Yield.value) {
3456 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 }
3458 else {
3459 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3460 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003461 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003463 case YieldFrom_kind:
3464 if (c->u->u_ste->ste_type != FunctionBlock)
3465 return compiler_error(c, "'yield' outside function");
3466 VISIT(c, expr, e->v.YieldFrom.value);
3467 ADDOP(c, GET_ITER);
3468 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3469 ADDOP(c, YIELD_FROM);
3470 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 case Compare_kind:
3472 return compiler_compare(c, e);
3473 case Call_kind:
3474 return compiler_call(c, e);
3475 case Num_kind:
3476 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3477 break;
3478 case Str_kind:
3479 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3480 break;
3481 case Bytes_kind:
3482 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3483 break;
3484 case Ellipsis_kind:
3485 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3486 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003487 case NameConstant_kind:
3488 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3489 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 /* The following exprs can be assignment targets. */
3491 case Attribute_kind:
3492 if (e->v.Attribute.ctx != AugStore)
3493 VISIT(c, expr, e->v.Attribute.value);
3494 switch (e->v.Attribute.ctx) {
3495 case AugLoad:
3496 ADDOP(c, DUP_TOP);
3497 /* Fall through to load */
3498 case Load:
3499 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3500 break;
3501 case AugStore:
3502 ADDOP(c, ROT_TWO);
3503 /* Fall through to save */
3504 case Store:
3505 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3506 break;
3507 case Del:
3508 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3509 break;
3510 case Param:
3511 default:
3512 PyErr_SetString(PyExc_SystemError,
3513 "param invalid in attribute expression");
3514 return 0;
3515 }
3516 break;
3517 case Subscript_kind:
3518 switch (e->v.Subscript.ctx) {
3519 case AugLoad:
3520 VISIT(c, expr, e->v.Subscript.value);
3521 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3522 break;
3523 case Load:
3524 VISIT(c, expr, e->v.Subscript.value);
3525 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3526 break;
3527 case AugStore:
3528 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3529 break;
3530 case Store:
3531 VISIT(c, expr, e->v.Subscript.value);
3532 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3533 break;
3534 case Del:
3535 VISIT(c, expr, e->v.Subscript.value);
3536 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3537 break;
3538 case Param:
3539 default:
3540 PyErr_SetString(PyExc_SystemError,
3541 "param invalid in subscript expression");
3542 return 0;
3543 }
3544 break;
3545 case Starred_kind:
3546 switch (e->v.Starred.ctx) {
3547 case Store:
3548 /* In all legitimate cases, the Starred node was already replaced
3549 * by compiler_list/compiler_tuple. XXX: is that okay? */
3550 return compiler_error(c,
3551 "starred assignment target must be in a list or tuple");
3552 default:
3553 return compiler_error(c,
3554 "can use starred expression only as assignment target");
3555 }
3556 break;
3557 case Name_kind:
3558 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3559 /* child nodes of List and Tuple will have expr_context set */
3560 case List_kind:
3561 return compiler_list(c, e);
3562 case Tuple_kind:
3563 return compiler_tuple(c, e);
3564 }
3565 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566}
3567
3568static int
3569compiler_augassign(struct compiler *c, stmt_ty s)
3570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 expr_ty e = s->v.AugAssign.target;
3572 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 switch (e->kind) {
3577 case Attribute_kind:
3578 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3579 AugLoad, e->lineno, e->col_offset, c->c_arena);
3580 if (auge == NULL)
3581 return 0;
3582 VISIT(c, expr, auge);
3583 VISIT(c, expr, s->v.AugAssign.value);
3584 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3585 auge->v.Attribute.ctx = AugStore;
3586 VISIT(c, expr, auge);
3587 break;
3588 case Subscript_kind:
3589 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3590 AugLoad, e->lineno, e->col_offset, c->c_arena);
3591 if (auge == NULL)
3592 return 0;
3593 VISIT(c, expr, auge);
3594 VISIT(c, expr, s->v.AugAssign.value);
3595 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3596 auge->v.Subscript.ctx = AugStore;
3597 VISIT(c, expr, auge);
3598 break;
3599 case Name_kind:
3600 if (!compiler_nameop(c, e->v.Name.id, Load))
3601 return 0;
3602 VISIT(c, expr, s->v.AugAssign.value);
3603 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3604 return compiler_nameop(c, e->v.Name.id, Store);
3605 default:
3606 PyErr_Format(PyExc_SystemError,
3607 "invalid node type (%d) for augmented assignment",
3608 e->kind);
3609 return 0;
3610 }
3611 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612}
3613
3614static int
3615compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 struct fblockinfo *f;
3618 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3619 PyErr_SetString(PyExc_SystemError,
3620 "too many statically nested blocks");
3621 return 0;
3622 }
3623 f = &c->u->u_fblock[c->u->u_nfblocks++];
3624 f->fb_type = t;
3625 f->fb_block = b;
3626 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627}
3628
3629static void
3630compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 struct compiler_unit *u = c->u;
3633 assert(u->u_nfblocks > 0);
3634 u->u_nfblocks--;
3635 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3636 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637}
3638
Thomas Wouters89f507f2006-12-13 04:49:30 +00003639static int
3640compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 int i;
3642 struct compiler_unit *u = c->u;
3643 for (i = 0; i < u->u_nfblocks; ++i) {
3644 if (u->u_fblock[i].fb_type == LOOP)
3645 return 1;
3646 }
3647 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003648}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649/* Raises a SyntaxError and returns 0.
3650 If something goes wrong, a different exception may be raised.
3651*/
3652
3653static int
3654compiler_error(struct compiler *c, const char *errstr)
3655{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003656 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658
Victor Stinner14e461d2013-08-26 22:28:21 +02003659 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 if (!loc) {
3661 Py_INCREF(Py_None);
3662 loc = Py_None;
3663 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003664 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003665 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 if (!u)
3667 goto exit;
3668 v = Py_BuildValue("(zO)", errstr, u);
3669 if (!v)
3670 goto exit;
3671 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 Py_DECREF(loc);
3674 Py_XDECREF(u);
3675 Py_XDECREF(v);
3676 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677}
3678
3679static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680compiler_handle_subscr(struct compiler *c, const char *kind,
3681 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 /* XXX this code is duplicated */
3686 switch (ctx) {
3687 case AugLoad: /* fall through to Load */
3688 case Load: op = BINARY_SUBSCR; break;
3689 case AugStore:/* fall through to Store */
3690 case Store: op = STORE_SUBSCR; break;
3691 case Del: op = DELETE_SUBSCR; break;
3692 case Param:
3693 PyErr_Format(PyExc_SystemError,
3694 "invalid %s kind %d in subscript\n",
3695 kind, ctx);
3696 return 0;
3697 }
3698 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003699 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 }
3701 else if (ctx == AugStore) {
3702 ADDOP(c, ROT_THREE);
3703 }
3704 ADDOP(c, op);
3705 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003706}
3707
3708static int
3709compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 int n = 2;
3712 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 /* only handles the cases where BUILD_SLICE is emitted */
3715 if (s->v.Slice.lower) {
3716 VISIT(c, expr, s->v.Slice.lower);
3717 }
3718 else {
3719 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 if (s->v.Slice.upper) {
3723 VISIT(c, expr, s->v.Slice.upper);
3724 }
3725 else {
3726 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3727 }
3728
3729 if (s->v.Slice.step) {
3730 n++;
3731 VISIT(c, expr, s->v.Slice.step);
3732 }
3733 ADDOP_I(c, BUILD_SLICE, n);
3734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735}
3736
3737static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3739 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 switch (s->kind) {
3742 case Slice_kind:
3743 return compiler_slice(c, s, ctx);
3744 case Index_kind:
3745 VISIT(c, expr, s->v.Index.value);
3746 break;
3747 case ExtSlice_kind:
3748 default:
3749 PyErr_SetString(PyExc_SystemError,
3750 "extended slice invalid in nested slice");
3751 return 0;
3752 }
3753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754}
3755
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756static int
3757compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 char * kindname = NULL;
3760 switch (s->kind) {
3761 case Index_kind:
3762 kindname = "index";
3763 if (ctx != AugStore) {
3764 VISIT(c, expr, s->v.Index.value);
3765 }
3766 break;
3767 case Slice_kind:
3768 kindname = "slice";
3769 if (ctx != AugStore) {
3770 if (!compiler_slice(c, s, ctx))
3771 return 0;
3772 }
3773 break;
3774 case ExtSlice_kind:
3775 kindname = "extended slice";
3776 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01003777 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 for (i = 0; i < n; i++) {
3779 slice_ty sub = (slice_ty)asdl_seq_GET(
3780 s->v.ExtSlice.dims, i);
3781 if (!compiler_visit_nested_slice(c, sub, ctx))
3782 return 0;
3783 }
3784 ADDOP_I(c, BUILD_TUPLE, n);
3785 }
3786 break;
3787 default:
3788 PyErr_Format(PyExc_SystemError,
3789 "invalid subscript kind %d", s->kind);
3790 return 0;
3791 }
3792 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793}
3794
Thomas Wouters89f507f2006-12-13 04:49:30 +00003795/* End of the compiler section, beginning of the assembler section */
3796
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797/* do depth-first search of basic block graph, starting with block.
3798 post records the block indices in post-order.
3799
3800 XXX must handle implicit jumps from one block to next
3801*/
3802
Thomas Wouters89f507f2006-12-13 04:49:30 +00003803struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 PyObject *a_bytecode; /* string containing bytecode */
3805 int a_offset; /* offset into bytecode */
3806 int a_nblocks; /* number of reachable blocks */
3807 basicblock **a_postorder; /* list of blocks in dfs postorder */
3808 PyObject *a_lnotab; /* string containing lnotab */
3809 int a_lnotab_off; /* offset into lnotab */
3810 int a_lineno; /* last lineno of emitted instruction */
3811 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003812};
3813
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814static void
3815dfs(struct compiler *c, basicblock *b, struct assembler *a)
3816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 int i;
3818 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 if (b->b_seen)
3821 return;
3822 b->b_seen = 1;
3823 if (b->b_next != NULL)
3824 dfs(c, b->b_next, a);
3825 for (i = 0; i < b->b_iused; i++) {
3826 instr = &b->b_instr[i];
3827 if (instr->i_jrel || instr->i_jabs)
3828 dfs(c, instr->i_target, a);
3829 }
3830 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003831}
3832
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003833static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003834stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3835{
Larry Hastings3a907972013-11-23 14:49:22 -08003836 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 struct instr *instr;
3838 if (b->b_seen || b->b_startdepth >= depth)
3839 return maxdepth;
3840 b->b_seen = 1;
3841 b->b_startdepth = depth;
3842 for (i = 0; i < b->b_iused; i++) {
3843 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08003844 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
3845 if (effect == PY_INVALID_STACK_EFFECT) {
3846 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
3847 Py_FatalError("PyCompile_OpcodeStackEffect()");
3848 }
3849 depth += effect;
3850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 if (depth > maxdepth)
3852 maxdepth = depth;
3853 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3854 if (instr->i_jrel || instr->i_jabs) {
3855 target_depth = depth;
3856 if (instr->i_opcode == FOR_ITER) {
3857 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02003858 }
3859 else if (instr->i_opcode == SETUP_FINALLY ||
3860 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 target_depth = depth+3;
3862 if (target_depth > maxdepth)
3863 maxdepth = target_depth;
3864 }
Antoine Pitrou99614052014-05-23 11:46:03 +02003865 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
3866 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
3867 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 maxdepth = stackdepth_walk(c, instr->i_target,
3869 target_depth, maxdepth);
3870 if (instr->i_opcode == JUMP_ABSOLUTE ||
3871 instr->i_opcode == JUMP_FORWARD) {
3872 goto out; /* remaining code is dead */
3873 }
3874 }
3875 }
3876 if (b->b_next)
3877 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 b->b_seen = 0;
3880 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881}
3882
3883/* Find the flow path that needs the largest stack. We assume that
3884 * cycles in the flow graph have no net effect on the stack depth.
3885 */
3886static int
3887stackdepth(struct compiler *c)
3888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 basicblock *b, *entryblock;
3890 entryblock = NULL;
3891 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3892 b->b_seen = 0;
3893 b->b_startdepth = INT_MIN;
3894 entryblock = b;
3895 }
3896 if (!entryblock)
3897 return 0;
3898 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899}
3900
3901static int
3902assemble_init(struct assembler *a, int nblocks, int firstlineno)
3903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 memset(a, 0, sizeof(struct assembler));
3905 a->a_lineno = firstlineno;
3906 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3907 if (!a->a_bytecode)
3908 return 0;
3909 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3910 if (!a->a_lnotab)
3911 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01003912 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 PyErr_NoMemory();
3914 return 0;
3915 }
3916 a->a_postorder = (basicblock **)PyObject_Malloc(
3917 sizeof(basicblock *) * nblocks);
3918 if (!a->a_postorder) {
3919 PyErr_NoMemory();
3920 return 0;
3921 }
3922 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923}
3924
3925static void
3926assemble_free(struct assembler *a)
3927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 Py_XDECREF(a->a_bytecode);
3929 Py_XDECREF(a->a_lnotab);
3930 if (a->a_postorder)
3931 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932}
3933
3934/* Return the size of a basic block in bytes. */
3935
3936static int
3937instrsize(struct instr *instr)
3938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 if (!instr->i_hasarg)
3940 return 1; /* 1 byte for the opcode*/
3941 if (instr->i_oparg > 0xffff)
3942 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3943 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003944}
3945
3946static int
3947blocksize(basicblock *b)
3948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 int i;
3950 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 for (i = 0; i < b->b_iused; i++)
3953 size += instrsize(&b->b_instr[i]);
3954 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003955}
3956
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003957/* Appends a pair to the end of the line number table, a_lnotab, representing
3958 the instruction's bytecode offset and line number. See
3959 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003960
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003961static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003962assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003965 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 d_bytecode = a->a_offset - a->a_lineno_off;
3969 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 assert(d_bytecode >= 0);
3972 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 if(d_bytecode == 0 && d_lineno == 0)
3975 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 if (d_bytecode > 255) {
3978 int j, nbytes, ncodes = d_bytecode / 255;
3979 nbytes = a->a_lnotab_off + 2 * ncodes;
3980 len = PyBytes_GET_SIZE(a->a_lnotab);
3981 if (nbytes >= len) {
3982 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3983 len = nbytes;
3984 else if (len <= INT_MAX / 2)
3985 len *= 2;
3986 else {
3987 PyErr_NoMemory();
3988 return 0;
3989 }
3990 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3991 return 0;
3992 }
3993 lnotab = (unsigned char *)
3994 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3995 for (j = 0; j < ncodes; j++) {
3996 *lnotab++ = 255;
3997 *lnotab++ = 0;
3998 }
3999 d_bytecode -= ncodes * 255;
4000 a->a_lnotab_off += ncodes * 2;
4001 }
4002 assert(d_bytecode <= 255);
4003 if (d_lineno > 255) {
4004 int j, nbytes, ncodes = d_lineno / 255;
4005 nbytes = a->a_lnotab_off + 2 * ncodes;
4006 len = PyBytes_GET_SIZE(a->a_lnotab);
4007 if (nbytes >= len) {
4008 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4009 len = nbytes;
4010 else if (len <= INT_MAX / 2)
4011 len *= 2;
4012 else {
4013 PyErr_NoMemory();
4014 return 0;
4015 }
4016 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4017 return 0;
4018 }
4019 lnotab = (unsigned char *)
4020 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4021 *lnotab++ = d_bytecode;
4022 *lnotab++ = 255;
4023 d_bytecode = 0;
4024 for (j = 1; j < ncodes; j++) {
4025 *lnotab++ = 0;
4026 *lnotab++ = 255;
4027 }
4028 d_lineno -= ncodes * 255;
4029 a->a_lnotab_off += ncodes * 2;
4030 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 len = PyBytes_GET_SIZE(a->a_lnotab);
4033 if (a->a_lnotab_off + 2 >= len) {
4034 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4035 return 0;
4036 }
4037 lnotab = (unsigned char *)
4038 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 a->a_lnotab_off += 2;
4041 if (d_bytecode) {
4042 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004043 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 }
4045 else { /* First line of a block; def stmt, etc. */
4046 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004047 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 }
4049 a->a_lineno = i->i_lineno;
4050 a->a_lineno_off = a->a_offset;
4051 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004052}
4053
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004054/* assemble_emit()
4055 Extend the bytecode with a new instruction.
4056 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004057*/
4058
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004059static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004060assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 int size, arg = 0, ext = 0;
4063 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4064 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 size = instrsize(i);
4067 if (i->i_hasarg) {
4068 arg = i->i_oparg;
4069 ext = arg >> 16;
4070 }
4071 if (i->i_lineno && !assemble_lnotab(a, i))
4072 return 0;
4073 if (a->a_offset + size >= len) {
4074 if (len > PY_SSIZE_T_MAX / 2)
4075 return 0;
4076 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4077 return 0;
4078 }
4079 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4080 a->a_offset += size;
4081 if (size == 6) {
4082 assert(i->i_hasarg);
4083 *code++ = (char)EXTENDED_ARG;
4084 *code++ = ext & 0xff;
4085 *code++ = ext >> 8;
4086 arg &= 0xffff;
4087 }
4088 *code++ = i->i_opcode;
4089 if (i->i_hasarg) {
4090 assert(size == 3 || size == 6);
4091 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004092 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 }
4094 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004095}
4096
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004097static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 basicblock *b;
4101 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4102 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 /* Compute the size of each block and fixup jump args.
4105 Replace block pointer with position in bytecode. */
4106 do {
4107 totsize = 0;
4108 for (i = a->a_nblocks - 1; i >= 0; i--) {
4109 b = a->a_postorder[i];
4110 bsize = blocksize(b);
4111 b->b_offset = totsize;
4112 totsize += bsize;
4113 }
4114 last_extended_arg_count = extended_arg_count;
4115 extended_arg_count = 0;
4116 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4117 bsize = b->b_offset;
4118 for (i = 0; i < b->b_iused; i++) {
4119 struct instr *instr = &b->b_instr[i];
4120 /* Relative jumps are computed relative to
4121 the instruction pointer after fetching
4122 the jump instruction.
4123 */
4124 bsize += instrsize(instr);
4125 if (instr->i_jabs)
4126 instr->i_oparg = instr->i_target->b_offset;
4127 else if (instr->i_jrel) {
4128 int delta = instr->i_target->b_offset - bsize;
4129 instr->i_oparg = delta;
4130 }
4131 else
4132 continue;
4133 if (instr->i_oparg > 0xffff)
4134 extended_arg_count++;
4135 }
4136 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 /* XXX: This is an awful hack that could hurt performance, but
4139 on the bright side it should work until we come up
4140 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 The issue is that in the first loop blocksize() is called
4143 which calls instrsize() which requires i_oparg be set
4144 appropriately. There is a bootstrap problem because
4145 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 So we loop until we stop seeing new EXTENDED_ARGs.
4148 The only EXTENDED_ARGs that could be popping up are
4149 ones in jump instructions. So this should converge
4150 fairly quickly.
4151 */
4152 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004153}
4154
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004155static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004156dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 PyObject *tuple, *k, *v;
4159 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 tuple = PyTuple_New(size);
4162 if (tuple == NULL)
4163 return NULL;
4164 while (PyDict_Next(dict, &pos, &k, &v)) {
4165 i = PyLong_AS_LONG(v);
4166 /* The keys of the dictionary are tuples. (see compiler_add_o)
4167 The object we want is always first, though. */
4168 k = PyTuple_GET_ITEM(k, 0);
4169 Py_INCREF(k);
4170 assert((i - offset) < size);
4171 assert((i - offset) >= 0);
4172 PyTuple_SET_ITEM(tuple, i - offset, k);
4173 }
4174 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004175}
4176
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004177static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004181 int flags = 0;
4182 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004184 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 if (!ste->ste_unoptimized)
4186 flags |= CO_OPTIMIZED;
4187 if (ste->ste_nested)
4188 flags |= CO_NESTED;
4189 if (ste->ste_generator)
4190 flags |= CO_GENERATOR;
4191 if (ste->ste_varargs)
4192 flags |= CO_VARARGS;
4193 if (ste->ste_varkeywords)
4194 flags |= CO_VARKEYWORDS;
4195 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 /* (Only) inherit compilerflags in PyCF_MASK */
4198 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 n = PyDict_Size(c->u->u_freevars);
4201 if (n < 0)
4202 return -1;
4203 if (n == 0) {
4204 n = PyDict_Size(c->u->u_cellvars);
4205 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004206 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004208 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 }
4210 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004213}
4214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215static PyCodeObject *
4216makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 PyObject *tmp;
4219 PyCodeObject *co = NULL;
4220 PyObject *consts = NULL;
4221 PyObject *names = NULL;
4222 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 PyObject *name = NULL;
4224 PyObject *freevars = NULL;
4225 PyObject *cellvars = NULL;
4226 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004227 Py_ssize_t nlocals;
4228 int nlocals_int;
4229 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004230 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 tmp = dict_keys_inorder(c->u->u_consts, 0);
4233 if (!tmp)
4234 goto error;
4235 consts = PySequence_List(tmp); /* optimize_code requires a list */
4236 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 names = dict_keys_inorder(c->u->u_names, 0);
4239 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4240 if (!consts || !names || !varnames)
4241 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4244 if (!cellvars)
4245 goto error;
4246 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4247 if (!freevars)
4248 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004251 assert(nlocals < INT_MAX);
4252 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 flags = compute_code_flags(c);
4255 if (flags < 0)
4256 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4259 if (!bytecode)
4260 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4263 if (!tmp)
4264 goto error;
4265 Py_DECREF(consts);
4266 consts = tmp;
4267
Victor Stinnerf8e32212013-11-19 23:56:34 +01004268 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4269 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4270 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004271 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 bytecode, consts, names, varnames,
4273 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004274 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 c->u->u_firstlineno,
4276 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004277 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 Py_XDECREF(consts);
4279 Py_XDECREF(names);
4280 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 Py_XDECREF(name);
4282 Py_XDECREF(freevars);
4283 Py_XDECREF(cellvars);
4284 Py_XDECREF(bytecode);
4285 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004286}
4287
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004288
4289/* For debugging purposes only */
4290#if 0
4291static void
4292dump_instr(const struct instr *i)
4293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 const char *jrel = i->i_jrel ? "jrel " : "";
4295 const char *jabs = i->i_jabs ? "jabs " : "";
4296 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 *arg = '\0';
4299 if (i->i_hasarg)
4300 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4303 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004304}
4305
4306static void
4307dump_basicblock(const basicblock *b)
4308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 const char *seen = b->b_seen ? "seen " : "";
4310 const char *b_return = b->b_return ? "return " : "";
4311 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4312 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4313 if (b->b_instr) {
4314 int i;
4315 for (i = 0; i < b->b_iused; i++) {
4316 fprintf(stderr, " [%02d] ", i);
4317 dump_instr(b->b_instr + i);
4318 }
4319 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004320}
4321#endif
4322
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323static PyCodeObject *
4324assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 basicblock *b, *entryblock;
4327 struct assembler a;
4328 int i, j, nblocks;
4329 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 /* Make sure every block that falls off the end returns None.
4332 XXX NEXT_BLOCK() isn't quite right, because if the last
4333 block ends with a jump or return b_next shouldn't set.
4334 */
4335 if (!c->u->u_curblock->b_return) {
4336 NEXT_BLOCK(c);
4337 if (addNone)
4338 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4339 ADDOP(c, RETURN_VALUE);
4340 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 nblocks = 0;
4343 entryblock = NULL;
4344 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4345 nblocks++;
4346 entryblock = b;
4347 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 /* Set firstlineno if it wasn't explicitly set. */
4350 if (!c->u->u_firstlineno) {
4351 if (entryblock && entryblock->b_instr)
4352 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4353 else
4354 c->u->u_firstlineno = 1;
4355 }
4356 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4357 goto error;
4358 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 /* Can't modify the bytecode after computing jump offsets. */
4361 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 /* Emit code in reverse postorder from dfs. */
4364 for (i = a.a_nblocks - 1; i >= 0; i--) {
4365 b = a.a_postorder[i];
4366 for (j = 0; j < b->b_iused; j++)
4367 if (!assemble_emit(&a, &b->b_instr[j]))
4368 goto error;
4369 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4372 goto error;
4373 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4374 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004377 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 assemble_free(&a);
4379 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004380}
Georg Brandl8334fd92010-12-04 10:26:46 +00004381
4382#undef PyAST_Compile
4383PyAPI_FUNC(PyCodeObject *)
4384PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4385 PyArena *arena)
4386{
4387 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4388}
4389