blob: 9d3646eb91905119ff8dc9d833e72e75acd6b2da [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:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400884 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 case BINARY_MODULO:
886 case BINARY_ADD:
887 case BINARY_SUBTRACT:
888 case BINARY_SUBSCR:
889 case BINARY_FLOOR_DIVIDE:
890 case BINARY_TRUE_DIVIDE:
891 return -1;
892 case INPLACE_FLOOR_DIVIDE:
893 case INPLACE_TRUE_DIVIDE:
894 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case INPLACE_ADD:
897 case INPLACE_SUBTRACT:
898 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400899 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case INPLACE_MODULO:
901 return -1;
902 case STORE_SUBSCR:
903 return -3;
904 case STORE_MAP:
905 return -2;
906 case DELETE_SUBSCR:
907 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 case BINARY_LSHIFT:
910 case BINARY_RSHIFT:
911 case BINARY_AND:
912 case BINARY_XOR:
913 case BINARY_OR:
914 return -1;
915 case INPLACE_POWER:
916 return -1;
917 case GET_ITER:
918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case PRINT_EXPR:
921 return -1;
922 case LOAD_BUILD_CLASS:
923 return 1;
924 case INPLACE_LSHIFT:
925 case INPLACE_RSHIFT:
926 case INPLACE_AND:
927 case INPLACE_XOR:
928 case INPLACE_OR:
929 return -1;
930 case BREAK_LOOP:
931 return 0;
932 case SETUP_WITH:
933 return 7;
934 case WITH_CLEANUP:
935 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case RETURN_VALUE:
937 return -1;
938 case IMPORT_STAR:
939 return -1;
940 case YIELD_VALUE:
941 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500942 case YIELD_FROM:
943 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 case POP_BLOCK:
945 return 0;
946 case POP_EXCEPT:
947 return 0; /* -3 except if bad bytecode */
948 case END_FINALLY:
949 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 case STORE_NAME:
952 return -1;
953 case DELETE_NAME:
954 return 0;
955 case UNPACK_SEQUENCE:
956 return oparg-1;
957 case UNPACK_EX:
958 return (oparg&0xFF) + (oparg>>8);
959 case FOR_ITER:
960 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 case STORE_ATTR:
963 return -2;
964 case DELETE_ATTR:
965 return -1;
966 case STORE_GLOBAL:
967 return -1;
968 case DELETE_GLOBAL:
969 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case LOAD_CONST:
971 return 1;
972 case LOAD_NAME:
973 return 1;
974 case BUILD_TUPLE:
975 case BUILD_LIST:
976 case BUILD_SET:
977 return 1-oparg;
978 case BUILD_MAP:
979 return 1;
980 case LOAD_ATTR:
981 return 0;
982 case COMPARE_OP:
983 return -1;
984 case IMPORT_NAME:
985 return -1;
986 case IMPORT_FROM:
987 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case JUMP_FORWARD:
990 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
991 case JUMP_IF_FALSE_OR_POP: /* "" */
992 case JUMP_ABSOLUTE:
993 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 case POP_JUMP_IF_FALSE:
996 case POP_JUMP_IF_TRUE:
997 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case LOAD_GLOBAL:
1000 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case CONTINUE_LOOP:
1003 return 0;
1004 case SETUP_LOOP:
1005 return 0;
1006 case SETUP_EXCEPT:
1007 case SETUP_FINALLY:
1008 return 6; /* can push 3 values for the new exception
1009 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case LOAD_FAST:
1012 return 1;
1013 case STORE_FAST:
1014 return -1;
1015 case DELETE_FAST:
1016 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case RAISE_VARARGS:
1019 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001020#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case CALL_FUNCTION:
1022 return -NARGS(oparg);
1023 case CALL_FUNCTION_VAR:
1024 case CALL_FUNCTION_KW:
1025 return -NARGS(oparg)-1;
1026 case CALL_FUNCTION_VAR_KW:
1027 return -NARGS(oparg)-2;
1028 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001029 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001031 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001032#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case BUILD_SLICE:
1034 if (oparg == 3)
1035 return -2;
1036 else
1037 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case LOAD_CLOSURE:
1040 return 1;
1041 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001042 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 return 1;
1044 case STORE_DEREF:
1045 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001046 case DELETE_DEREF:
1047 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001049 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 }
Larry Hastings3a907972013-11-23 14:49:22 -08001051 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052}
1053
1054/* Add an opcode with no argument.
1055 Returns 0 on failure, 1 on success.
1056*/
1057
1058static int
1059compiler_addop(struct compiler *c, int opcode)
1060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 basicblock *b;
1062 struct instr *i;
1063 int off;
1064 off = compiler_next_instr(c, c->u->u_curblock);
1065 if (off < 0)
1066 return 0;
1067 b = c->u->u_curblock;
1068 i = &b->b_instr[off];
1069 i->i_opcode = opcode;
1070 i->i_hasarg = 0;
1071 if (opcode == RETURN_VALUE)
1072 b->b_return = 1;
1073 compiler_set_lineno(c, off);
1074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075}
1076
Victor Stinnerf8e32212013-11-19 23:56:34 +01001077static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyObject *t, *v;
1081 Py_ssize_t arg;
1082 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083
Serhiy Storchaka95949422013-08-27 19:40:23 +03001084 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1086 if (PyFloat_Check(o)) {
1087 d = PyFloat_AS_DOUBLE(o);
1088 /* all we need is to make the tuple different in either the 0.0
1089 * or -0.0 case from all others, just to avoid the "coercion".
1090 */
1091 if (d == 0.0 && copysign(1.0, d) < 0.0)
1092 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1093 else
1094 t = PyTuple_Pack(2, o, o->ob_type);
1095 }
1096 else if (PyComplex_Check(o)) {
1097 Py_complex z;
1098 int real_negzero, imag_negzero;
1099 /* For the complex case we must make complex(x, 0.)
1100 different from complex(x, -0.) and complex(0., y)
1101 different from complex(-0., y), for any x and y.
1102 All four complex zeros must be distinguished.*/
1103 z = PyComplex_AsCComplex(o);
1104 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1105 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1106 if (real_negzero && imag_negzero) {
1107 t = PyTuple_Pack(5, o, o->ob_type,
1108 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 else if (imag_negzero) {
1111 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001112 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 else if (real_negzero) {
1114 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1115 }
1116 else {
1117 t = PyTuple_Pack(2, o, o->ob_type);
1118 }
1119 }
1120 else {
1121 t = PyTuple_Pack(2, o, o->ob_type);
1122 }
1123 if (t == NULL)
1124 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 v = PyDict_GetItem(dict, t);
1127 if (!v) {
1128 if (PyErr_Occurred())
1129 return -1;
1130 arg = PyDict_Size(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001131 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (!v) {
1133 Py_DECREF(t);
1134 return -1;
1135 }
1136 if (PyDict_SetItem(dict, t, v) < 0) {
1137 Py_DECREF(t);
1138 Py_DECREF(v);
1139 return -1;
1140 }
1141 Py_DECREF(v);
1142 }
1143 else
1144 arg = PyLong_AsLong(v);
1145 Py_DECREF(t);
1146 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147}
1148
1149static int
1150compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001153 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return compiler_addop_i(c, opcode, arg);
1157}
1158
1159static int
1160compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001163 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1165 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001166 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 arg = compiler_add_o(c, dict, mangled);
1168 Py_DECREF(mangled);
1169 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001170 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171 return compiler_addop_i(c, opcode, arg);
1172}
1173
1174/* Add an opcode with an integer argument.
1175 Returns 0 on failure, 1 on success.
1176*/
1177
1178static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001179compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 struct instr *i;
1182 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001183
1184 /* Integer arguments are limit to 16-bit. There is an extension for 32-bit
1185 integer arguments. */
Victor Stinnerf8e32212013-11-19 23:56:34 +01001186 assert((-2147483647-1) <= oparg);
1187 assert(oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 off = compiler_next_instr(c, c->u->u_curblock);
1190 if (off < 0)
1191 return 0;
1192 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001193 i->i_opcode = opcode;
1194 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 i->i_hasarg = 1;
1196 compiler_set_lineno(c, off);
1197 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198}
1199
1200static int
1201compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 struct instr *i;
1204 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 assert(b != NULL);
1207 off = compiler_next_instr(c, c->u->u_curblock);
1208 if (off < 0)
1209 return 0;
1210 i = &c->u->u_curblock->b_instr[off];
1211 i->i_opcode = opcode;
1212 i->i_target = b;
1213 i->i_hasarg = 1;
1214 if (absolute)
1215 i->i_jabs = 1;
1216 else
1217 i->i_jrel = 1;
1218 compiler_set_lineno(c, off);
1219 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220}
1221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1223 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224 it as the current block. NEXT_BLOCK() also creates an implicit jump
1225 from the current block to the new block.
1226*/
1227
Thomas Wouters89f507f2006-12-13 04:49:30 +00001228/* The returns inside these macros make it impossible to decref objects
1229 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230*/
1231
1232
1233#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (compiler_use_new_block((C)) == NULL) \
1235 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
1238#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (compiler_next_block((C)) == NULL) \
1240 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241}
1242
1243#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop((C), (OP))) \
1245 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001248#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (!compiler_addop((C), (OP))) { \
1250 compiler_exit_scope(c); \
1251 return 0; \
1252 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001253}
1254
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1257 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258}
1259
1260#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1262 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263}
1264
1265#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (!compiler_addop_i((C), (OP), (O))) \
1267 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268}
1269
1270#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 if (!compiler_addop_j((C), (OP), (O), 1)) \
1272 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273}
1274
1275#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (!compiler_addop_j((C), (OP), (O), 0)) \
1277 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278}
1279
1280/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1281 the ASDL name to synthesize the name of the C type and the visit function.
1282*/
1283
1284#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_visit_ ## TYPE((C), (V))) \
1286 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001289#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (!compiler_visit_ ## TYPE((C), (V))) { \
1291 compiler_exit_scope(c); \
1292 return 0; \
1293 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001294}
1295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (!compiler_visit_slice((C), (V), (CTX))) \
1298 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299}
1300
1301#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 int _i; \
1303 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1304 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1305 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1306 if (!compiler_visit_ ## TYPE((C), elt)) \
1307 return 0; \
1308 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001311#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 int _i; \
1313 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1314 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1315 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1316 if (!compiler_visit_ ## TYPE((C), elt)) { \
1317 compiler_exit_scope(c); \
1318 return 0; \
1319 } \
1320 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001321}
1322
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323static int
1324compiler_isdocstring(stmt_ty s)
1325{
1326 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001327 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328 return s->v.Expr.value->kind == Str_kind;
1329}
1330
1331/* Compile a sequence of statements, checking for a docstring. */
1332
1333static int
1334compiler_body(struct compiler *c, asdl_seq *stmts)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 int i = 0;
1337 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (!asdl_seq_LEN(stmts))
1340 return 1;
1341 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001342 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 /* don't generate docstrings if -OO */
1344 i = 1;
1345 VISIT(c, expr, st->v.Expr.value);
1346 if (!compiler_nameop(c, __doc__, Store))
1347 return 0;
1348 }
1349 for (; i < asdl_seq_LEN(stmts); i++)
1350 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1351 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352}
1353
1354static PyCodeObject *
1355compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 PyCodeObject *co;
1358 int addNone = 1;
1359 static PyObject *module;
1360 if (!module) {
1361 module = PyUnicode_InternFromString("<module>");
1362 if (!module)
1363 return NULL;
1364 }
1365 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001366 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return NULL;
1368 switch (mod->kind) {
1369 case Module_kind:
1370 if (!compiler_body(c, mod->v.Module.body)) {
1371 compiler_exit_scope(c);
1372 return 0;
1373 }
1374 break;
1375 case Interactive_kind:
1376 c->c_interactive = 1;
1377 VISIT_SEQ_IN_SCOPE(c, stmt,
1378 mod->v.Interactive.body);
1379 break;
1380 case Expression_kind:
1381 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1382 addNone = 0;
1383 break;
1384 case Suite_kind:
1385 PyErr_SetString(PyExc_SystemError,
1386 "suite should not be possible");
1387 return 0;
1388 default:
1389 PyErr_Format(PyExc_SystemError,
1390 "module kind %d should not be possible",
1391 mod->kind);
1392 return 0;
1393 }
1394 co = assemble(c, addNone);
1395 compiler_exit_scope(c);
1396 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001397}
1398
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399/* The test for LOCAL must come before the test for FREE in order to
1400 handle classes where name is both local and free. The local var is
1401 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001402*/
1403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404static int
1405get_ref_type(struct compiler *c, PyObject *name)
1406{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001407 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001408 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1409 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1410 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001411 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (scope == 0) {
1413 char buf[350];
1414 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001415 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 "symbols: %s\nlocals: %s\nglobals: %s",
1417 PyBytes_AS_STRING(name),
1418 PyBytes_AS_STRING(c->u->u_name),
1419 PyObject_REPR(c->u->u_ste->ste_id),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyObject_REPR(c->u->u_ste->ste_symbols),
1421 PyObject_REPR(c->u->u_varnames),
1422 PyObject_REPR(c->u->u_names)
1423 );
1424 Py_FatalError(buf);
1425 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428}
1429
1430static int
1431compiler_lookup_arg(PyObject *dict, PyObject *name)
1432{
1433 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001436 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001438 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001440 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001441 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442}
1443
1444static int
Victor Stinnerad9a0662013-11-19 22:23:20 +01001445compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001447 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001448 if (qualname == NULL)
1449 qualname = co->co_name;
1450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (free == 0) {
1452 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001453 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 ADDOP_I(c, MAKE_FUNCTION, args);
1455 return 1;
1456 }
1457 for (i = 0; i < free; ++i) {
1458 /* Bypass com_addop_varname because it will generate
1459 LOAD_DEREF but LOAD_CLOSURE is needed.
1460 */
1461 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1462 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 /* Special case: If a class contains a method with a
1465 free variable that has the same name as a method,
1466 the name will be considered free *and* local in the
1467 class. It should be handled by the closure, as
1468 well as by the normal name loookup logic.
1469 */
1470 reftype = get_ref_type(c, name);
1471 if (reftype == CELL)
1472 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1473 else /* (reftype == FREE) */
1474 arg = compiler_lookup_arg(c->u->u_freevars, name);
1475 if (arg == -1) {
1476 fprintf(stderr,
1477 "lookup %s in %s %d %d\n"
1478 "freevars of %s: %s\n",
1479 PyObject_REPR(name),
1480 PyBytes_AS_STRING(c->u->u_name),
1481 reftype, arg,
1482 _PyUnicode_AsString(co->co_name),
1483 PyObject_REPR(co->co_freevars));
1484 Py_FatalError("compiler_make_closure()");
1485 }
1486 ADDOP_I(c, LOAD_CLOSURE, arg);
1487 }
1488 ADDOP_I(c, BUILD_TUPLE, free);
1489 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001490 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 ADDOP_I(c, MAKE_CLOSURE, args);
1492 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493}
1494
1495static int
1496compiler_decorators(struct compiler *c, asdl_seq* decos)
1497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (!decos)
1501 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1504 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1505 }
1506 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507}
1508
1509static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001510compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 int i, default_count = 0;
1514 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1515 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1516 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1517 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001518 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1519 if (!mangled)
1520 return -1;
1521 ADDOP_O(c, LOAD_CONST, mangled, consts);
1522 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (!compiler_visit_expr(c, default_)) {
1524 return -1;
1525 }
1526 default_count++;
1527 }
1528 }
1529 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001530}
1531
1532static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001533compiler_visit_argannotation(struct compiler *c, identifier id,
1534 expr_ty annotation, PyObject *names)
1535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001537 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001539 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001540 if (!mangled)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 return -1;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001542 if (PyList_Append(names, mangled) < 0) {
1543 Py_DECREF(mangled);
1544 return -1;
1545 }
1546 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 }
1548 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001549}
1550
1551static int
1552compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1553 PyObject *names)
1554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 int i, error;
1556 for (i = 0; i < asdl_seq_LEN(args); i++) {
1557 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1558 error = compiler_visit_argannotation(
1559 c,
1560 arg->arg,
1561 arg->annotation,
1562 names);
1563 if (error)
1564 return error;
1565 }
1566 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001567}
1568
1569static int
1570compiler_visit_annotations(struct compiler *c, arguments_ty args,
1571 expr_ty returns)
1572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 /* Push arg annotations and a list of the argument names. Return the #
1574 of items pushed. The expressions are evaluated out-of-order wrt the
1575 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1578 */
1579 static identifier return_str;
1580 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001581 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 names = PyList_New(0);
1583 if (!names)
1584 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (compiler_visit_argannotations(c, args->args, names))
1587 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001588 if (args->vararg && args->vararg->annotation &&
1589 compiler_visit_argannotation(c, args->vararg->arg,
1590 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 goto error;
1592 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1593 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001594 if (args->kwarg && args->kwarg->annotation &&
1595 compiler_visit_argannotation(c, args->kwarg->arg,
1596 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 if (!return_str) {
1600 return_str = PyUnicode_InternFromString("return");
1601 if (!return_str)
1602 goto error;
1603 }
1604 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1605 goto error;
1606 }
1607
1608 len = PyList_GET_SIZE(names);
1609 if (len > 65534) {
1610 /* len must fit in 16 bits, and len is incremented below */
1611 PyErr_SetString(PyExc_SyntaxError,
1612 "too many annotations");
1613 goto error;
1614 }
1615 if (len) {
1616 /* convert names to a tuple and place on stack */
1617 PyObject *elt;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001618 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 PyObject *s = PyTuple_New(len);
1620 if (!s)
1621 goto error;
1622 for (i = 0; i < len; i++) {
1623 elt = PyList_GET_ITEM(names, i);
1624 Py_INCREF(elt);
1625 PyTuple_SET_ITEM(s, i, elt);
1626 }
1627 ADDOP_O(c, LOAD_CONST, s, consts);
1628 Py_DECREF(s);
1629 len++; /* include the just-pushed tuple */
1630 }
1631 Py_DECREF(names);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001632
1633 /* We just checked that len <= 65535, see above */
1634 return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
Neal Norwitzc1505362006-12-28 06:47:50 +00001635
1636error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 Py_DECREF(names);
1638 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001639}
1640
1641static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001642compiler_function(struct compiler *c, stmt_ty s)
1643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001645 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 arguments_ty args = s->v.FunctionDef.args;
1647 expr_ty returns = s->v.FunctionDef.returns;
1648 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1649 stmt_ty st;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001650 Py_ssize_t i, n, arglength;
1651 int docstring, kw_default_count = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (!compiler_decorators(c, decos))
1657 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001658 if (args->defaults)
1659 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (args->kwonlyargs) {
1661 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1662 args->kw_defaults);
1663 if (res < 0)
1664 return 0;
1665 kw_default_count = res;
1666 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 num_annotations = compiler_visit_annotations(c, args, returns);
1668 if (num_annotations < 0)
1669 return 0;
1670 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001671
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001672 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1673 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 s->lineno))
1675 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1678 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001679 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 first_const = st->v.Expr.value->v.Str.s;
1681 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1682 compiler_exit_scope(c);
1683 return 0;
1684 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 c->u->u_argcount = asdl_seq_LEN(args->args);
1687 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1688 n = asdl_seq_LEN(s->v.FunctionDef.body);
1689 /* if there was a docstring, we need to skip the first statement */
1690 for (i = docstring; i < n; i++) {
1691 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1692 VISIT_IN_SCOPE(c, stmt, st);
1693 }
1694 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001695 qualname = c->u->u_qualname;
1696 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001698 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001699 Py_XDECREF(qualname);
1700 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 arglength = asdl_seq_LEN(args->defaults);
1705 arglength |= kw_default_count << 8;
1706 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001707 compiler_make_closure(c, co, arglength, qualname);
1708 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 /* decorators */
1712 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1713 ADDOP_I(c, CALL_FUNCTION, 1);
1714 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717}
1718
1719static int
1720compiler_class(struct compiler *c, stmt_ty s)
1721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyCodeObject *co;
1723 PyObject *str;
1724 int i;
1725 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (!compiler_decorators(c, decos))
1728 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 /* ultimately generate code for:
1731 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1732 where:
1733 <func> is a function/closure created from the class body;
1734 it has a single argument (__locals__) where the dict
1735 (or MutableSequence) representing the locals is passed
1736 <name> is the class name
1737 <bases> is the positional arguments and *varargs argument
1738 <keywords> is the keyword arguments and **kwds argument
1739 This borrows from compiler_call.
1740 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001743 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1744 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 return 0;
1746 /* this block represents what we do in the new scope */
1747 {
1748 /* use the class name for name mangling */
1749 Py_INCREF(s->v.ClassDef.name);
1750 Py_XDECREF(c->u->u_private);
1751 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 /* load (global) __name__ ... */
1753 str = PyUnicode_InternFromString("__name__");
1754 if (!str || !compiler_nameop(c, str, Load)) {
1755 Py_XDECREF(str);
1756 compiler_exit_scope(c);
1757 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 Py_DECREF(str);
1760 /* ... and store it as __module__ */
1761 str = PyUnicode_InternFromString("__module__");
1762 if (!str || !compiler_nameop(c, str, Store)) {
1763 Py_XDECREF(str);
1764 compiler_exit_scope(c);
1765 return 0;
1766 }
1767 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001768 assert(c->u->u_qualname);
1769 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001770 str = PyUnicode_InternFromString("__qualname__");
1771 if (!str || !compiler_nameop(c, str, Store)) {
1772 Py_XDECREF(str);
1773 compiler_exit_scope(c);
1774 return 0;
1775 }
1776 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 /* compile the body proper */
1778 if (!compiler_body(c, s->v.ClassDef.body)) {
1779 compiler_exit_scope(c);
1780 return 0;
1781 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001782 if (c->u->u_ste->ste_needs_class_closure) {
1783 /* return the (empty) __class__ cell */
1784 str = PyUnicode_InternFromString("__class__");
1785 if (str == NULL) {
1786 compiler_exit_scope(c);
1787 return 0;
1788 }
1789 i = compiler_lookup_arg(c->u->u_cellvars, str);
1790 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001791 if (i < 0) {
1792 compiler_exit_scope(c);
1793 return 0;
1794 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001795 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Return the cell where to store __class__ */
1797 ADDOP_I(c, LOAD_CLOSURE, i);
1798 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001799 else {
1800 assert(PyDict_Size(c->u->u_cellvars) == 0);
1801 /* This happens when nobody references the cell. Return None. */
1802 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1803 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1805 /* create the code object */
1806 co = assemble(c, 1);
1807 }
1808 /* leave the new scope */
1809 compiler_exit_scope(c);
1810 if (co == NULL)
1811 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 /* 2. load the 'build_class' function */
1814 ADDOP(c, LOAD_BUILD_CLASS);
1815
1816 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001817 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 Py_DECREF(co);
1819
1820 /* 4. load class name */
1821 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1822
1823 /* 5. generate the rest of the code for the call */
1824 if (!compiler_call_helper(c, 2,
1825 s->v.ClassDef.bases,
1826 s->v.ClassDef.keywords,
1827 s->v.ClassDef.starargs,
1828 s->v.ClassDef.kwargs))
1829 return 0;
1830
1831 /* 6. apply decorators */
1832 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1833 ADDOP_I(c, CALL_FUNCTION, 1);
1834 }
1835
1836 /* 7. store into <name> */
1837 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1838 return 0;
1839 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840}
1841
1842static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001843compiler_ifexp(struct compiler *c, expr_ty e)
1844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 basicblock *end, *next;
1846
1847 assert(e->kind == IfExp_kind);
1848 end = compiler_new_block(c);
1849 if (end == NULL)
1850 return 0;
1851 next = compiler_new_block(c);
1852 if (next == NULL)
1853 return 0;
1854 VISIT(c, expr, e->v.IfExp.test);
1855 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1856 VISIT(c, expr, e->v.IfExp.body);
1857 ADDOP_JREL(c, JUMP_FORWARD, end);
1858 compiler_use_next_block(c, next);
1859 VISIT(c, expr, e->v.IfExp.orelse);
1860 compiler_use_next_block(c, end);
1861 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001862}
1863
1864static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865compiler_lambda(struct compiler *c, expr_ty e)
1866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001868 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 static identifier name;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001870 int kw_default_count = 0;
1871 Py_ssize_t arglength;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 arguments_ty args = e->v.Lambda.args;
1873 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (!name) {
1876 name = PyUnicode_InternFromString("<lambda>");
1877 if (!name)
1878 return 0;
1879 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001881 if (args->defaults)
1882 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (args->kwonlyargs) {
1884 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1885 args->kw_defaults);
1886 if (res < 0) return 0;
1887 kw_default_count = res;
1888 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001889 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001890 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 /* Make None the first constant, so the lambda can't have a
1894 docstring. */
1895 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1896 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 c->u->u_argcount = asdl_seq_LEN(args->args);
1899 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1900 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1901 if (c->u->u_ste->ste_generator) {
1902 ADDOP_IN_SCOPE(c, POP_TOP);
1903 }
1904 else {
1905 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1906 }
1907 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001908 qualname = c->u->u_qualname;
1909 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001911 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 arglength = asdl_seq_LEN(args->defaults);
1915 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001916 compiler_make_closure(c, co, arglength, qualname);
1917 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 Py_DECREF(co);
1919
1920 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921}
1922
1923static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924compiler_if(struct compiler *c, stmt_ty s)
1925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 basicblock *end, *next;
1927 int constant;
1928 assert(s->kind == If_kind);
1929 end = compiler_new_block(c);
1930 if (end == NULL)
1931 return 0;
1932
Georg Brandl8334fd92010-12-04 10:26:46 +00001933 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* constant = 0: "if 0"
1935 * constant = 1: "if 1", "if 2", ...
1936 * constant = -1: rest */
1937 if (constant == 0) {
1938 if (s->v.If.orelse)
1939 VISIT_SEQ(c, stmt, s->v.If.orelse);
1940 } else if (constant == 1) {
1941 VISIT_SEQ(c, stmt, s->v.If.body);
1942 } else {
1943 if (s->v.If.orelse) {
1944 next = compiler_new_block(c);
1945 if (next == NULL)
1946 return 0;
1947 }
1948 else
1949 next = end;
1950 VISIT(c, expr, s->v.If.test);
1951 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1952 VISIT_SEQ(c, stmt, s->v.If.body);
1953 ADDOP_JREL(c, JUMP_FORWARD, end);
1954 if (s->v.If.orelse) {
1955 compiler_use_next_block(c, next);
1956 VISIT_SEQ(c, stmt, s->v.If.orelse);
1957 }
1958 }
1959 compiler_use_next_block(c, end);
1960 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961}
1962
1963static int
1964compiler_for(struct compiler *c, stmt_ty s)
1965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 start = compiler_new_block(c);
1969 cleanup = compiler_new_block(c);
1970 end = compiler_new_block(c);
1971 if (start == NULL || end == NULL || cleanup == NULL)
1972 return 0;
1973 ADDOP_JREL(c, SETUP_LOOP, end);
1974 if (!compiler_push_fblock(c, LOOP, start))
1975 return 0;
1976 VISIT(c, expr, s->v.For.iter);
1977 ADDOP(c, GET_ITER);
1978 compiler_use_next_block(c, start);
1979 ADDOP_JREL(c, FOR_ITER, cleanup);
1980 VISIT(c, expr, s->v.For.target);
1981 VISIT_SEQ(c, stmt, s->v.For.body);
1982 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1983 compiler_use_next_block(c, cleanup);
1984 ADDOP(c, POP_BLOCK);
1985 compiler_pop_fblock(c, LOOP, start);
1986 VISIT_SEQ(c, stmt, s->v.For.orelse);
1987 compiler_use_next_block(c, end);
1988 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989}
1990
1991static int
1992compiler_while(struct compiler *c, stmt_ty s)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001995 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (constant == 0) {
1998 if (s->v.While.orelse)
1999 VISIT_SEQ(c, stmt, s->v.While.orelse);
2000 return 1;
2001 }
2002 loop = compiler_new_block(c);
2003 end = compiler_new_block(c);
2004 if (constant == -1) {
2005 anchor = compiler_new_block(c);
2006 if (anchor == NULL)
2007 return 0;
2008 }
2009 if (loop == NULL || end == NULL)
2010 return 0;
2011 if (s->v.While.orelse) {
2012 orelse = compiler_new_block(c);
2013 if (orelse == NULL)
2014 return 0;
2015 }
2016 else
2017 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 ADDOP_JREL(c, SETUP_LOOP, end);
2020 compiler_use_next_block(c, loop);
2021 if (!compiler_push_fblock(c, LOOP, loop))
2022 return 0;
2023 if (constant == -1) {
2024 VISIT(c, expr, s->v.While.test);
2025 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2026 }
2027 VISIT_SEQ(c, stmt, s->v.While.body);
2028 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* XXX should the two POP instructions be in a separate block
2031 if there is no else clause ?
2032 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 if (constant == -1) {
2035 compiler_use_next_block(c, anchor);
2036 ADDOP(c, POP_BLOCK);
2037 }
2038 compiler_pop_fblock(c, LOOP, loop);
2039 if (orelse != NULL) /* what if orelse is just pass? */
2040 VISIT_SEQ(c, stmt, s->v.While.orelse);
2041 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044}
2045
2046static int
2047compiler_continue(struct compiler *c)
2048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2050 static const char IN_FINALLY_ERROR_MSG[] =
2051 "'continue' not supported inside 'finally' clause";
2052 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (!c->u->u_nfblocks)
2055 return compiler_error(c, LOOP_ERROR_MSG);
2056 i = c->u->u_nfblocks - 1;
2057 switch (c->u->u_fblock[i].fb_type) {
2058 case LOOP:
2059 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2060 break;
2061 case EXCEPT:
2062 case FINALLY_TRY:
2063 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2064 /* Prevent continue anywhere under a finally
2065 even if hidden in a sub-try or except. */
2066 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2067 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2068 }
2069 if (i == -1)
2070 return compiler_error(c, LOOP_ERROR_MSG);
2071 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2072 break;
2073 case FINALLY_END:
2074 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2075 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078}
2079
2080/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081
2082 SETUP_FINALLY L
2083 <code for body>
2084 POP_BLOCK
2085 LOAD_CONST <None>
2086 L: <code for finalbody>
2087 END_FINALLY
2088
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 The special instructions use the block stack. Each block
2090 stack entry contains the instruction that created it (here
2091 SETUP_FINALLY), the level of the value stack at the time the
2092 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 Pushes the current value stack level and the label
2096 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 Pops en entry from the block stack, and pops the value
2099 stack until its level is the same as indicated on the
2100 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 Pops a variable number of entries from the *value* stack
2103 and re-raises the exception they specify. The number of
2104 entries popped depends on the (pseudo) exception type.
2105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 The block stack is unwound when an exception is raised:
2107 when a SETUP_FINALLY entry is found, the exception is pushed
2108 onto the value stack (and the exception condition is cleared),
2109 and the interpreter jumps to the label gotten from the block
2110 stack.
2111*/
2112
2113static int
2114compiler_try_finally(struct compiler *c, stmt_ty s)
2115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 basicblock *body, *end;
2117 body = compiler_new_block(c);
2118 end = compiler_new_block(c);
2119 if (body == NULL || end == NULL)
2120 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 ADDOP_JREL(c, SETUP_FINALLY, end);
2123 compiler_use_next_block(c, body);
2124 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2125 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002126 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2127 if (!compiler_try_except(c, s))
2128 return 0;
2129 }
2130 else {
2131 VISIT_SEQ(c, stmt, s->v.Try.body);
2132 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 ADDOP(c, POP_BLOCK);
2134 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2137 compiler_use_next_block(c, end);
2138 if (!compiler_push_fblock(c, FINALLY_END, end))
2139 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002140 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 ADDOP(c, END_FINALLY);
2142 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145}
2146
2147/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002148 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 (The contents of the value stack is shown in [], with the top
2150 at the right; 'tb' is trace-back info, 'val' the exception's
2151 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152
2153 Value stack Label Instruction Argument
2154 [] SETUP_EXCEPT L1
2155 [] <code for S>
2156 [] POP_BLOCK
2157 [] JUMP_FORWARD L0
2158
2159 [tb, val, exc] L1: DUP )
2160 [tb, val, exc, exc] <evaluate E1> )
2161 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2162 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2163 [tb, val, exc] POP
2164 [tb, val] <assign to V1> (or POP if no V1)
2165 [tb] POP
2166 [] <code for S1>
2167 JUMP_FORWARD L0
2168
2169 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 .............................etc.......................
2171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2173
2174 [] L0: <next statement>
2175
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 Of course, parts are not generated if Vi or Ei is not present.
2177*/
2178static int
2179compiler_try_except(struct compiler *c, stmt_ty s)
2180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002182 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 body = compiler_new_block(c);
2185 except = compiler_new_block(c);
2186 orelse = compiler_new_block(c);
2187 end = compiler_new_block(c);
2188 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2189 return 0;
2190 ADDOP_JREL(c, SETUP_EXCEPT, except);
2191 compiler_use_next_block(c, body);
2192 if (!compiler_push_fblock(c, EXCEPT, body))
2193 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002194 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 ADDOP(c, POP_BLOCK);
2196 compiler_pop_fblock(c, EXCEPT, body);
2197 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002198 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 compiler_use_next_block(c, except);
2200 for (i = 0; i < n; i++) {
2201 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002202 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 if (!handler->v.ExceptHandler.type && i < n-1)
2204 return compiler_error(c, "default 'except:' must be last");
2205 c->u->u_lineno_set = 0;
2206 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002207 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 except = compiler_new_block(c);
2209 if (except == NULL)
2210 return 0;
2211 if (handler->v.ExceptHandler.type) {
2212 ADDOP(c, DUP_TOP);
2213 VISIT(c, expr, handler->v.ExceptHandler.type);
2214 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2215 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2216 }
2217 ADDOP(c, POP_TOP);
2218 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002219 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002220
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002221 cleanup_end = compiler_new_block(c);
2222 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002223 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002224 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002225
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002226 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2227 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002229 /*
2230 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002231 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002232 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002233 try:
2234 # body
2235 finally:
2236 name = None
2237 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002238 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002240 /* second try: */
2241 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2242 compiler_use_next_block(c, cleanup_body);
2243 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2244 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002246 /* second # body */
2247 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2248 ADDOP(c, POP_BLOCK);
2249 ADDOP(c, POP_EXCEPT);
2250 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002252 /* finally: */
2253 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2254 compiler_use_next_block(c, cleanup_end);
2255 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2256 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002258 /* name = None */
2259 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2260 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002262 /* del name */
2263 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002265 ADDOP(c, END_FINALLY);
2266 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 }
2268 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002269 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002271 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002272 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002273 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274
Guido van Rossumb940e112007-01-10 16:19:56 +00002275 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002276 ADDOP(c, POP_TOP);
2277 compiler_use_next_block(c, cleanup_body);
2278 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2279 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002281 ADDOP(c, POP_EXCEPT);
2282 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 }
2284 ADDOP_JREL(c, JUMP_FORWARD, end);
2285 compiler_use_next_block(c, except);
2286 }
2287 ADDOP(c, END_FINALLY);
2288 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002289 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 compiler_use_next_block(c, end);
2291 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292}
2293
2294static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002295compiler_try(struct compiler *c, stmt_ty s) {
2296 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2297 return compiler_try_finally(c, s);
2298 else
2299 return compiler_try_except(c, s);
2300}
2301
2302
2303static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304compiler_import_as(struct compiler *c, identifier name, identifier asname)
2305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* The IMPORT_NAME opcode was already generated. This function
2307 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 If there is a dot in name, we need to split it and emit a
2310 LOAD_ATTR for each name.
2311 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002312 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2313 PyUnicode_GET_LENGTH(name), 1);
2314 if (dot == -2)
2315 return -1;
2316 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002318 Py_ssize_t pos = dot + 1;
2319 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002321 dot = PyUnicode_FindChar(name, '.', pos,
2322 PyUnicode_GET_LENGTH(name), 1);
2323 if (dot == -2)
2324 return -1;
2325 attr = PyUnicode_Substring(name, pos,
2326 (dot != -1) ? dot :
2327 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (!attr)
2329 return -1;
2330 ADDOP_O(c, LOAD_ATTR, attr, names);
2331 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002332 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 }
2334 }
2335 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336}
2337
2338static int
2339compiler_import(struct compiler *c, stmt_ty s)
2340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* The Import node stores a module name like a.b.c as a single
2342 string. This is convenient for all cases except
2343 import a.b.c as d
2344 where we need to parse that string to extract the individual
2345 module names.
2346 XXX Perhaps change the representation to make this case simpler?
2347 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002348 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 for (i = 0; i < n; i++) {
2351 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2352 int r;
2353 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 level = PyLong_FromLong(0);
2356 if (level == NULL)
2357 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 ADDOP_O(c, LOAD_CONST, level, consts);
2360 Py_DECREF(level);
2361 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2362 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 if (alias->asname) {
2365 r = compiler_import_as(c, alias->name, alias->asname);
2366 if (!r)
2367 return r;
2368 }
2369 else {
2370 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 Py_ssize_t dot = PyUnicode_FindChar(
2372 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002373 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002374 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002375 if (tmp == NULL)
2376 return 0;
2377 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 Py_DECREF(tmp);
2381 }
2382 if (!r)
2383 return r;
2384 }
2385 }
2386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387}
2388
2389static int
2390compiler_from_import(struct compiler *c, stmt_ty s)
2391{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002392 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 PyObject *names = PyTuple_New(n);
2395 PyObject *level;
2396 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 if (!empty_string) {
2399 empty_string = PyUnicode_FromString("");
2400 if (!empty_string)
2401 return 0;
2402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 if (!names)
2405 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 level = PyLong_FromLong(s->v.ImportFrom.level);
2408 if (!level) {
2409 Py_DECREF(names);
2410 return 0;
2411 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 /* build up the names */
2414 for (i = 0; i < n; i++) {
2415 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2416 Py_INCREF(alias->name);
2417 PyTuple_SET_ITEM(names, i, alias->name);
2418 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2421 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2422 Py_DECREF(level);
2423 Py_DECREF(names);
2424 return compiler_error(c, "from __future__ imports must occur "
2425 "at the beginning of the file");
2426 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 ADDOP_O(c, LOAD_CONST, level, consts);
2429 Py_DECREF(level);
2430 ADDOP_O(c, LOAD_CONST, names, consts);
2431 Py_DECREF(names);
2432 if (s->v.ImportFrom.module) {
2433 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2434 }
2435 else {
2436 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2437 }
2438 for (i = 0; i < n; i++) {
2439 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2440 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 assert(n == 1);
2444 ADDOP(c, IMPORT_STAR);
2445 return 1;
2446 }
2447
2448 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2449 store_name = alias->name;
2450 if (alias->asname)
2451 store_name = alias->asname;
2452
2453 if (!compiler_nameop(c, store_name, Store)) {
2454 Py_DECREF(names);
2455 return 0;
2456 }
2457 }
2458 /* remove imported module */
2459 ADDOP(c, POP_TOP);
2460 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461}
2462
2463static int
2464compiler_assert(struct compiler *c, stmt_ty s)
2465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 static PyObject *assertion_error = NULL;
2467 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002468 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469
Georg Brandl8334fd92010-12-04 10:26:46 +00002470 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 return 1;
2472 if (assertion_error == NULL) {
2473 assertion_error = PyUnicode_InternFromString("AssertionError");
2474 if (assertion_error == NULL)
2475 return 0;
2476 }
2477 if (s->v.Assert.test->kind == Tuple_kind &&
2478 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002479 msg = PyUnicode_FromString("assertion is always true, "
2480 "perhaps remove parentheses?");
2481 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002483 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2484 c->c_filename, c->u->u_lineno,
2485 NULL, NULL) == -1) {
2486 Py_DECREF(msg);
2487 return 0;
2488 }
2489 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 }
2491 VISIT(c, expr, s->v.Assert.test);
2492 end = compiler_new_block(c);
2493 if (end == NULL)
2494 return 0;
2495 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2496 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2497 if (s->v.Assert.msg) {
2498 VISIT(c, expr, s->v.Assert.msg);
2499 ADDOP_I(c, CALL_FUNCTION, 1);
2500 }
2501 ADDOP_I(c, RAISE_VARARGS, 1);
2502 compiler_use_next_block(c, end);
2503 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504}
2505
2506static int
2507compiler_visit_stmt(struct compiler *c, stmt_ty s)
2508{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002509 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 /* Always assign a lineno to the next instruction for a stmt. */
2512 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002513 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 switch (s->kind) {
2517 case FunctionDef_kind:
2518 return compiler_function(c, s);
2519 case ClassDef_kind:
2520 return compiler_class(c, s);
2521 case Return_kind:
2522 if (c->u->u_ste->ste_type != FunctionBlock)
2523 return compiler_error(c, "'return' outside function");
2524 if (s->v.Return.value) {
2525 VISIT(c, expr, s->v.Return.value);
2526 }
2527 else
2528 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2529 ADDOP(c, RETURN_VALUE);
2530 break;
2531 case Delete_kind:
2532 VISIT_SEQ(c, expr, s->v.Delete.targets)
2533 break;
2534 case Assign_kind:
2535 n = asdl_seq_LEN(s->v.Assign.targets);
2536 VISIT(c, expr, s->v.Assign.value);
2537 for (i = 0; i < n; i++) {
2538 if (i < n - 1)
2539 ADDOP(c, DUP_TOP);
2540 VISIT(c, expr,
2541 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2542 }
2543 break;
2544 case AugAssign_kind:
2545 return compiler_augassign(c, s);
2546 case For_kind:
2547 return compiler_for(c, s);
2548 case While_kind:
2549 return compiler_while(c, s);
2550 case If_kind:
2551 return compiler_if(c, s);
2552 case Raise_kind:
2553 n = 0;
2554 if (s->v.Raise.exc) {
2555 VISIT(c, expr, s->v.Raise.exc);
2556 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002557 if (s->v.Raise.cause) {
2558 VISIT(c, expr, s->v.Raise.cause);
2559 n++;
2560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002562 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002564 case Try_kind:
2565 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 case Assert_kind:
2567 return compiler_assert(c, s);
2568 case Import_kind:
2569 return compiler_import(c, s);
2570 case ImportFrom_kind:
2571 return compiler_from_import(c, s);
2572 case Global_kind:
2573 case Nonlocal_kind:
2574 break;
2575 case Expr_kind:
2576 if (c->c_interactive && c->c_nestlevel <= 1) {
2577 VISIT(c, expr, s->v.Expr.value);
2578 ADDOP(c, PRINT_EXPR);
2579 }
2580 else if (s->v.Expr.value->kind != Str_kind &&
2581 s->v.Expr.value->kind != Num_kind) {
2582 VISIT(c, expr, s->v.Expr.value);
2583 ADDOP(c, POP_TOP);
2584 }
2585 break;
2586 case Pass_kind:
2587 break;
2588 case Break_kind:
2589 if (!compiler_in_loop(c))
2590 return compiler_error(c, "'break' outside loop");
2591 ADDOP(c, BREAK_LOOP);
2592 break;
2593 case Continue_kind:
2594 return compiler_continue(c);
2595 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002596 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 }
2598 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599}
2600
2601static int
2602unaryop(unaryop_ty op)
2603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 switch (op) {
2605 case Invert:
2606 return UNARY_INVERT;
2607 case Not:
2608 return UNARY_NOT;
2609 case UAdd:
2610 return UNARY_POSITIVE;
2611 case USub:
2612 return UNARY_NEGATIVE;
2613 default:
2614 PyErr_Format(PyExc_SystemError,
2615 "unary op %d should not be possible", op);
2616 return 0;
2617 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618}
2619
2620static int
2621binop(struct compiler *c, operator_ty op)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 switch (op) {
2624 case Add:
2625 return BINARY_ADD;
2626 case Sub:
2627 return BINARY_SUBTRACT;
2628 case Mult:
2629 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002630 case MatMult:
2631 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 case Div:
2633 return BINARY_TRUE_DIVIDE;
2634 case Mod:
2635 return BINARY_MODULO;
2636 case Pow:
2637 return BINARY_POWER;
2638 case LShift:
2639 return BINARY_LSHIFT;
2640 case RShift:
2641 return BINARY_RSHIFT;
2642 case BitOr:
2643 return BINARY_OR;
2644 case BitXor:
2645 return BINARY_XOR;
2646 case BitAnd:
2647 return BINARY_AND;
2648 case FloorDiv:
2649 return BINARY_FLOOR_DIVIDE;
2650 default:
2651 PyErr_Format(PyExc_SystemError,
2652 "binary op %d should not be possible", op);
2653 return 0;
2654 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655}
2656
2657static int
2658cmpop(cmpop_ty op)
2659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 switch (op) {
2661 case Eq:
2662 return PyCmp_EQ;
2663 case NotEq:
2664 return PyCmp_NE;
2665 case Lt:
2666 return PyCmp_LT;
2667 case LtE:
2668 return PyCmp_LE;
2669 case Gt:
2670 return PyCmp_GT;
2671 case GtE:
2672 return PyCmp_GE;
2673 case Is:
2674 return PyCmp_IS;
2675 case IsNot:
2676 return PyCmp_IS_NOT;
2677 case In:
2678 return PyCmp_IN;
2679 case NotIn:
2680 return PyCmp_NOT_IN;
2681 default:
2682 return PyCmp_BAD;
2683 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684}
2685
2686static int
2687inplace_binop(struct compiler *c, operator_ty op)
2688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 switch (op) {
2690 case Add:
2691 return INPLACE_ADD;
2692 case Sub:
2693 return INPLACE_SUBTRACT;
2694 case Mult:
2695 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002696 case MatMult:
2697 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 case Div:
2699 return INPLACE_TRUE_DIVIDE;
2700 case Mod:
2701 return INPLACE_MODULO;
2702 case Pow:
2703 return INPLACE_POWER;
2704 case LShift:
2705 return INPLACE_LSHIFT;
2706 case RShift:
2707 return INPLACE_RSHIFT;
2708 case BitOr:
2709 return INPLACE_OR;
2710 case BitXor:
2711 return INPLACE_XOR;
2712 case BitAnd:
2713 return INPLACE_AND;
2714 case FloorDiv:
2715 return INPLACE_FLOOR_DIVIDE;
2716 default:
2717 PyErr_Format(PyExc_SystemError,
2718 "inplace binary op %d should not be possible", op);
2719 return 0;
2720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721}
2722
2723static int
2724compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2725{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002726 int op, scope;
2727 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 PyObject *dict = c->u->u_names;
2731 PyObject *mangled;
2732 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 mangled = _Py_Mangle(c->u->u_private, name);
2735 if (!mangled)
2736 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002737
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002738 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2739 PyUnicode_CompareWithASCIIString(name, "True") &&
2740 PyUnicode_CompareWithASCIIString(name, "False"));
2741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 op = 0;
2743 optype = OP_NAME;
2744 scope = PyST_GetScope(c->u->u_ste, mangled);
2745 switch (scope) {
2746 case FREE:
2747 dict = c->u->u_freevars;
2748 optype = OP_DEREF;
2749 break;
2750 case CELL:
2751 dict = c->u->u_cellvars;
2752 optype = OP_DEREF;
2753 break;
2754 case LOCAL:
2755 if (c->u->u_ste->ste_type == FunctionBlock)
2756 optype = OP_FAST;
2757 break;
2758 case GLOBAL_IMPLICIT:
2759 if (c->u->u_ste->ste_type == FunctionBlock &&
2760 !c->u->u_ste->ste_unoptimized)
2761 optype = OP_GLOBAL;
2762 break;
2763 case GLOBAL_EXPLICIT:
2764 optype = OP_GLOBAL;
2765 break;
2766 default:
2767 /* scope can be 0 */
2768 break;
2769 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 switch (optype) {
2775 case OP_DEREF:
2776 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002777 case Load:
2778 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2779 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 case Store: op = STORE_DEREF; break;
2781 case AugLoad:
2782 case AugStore:
2783 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002784 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 case Param:
2786 default:
2787 PyErr_SetString(PyExc_SystemError,
2788 "param invalid for deref variable");
2789 return 0;
2790 }
2791 break;
2792 case OP_FAST:
2793 switch (ctx) {
2794 case Load: op = LOAD_FAST; break;
2795 case Store: op = STORE_FAST; break;
2796 case Del: op = DELETE_FAST; break;
2797 case AugLoad:
2798 case AugStore:
2799 break;
2800 case Param:
2801 default:
2802 PyErr_SetString(PyExc_SystemError,
2803 "param invalid for local variable");
2804 return 0;
2805 }
2806 ADDOP_O(c, op, mangled, varnames);
2807 Py_DECREF(mangled);
2808 return 1;
2809 case OP_GLOBAL:
2810 switch (ctx) {
2811 case Load: op = LOAD_GLOBAL; break;
2812 case Store: op = STORE_GLOBAL; break;
2813 case Del: op = DELETE_GLOBAL; break;
2814 case AugLoad:
2815 case AugStore:
2816 break;
2817 case Param:
2818 default:
2819 PyErr_SetString(PyExc_SystemError,
2820 "param invalid for global variable");
2821 return 0;
2822 }
2823 break;
2824 case OP_NAME:
2825 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002826 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 case Store: op = STORE_NAME; break;
2828 case Del: op = DELETE_NAME; break;
2829 case AugLoad:
2830 case AugStore:
2831 break;
2832 case Param:
2833 default:
2834 PyErr_SetString(PyExc_SystemError,
2835 "param invalid for name variable");
2836 return 0;
2837 }
2838 break;
2839 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 assert(op);
2842 arg = compiler_add_o(c, dict, mangled);
2843 Py_DECREF(mangled);
2844 if (arg < 0)
2845 return 0;
2846 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847}
2848
2849static int
2850compiler_boolop(struct compiler *c, expr_ty e)
2851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002853 int jumpi;
2854 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 assert(e->kind == BoolOp_kind);
2858 if (e->v.BoolOp.op == And)
2859 jumpi = JUMP_IF_FALSE_OR_POP;
2860 else
2861 jumpi = JUMP_IF_TRUE_OR_POP;
2862 end = compiler_new_block(c);
2863 if (end == NULL)
2864 return 0;
2865 s = e->v.BoolOp.values;
2866 n = asdl_seq_LEN(s) - 1;
2867 assert(n >= 0);
2868 for (i = 0; i < n; ++i) {
2869 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2870 ADDOP_JABS(c, jumpi, end);
2871 }
2872 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2873 compiler_use_next_block(c, end);
2874 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875}
2876
2877static int
2878compiler_list(struct compiler *c, expr_ty e)
2879{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002880 Py_ssize_t n = asdl_seq_LEN(e->v.List.elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 if (e->v.List.ctx == Store) {
2882 int i, seen_star = 0;
2883 for (i = 0; i < n; i++) {
2884 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2885 if (elt->kind == Starred_kind && !seen_star) {
2886 if ((i >= (1 << 8)) ||
2887 (n-i-1 >= (INT_MAX >> 8)))
2888 return compiler_error(c,
2889 "too many expressions in "
2890 "star-unpacking assignment");
2891 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2892 seen_star = 1;
2893 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2894 } else if (elt->kind == Starred_kind) {
2895 return compiler_error(c,
2896 "two starred expressions in assignment");
2897 }
2898 }
2899 if (!seen_star) {
2900 ADDOP_I(c, UNPACK_SEQUENCE, n);
2901 }
2902 }
2903 VISIT_SEQ(c, expr, e->v.List.elts);
2904 if (e->v.List.ctx == Load) {
2905 ADDOP_I(c, BUILD_LIST, n);
2906 }
2907 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908}
2909
2910static int
2911compiler_tuple(struct compiler *c, expr_ty e)
2912{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002913 Py_ssize_t n = asdl_seq_LEN(e->v.Tuple.elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 if (e->v.Tuple.ctx == Store) {
2915 int i, seen_star = 0;
2916 for (i = 0; i < n; i++) {
2917 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2918 if (elt->kind == Starred_kind && !seen_star) {
2919 if ((i >= (1 << 8)) ||
2920 (n-i-1 >= (INT_MAX >> 8)))
2921 return compiler_error(c,
2922 "too many expressions in "
2923 "star-unpacking assignment");
2924 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2925 seen_star = 1;
2926 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2927 } else if (elt->kind == Starred_kind) {
2928 return compiler_error(c,
2929 "two starred expressions in assignment");
2930 }
2931 }
2932 if (!seen_star) {
2933 ADDOP_I(c, UNPACK_SEQUENCE, n);
2934 }
2935 }
2936 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2937 if (e->v.Tuple.ctx == Load) {
2938 ADDOP_I(c, BUILD_TUPLE, n);
2939 }
2940 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941}
2942
2943static int
2944compiler_compare(struct compiler *c, expr_ty e)
2945{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002946 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2950 VISIT(c, expr, e->v.Compare.left);
2951 n = asdl_seq_LEN(e->v.Compare.ops);
2952 assert(n > 0);
2953 if (n > 1) {
2954 cleanup = compiler_new_block(c);
2955 if (cleanup == NULL)
2956 return 0;
2957 VISIT(c, expr,
2958 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2959 }
2960 for (i = 1; i < n; i++) {
2961 ADDOP(c, DUP_TOP);
2962 ADDOP(c, ROT_THREE);
2963 ADDOP_I(c, COMPARE_OP,
2964 cmpop((cmpop_ty)(asdl_seq_GET(
2965 e->v.Compare.ops, i - 1))));
2966 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2967 NEXT_BLOCK(c);
2968 if (i < (n - 1))
2969 VISIT(c, expr,
2970 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2971 }
2972 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2973 ADDOP_I(c, COMPARE_OP,
2974 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2975 if (n > 1) {
2976 basicblock *end = compiler_new_block(c);
2977 if (end == NULL)
2978 return 0;
2979 ADDOP_JREL(c, JUMP_FORWARD, end);
2980 compiler_use_next_block(c, cleanup);
2981 ADDOP(c, ROT_TWO);
2982 ADDOP(c, POP_TOP);
2983 compiler_use_next_block(c, end);
2984 }
2985 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986}
2987
2988static int
2989compiler_call(struct compiler *c, expr_ty e)
2990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 VISIT(c, expr, e->v.Call.func);
2992 return compiler_call_helper(c, 0,
2993 e->v.Call.args,
2994 e->v.Call.keywords,
2995 e->v.Call.starargs,
2996 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002997}
2998
2999/* shared code between compiler_call and compiler_class */
3000static int
3001compiler_call_helper(struct compiler *c,
Victor Stinnerad9a0662013-11-19 22:23:20 +01003002 Py_ssize_t n, /* Args already pushed */
3003 asdl_seq *args,
3004 asdl_seq *keywords,
3005 expr_ty starargs,
3006 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 n += asdl_seq_LEN(args);
3011 VISIT_SEQ(c, expr, args);
3012 if (keywords) {
3013 VISIT_SEQ(c, keyword, keywords);
3014 n |= asdl_seq_LEN(keywords) << 8;
3015 }
3016 if (starargs) {
3017 VISIT(c, expr, starargs);
3018 code |= 1;
3019 }
3020 if (kwargs) {
3021 VISIT(c, expr, kwargs);
3022 code |= 2;
3023 }
3024 switch (code) {
3025 case 0:
3026 ADDOP_I(c, CALL_FUNCTION, n);
3027 break;
3028 case 1:
3029 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3030 break;
3031 case 2:
3032 ADDOP_I(c, CALL_FUNCTION_KW, n);
3033 break;
3034 case 3:
3035 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3036 break;
3037 }
3038 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039}
3040
Nick Coghlan650f0d02007-04-15 12:05:43 +00003041
3042/* List and set comprehensions and generator expressions work by creating a
3043 nested function to perform the actual iteration. This means that the
3044 iteration variables don't leak into the current scope.
3045 The defined function is called immediately following its definition, with the
3046 result of that call being the result of the expression.
3047 The LC/SC version returns the populated container, while the GE version is
3048 flagged in symtable.c as a generator, so it returns the generator object
3049 when the function is called.
3050 This code *knows* that the loop cannot contain break, continue, or return,
3051 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3052
3053 Possible cleanups:
3054 - iterate over the generator sequence instead of using recursion
3055*/
3056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058compiler_comprehension_generator(struct compiler *c,
3059 asdl_seq *generators, int gen_index,
3060 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 /* generate code for the iterator, then each of the ifs,
3063 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 comprehension_ty gen;
3066 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003067 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 start = compiler_new_block(c);
3070 skip = compiler_new_block(c);
3071 if_cleanup = compiler_new_block(c);
3072 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3075 anchor == NULL)
3076 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 if (gen_index == 0) {
3081 /* Receive outermost iter as an implicit argument */
3082 c->u->u_argcount = 1;
3083 ADDOP_I(c, LOAD_FAST, 0);
3084 }
3085 else {
3086 /* Sub-iter - calculate on the fly */
3087 VISIT(c, expr, gen->iter);
3088 ADDOP(c, GET_ITER);
3089 }
3090 compiler_use_next_block(c, start);
3091 ADDOP_JREL(c, FOR_ITER, anchor);
3092 NEXT_BLOCK(c);
3093 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 /* XXX this needs to be cleaned up...a lot! */
3096 n = asdl_seq_LEN(gen->ifs);
3097 for (i = 0; i < n; i++) {
3098 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3099 VISIT(c, expr, e);
3100 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3101 NEXT_BLOCK(c);
3102 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 if (++gen_index < asdl_seq_LEN(generators))
3105 if (!compiler_comprehension_generator(c,
3106 generators, gen_index,
3107 elt, val, type))
3108 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 /* only append after the last for generator */
3111 if (gen_index >= asdl_seq_LEN(generators)) {
3112 /* comprehension specific code */
3113 switch (type) {
3114 case COMP_GENEXP:
3115 VISIT(c, expr, elt);
3116 ADDOP(c, YIELD_VALUE);
3117 ADDOP(c, POP_TOP);
3118 break;
3119 case COMP_LISTCOMP:
3120 VISIT(c, expr, elt);
3121 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3122 break;
3123 case COMP_SETCOMP:
3124 VISIT(c, expr, elt);
3125 ADDOP_I(c, SET_ADD, gen_index + 1);
3126 break;
3127 case COMP_DICTCOMP:
3128 /* With 'd[k] = v', v is evaluated before k, so we do
3129 the same. */
3130 VISIT(c, expr, val);
3131 VISIT(c, expr, elt);
3132 ADDOP_I(c, MAP_ADD, gen_index + 1);
3133 break;
3134 default:
3135 return 0;
3136 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 compiler_use_next_block(c, skip);
3139 }
3140 compiler_use_next_block(c, if_cleanup);
3141 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3142 compiler_use_next_block(c, anchor);
3143
3144 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145}
3146
3147static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003148compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 PyCodeObject *co = NULL;
3152 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003153 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 outermost_iter = ((comprehension_ty)
3156 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003157
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003158 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3159 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 if (type != COMP_GENEXP) {
3163 int op;
3164 switch (type) {
3165 case COMP_LISTCOMP:
3166 op = BUILD_LIST;
3167 break;
3168 case COMP_SETCOMP:
3169 op = BUILD_SET;
3170 break;
3171 case COMP_DICTCOMP:
3172 op = BUILD_MAP;
3173 break;
3174 default:
3175 PyErr_Format(PyExc_SystemError,
3176 "unknown comprehension type %d", type);
3177 goto error_in_scope;
3178 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 ADDOP_I(c, op, 0);
3181 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 if (!compiler_comprehension_generator(c, generators, 0, elt,
3184 val, type))
3185 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 if (type != COMP_GENEXP) {
3188 ADDOP(c, RETURN_VALUE);
3189 }
3190
3191 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003192 qualname = c->u->u_qualname;
3193 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003195 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 goto error;
3197
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003198 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003200 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 Py_DECREF(co);
3202
3203 VISIT(c, expr, outermost_iter);
3204 ADDOP(c, GET_ITER);
3205 ADDOP_I(c, CALL_FUNCTION, 1);
3206 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003207error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003209error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003210 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 Py_XDECREF(co);
3212 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003213}
3214
3215static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216compiler_genexp(struct compiler *c, expr_ty e)
3217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 static identifier name;
3219 if (!name) {
3220 name = PyUnicode_FromString("<genexpr>");
3221 if (!name)
3222 return 0;
3223 }
3224 assert(e->kind == GeneratorExp_kind);
3225 return compiler_comprehension(c, e, COMP_GENEXP, name,
3226 e->v.GeneratorExp.generators,
3227 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228}
3229
3230static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003231compiler_listcomp(struct compiler *c, expr_ty e)
3232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 static identifier name;
3234 if (!name) {
3235 name = PyUnicode_FromString("<listcomp>");
3236 if (!name)
3237 return 0;
3238 }
3239 assert(e->kind == ListComp_kind);
3240 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3241 e->v.ListComp.generators,
3242 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003243}
3244
3245static int
3246compiler_setcomp(struct compiler *c, expr_ty e)
3247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 static identifier name;
3249 if (!name) {
3250 name = PyUnicode_FromString("<setcomp>");
3251 if (!name)
3252 return 0;
3253 }
3254 assert(e->kind == SetComp_kind);
3255 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3256 e->v.SetComp.generators,
3257 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003258}
3259
3260
3261static int
3262compiler_dictcomp(struct compiler *c, expr_ty e)
3263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 static identifier name;
3265 if (!name) {
3266 name = PyUnicode_FromString("<dictcomp>");
3267 if (!name)
3268 return 0;
3269 }
3270 assert(e->kind == DictComp_kind);
3271 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3272 e->v.DictComp.generators,
3273 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003274}
3275
3276
3277static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278compiler_visit_keyword(struct compiler *c, keyword_ty k)
3279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3281 VISIT(c, expr, k->value);
3282 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283}
3284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286 whether they are true or false.
3287
3288 Return values: 1 for true, 0 for false, -1 for non-constant.
3289 */
3290
3291static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003292expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 char *id;
3295 switch (e->kind) {
3296 case Ellipsis_kind:
3297 return 1;
3298 case Num_kind:
3299 return PyObject_IsTrue(e->v.Num.n);
3300 case Str_kind:
3301 return PyObject_IsTrue(e->v.Str.s);
3302 case Name_kind:
3303 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003304 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003305 if (id && strcmp(id, "__debug__") == 0)
3306 return !c->c_optimize;
3307 return -1;
3308 case NameConstant_kind: {
3309 PyObject *o = e->v.NameConstant.value;
3310 if (o == Py_None)
3311 return 0;
3312 else if (o == Py_True)
3313 return 1;
3314 else if (o == Py_False)
3315 return 0;
3316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 default:
3318 return -1;
3319 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003320}
3321
Guido van Rossumc2e20742006-02-27 22:32:47 +00003322/*
3323 Implements the with statement from PEP 343.
3324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003326
3327 with EXPR as VAR:
3328 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329
Guido van Rossumc2e20742006-02-27 22:32:47 +00003330 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331
Thomas Wouters477c8d52006-05-27 19:21:47 +00003332 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003333 exit = context.__exit__ # not calling it
3334 value = context.__enter__()
3335 try:
3336 VAR = value # if VAR present in the syntax
3337 BLOCK
3338 finally:
3339 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003341 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003343 exit(*exc)
3344 */
3345static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003346compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003347{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003348 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003349 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003350
3351 assert(s->kind == With_kind);
3352
Guido van Rossumc2e20742006-02-27 22:32:47 +00003353 block = compiler_new_block(c);
3354 finally = compiler_new_block(c);
3355 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003356 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003357
Thomas Wouters477c8d52006-05-27 19:21:47 +00003358 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003359 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003360 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003361
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003362 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003363 compiler_use_next_block(c, block);
3364 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003365 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003366 }
3367
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003368 if (item->optional_vars) {
3369 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003370 }
3371 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003373 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003374 }
3375
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003376 pos++;
3377 if (pos == asdl_seq_LEN(s->v.With.items))
3378 /* BLOCK code */
3379 VISIT_SEQ(c, stmt, s->v.With.body)
3380 else if (!compiler_with(c, s, pos))
3381 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003382
3383 /* End of try block; start the finally block */
3384 ADDOP(c, POP_BLOCK);
3385 compiler_pop_fblock(c, FINALLY_TRY, block);
3386
3387 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3388 compiler_use_next_block(c, finally);
3389 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003390 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003391
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003392 /* Finally block starts; context.__exit__ is on the stack under
3393 the exception or return information. Just issue our magic
3394 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003395 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003396
3397 /* Finally block ends. */
3398 ADDOP(c, END_FINALLY);
3399 compiler_pop_fblock(c, FINALLY_END, finally);
3400 return 1;
3401}
3402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403static int
3404compiler_visit_expr(struct compiler *c, expr_ty e)
3405{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003406 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 /* If expr e has a different line number than the last expr/stmt,
3409 set a new line number for the next instruction.
3410 */
3411 if (e->lineno > c->u->u_lineno) {
3412 c->u->u_lineno = e->lineno;
3413 c->u->u_lineno_set = 0;
3414 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003415 /* Updating the column offset is always harmless. */
3416 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 switch (e->kind) {
3418 case BoolOp_kind:
3419 return compiler_boolop(c, e);
3420 case BinOp_kind:
3421 VISIT(c, expr, e->v.BinOp.left);
3422 VISIT(c, expr, e->v.BinOp.right);
3423 ADDOP(c, binop(c, e->v.BinOp.op));
3424 break;
3425 case UnaryOp_kind:
3426 VISIT(c, expr, e->v.UnaryOp.operand);
3427 ADDOP(c, unaryop(e->v.UnaryOp.op));
3428 break;
3429 case Lambda_kind:
3430 return compiler_lambda(c, e);
3431 case IfExp_kind:
3432 return compiler_ifexp(c, e);
3433 case Dict_kind:
3434 n = asdl_seq_LEN(e->v.Dict.values);
Victor Stinnerad9a0662013-11-19 22:23:20 +01003435 /* BUILD_MAP parameter is only used to preallocate the dictionary,
3436 it doesn't need to be exact */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3438 for (i = 0; i < n; i++) {
3439 VISIT(c, expr,
3440 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3441 VISIT(c, expr,
3442 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3443 ADDOP(c, STORE_MAP);
3444 }
3445 break;
3446 case Set_kind:
3447 n = asdl_seq_LEN(e->v.Set.elts);
3448 VISIT_SEQ(c, expr, e->v.Set.elts);
3449 ADDOP_I(c, BUILD_SET, n);
3450 break;
3451 case GeneratorExp_kind:
3452 return compiler_genexp(c, e);
3453 case ListComp_kind:
3454 return compiler_listcomp(c, e);
3455 case SetComp_kind:
3456 return compiler_setcomp(c, e);
3457 case DictComp_kind:
3458 return compiler_dictcomp(c, e);
3459 case Yield_kind:
3460 if (c->u->u_ste->ste_type != FunctionBlock)
3461 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003462 if (e->v.Yield.value) {
3463 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 }
3465 else {
3466 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3467 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003468 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003470 case YieldFrom_kind:
3471 if (c->u->u_ste->ste_type != FunctionBlock)
3472 return compiler_error(c, "'yield' outside function");
3473 VISIT(c, expr, e->v.YieldFrom.value);
3474 ADDOP(c, GET_ITER);
3475 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3476 ADDOP(c, YIELD_FROM);
3477 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 case Compare_kind:
3479 return compiler_compare(c, e);
3480 case Call_kind:
3481 return compiler_call(c, e);
3482 case Num_kind:
3483 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3484 break;
3485 case Str_kind:
3486 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3487 break;
3488 case Bytes_kind:
3489 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3490 break;
3491 case Ellipsis_kind:
3492 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3493 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003494 case NameConstant_kind:
3495 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3496 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 /* The following exprs can be assignment targets. */
3498 case Attribute_kind:
3499 if (e->v.Attribute.ctx != AugStore)
3500 VISIT(c, expr, e->v.Attribute.value);
3501 switch (e->v.Attribute.ctx) {
3502 case AugLoad:
3503 ADDOP(c, DUP_TOP);
3504 /* Fall through to load */
3505 case Load:
3506 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3507 break;
3508 case AugStore:
3509 ADDOP(c, ROT_TWO);
3510 /* Fall through to save */
3511 case Store:
3512 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3513 break;
3514 case Del:
3515 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3516 break;
3517 case Param:
3518 default:
3519 PyErr_SetString(PyExc_SystemError,
3520 "param invalid in attribute expression");
3521 return 0;
3522 }
3523 break;
3524 case Subscript_kind:
3525 switch (e->v.Subscript.ctx) {
3526 case AugLoad:
3527 VISIT(c, expr, e->v.Subscript.value);
3528 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3529 break;
3530 case Load:
3531 VISIT(c, expr, e->v.Subscript.value);
3532 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3533 break;
3534 case AugStore:
3535 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3536 break;
3537 case Store:
3538 VISIT(c, expr, e->v.Subscript.value);
3539 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3540 break;
3541 case Del:
3542 VISIT(c, expr, e->v.Subscript.value);
3543 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3544 break;
3545 case Param:
3546 default:
3547 PyErr_SetString(PyExc_SystemError,
3548 "param invalid in subscript expression");
3549 return 0;
3550 }
3551 break;
3552 case Starred_kind:
3553 switch (e->v.Starred.ctx) {
3554 case Store:
3555 /* In all legitimate cases, the Starred node was already replaced
3556 * by compiler_list/compiler_tuple. XXX: is that okay? */
3557 return compiler_error(c,
3558 "starred assignment target must be in a list or tuple");
3559 default:
3560 return compiler_error(c,
3561 "can use starred expression only as assignment target");
3562 }
3563 break;
3564 case Name_kind:
3565 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3566 /* child nodes of List and Tuple will have expr_context set */
3567 case List_kind:
3568 return compiler_list(c, e);
3569 case Tuple_kind:
3570 return compiler_tuple(c, e);
3571 }
3572 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573}
3574
3575static int
3576compiler_augassign(struct compiler *c, stmt_ty s)
3577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 expr_ty e = s->v.AugAssign.target;
3579 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 switch (e->kind) {
3584 case Attribute_kind:
3585 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3586 AugLoad, e->lineno, e->col_offset, c->c_arena);
3587 if (auge == NULL)
3588 return 0;
3589 VISIT(c, expr, auge);
3590 VISIT(c, expr, s->v.AugAssign.value);
3591 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3592 auge->v.Attribute.ctx = AugStore;
3593 VISIT(c, expr, auge);
3594 break;
3595 case Subscript_kind:
3596 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3597 AugLoad, e->lineno, e->col_offset, c->c_arena);
3598 if (auge == NULL)
3599 return 0;
3600 VISIT(c, expr, auge);
3601 VISIT(c, expr, s->v.AugAssign.value);
3602 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3603 auge->v.Subscript.ctx = AugStore;
3604 VISIT(c, expr, auge);
3605 break;
3606 case Name_kind:
3607 if (!compiler_nameop(c, e->v.Name.id, Load))
3608 return 0;
3609 VISIT(c, expr, s->v.AugAssign.value);
3610 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3611 return compiler_nameop(c, e->v.Name.id, Store);
3612 default:
3613 PyErr_Format(PyExc_SystemError,
3614 "invalid node type (%d) for augmented assignment",
3615 e->kind);
3616 return 0;
3617 }
3618 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619}
3620
3621static int
3622compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 struct fblockinfo *f;
3625 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3626 PyErr_SetString(PyExc_SystemError,
3627 "too many statically nested blocks");
3628 return 0;
3629 }
3630 f = &c->u->u_fblock[c->u->u_nfblocks++];
3631 f->fb_type = t;
3632 f->fb_block = b;
3633 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634}
3635
3636static void
3637compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 struct compiler_unit *u = c->u;
3640 assert(u->u_nfblocks > 0);
3641 u->u_nfblocks--;
3642 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3643 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644}
3645
Thomas Wouters89f507f2006-12-13 04:49:30 +00003646static int
3647compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 int i;
3649 struct compiler_unit *u = c->u;
3650 for (i = 0; i < u->u_nfblocks; ++i) {
3651 if (u->u_fblock[i].fb_type == LOOP)
3652 return 1;
3653 }
3654 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003655}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656/* Raises a SyntaxError and returns 0.
3657 If something goes wrong, a different exception may be raised.
3658*/
3659
3660static int
3661compiler_error(struct compiler *c, const char *errstr)
3662{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003663 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003665
Victor Stinner14e461d2013-08-26 22:28:21 +02003666 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 if (!loc) {
3668 Py_INCREF(Py_None);
3669 loc = Py_None;
3670 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003671 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003672 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 if (!u)
3674 goto exit;
3675 v = Py_BuildValue("(zO)", errstr, u);
3676 if (!v)
3677 goto exit;
3678 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 Py_DECREF(loc);
3681 Py_XDECREF(u);
3682 Py_XDECREF(v);
3683 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684}
3685
3686static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687compiler_handle_subscr(struct compiler *c, const char *kind,
3688 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 /* XXX this code is duplicated */
3693 switch (ctx) {
3694 case AugLoad: /* fall through to Load */
3695 case Load: op = BINARY_SUBSCR; break;
3696 case AugStore:/* fall through to Store */
3697 case Store: op = STORE_SUBSCR; break;
3698 case Del: op = DELETE_SUBSCR; break;
3699 case Param:
3700 PyErr_Format(PyExc_SystemError,
3701 "invalid %s kind %d in subscript\n",
3702 kind, ctx);
3703 return 0;
3704 }
3705 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003706 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 }
3708 else if (ctx == AugStore) {
3709 ADDOP(c, ROT_THREE);
3710 }
3711 ADDOP(c, op);
3712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713}
3714
3715static int
3716compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 int n = 2;
3719 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 /* only handles the cases where BUILD_SLICE is emitted */
3722 if (s->v.Slice.lower) {
3723 VISIT(c, expr, s->v.Slice.lower);
3724 }
3725 else {
3726 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 if (s->v.Slice.upper) {
3730 VISIT(c, expr, s->v.Slice.upper);
3731 }
3732 else {
3733 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3734 }
3735
3736 if (s->v.Slice.step) {
3737 n++;
3738 VISIT(c, expr, s->v.Slice.step);
3739 }
3740 ADDOP_I(c, BUILD_SLICE, n);
3741 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742}
3743
3744static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3746 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 switch (s->kind) {
3749 case Slice_kind:
3750 return compiler_slice(c, s, ctx);
3751 case Index_kind:
3752 VISIT(c, expr, s->v.Index.value);
3753 break;
3754 case ExtSlice_kind:
3755 default:
3756 PyErr_SetString(PyExc_SystemError,
3757 "extended slice invalid in nested slice");
3758 return 0;
3759 }
3760 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761}
3762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763static int
3764compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 char * kindname = NULL;
3767 switch (s->kind) {
3768 case Index_kind:
3769 kindname = "index";
3770 if (ctx != AugStore) {
3771 VISIT(c, expr, s->v.Index.value);
3772 }
3773 break;
3774 case Slice_kind:
3775 kindname = "slice";
3776 if (ctx != AugStore) {
3777 if (!compiler_slice(c, s, ctx))
3778 return 0;
3779 }
3780 break;
3781 case ExtSlice_kind:
3782 kindname = "extended slice";
3783 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01003784 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 for (i = 0; i < n; i++) {
3786 slice_ty sub = (slice_ty)asdl_seq_GET(
3787 s->v.ExtSlice.dims, i);
3788 if (!compiler_visit_nested_slice(c, sub, ctx))
3789 return 0;
3790 }
3791 ADDOP_I(c, BUILD_TUPLE, n);
3792 }
3793 break;
3794 default:
3795 PyErr_Format(PyExc_SystemError,
3796 "invalid subscript kind %d", s->kind);
3797 return 0;
3798 }
3799 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800}
3801
Thomas Wouters89f507f2006-12-13 04:49:30 +00003802/* End of the compiler section, beginning of the assembler section */
3803
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804/* do depth-first search of basic block graph, starting with block.
3805 post records the block indices in post-order.
3806
3807 XXX must handle implicit jumps from one block to next
3808*/
3809
Thomas Wouters89f507f2006-12-13 04:49:30 +00003810struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 PyObject *a_bytecode; /* string containing bytecode */
3812 int a_offset; /* offset into bytecode */
3813 int a_nblocks; /* number of reachable blocks */
3814 basicblock **a_postorder; /* list of blocks in dfs postorder */
3815 PyObject *a_lnotab; /* string containing lnotab */
3816 int a_lnotab_off; /* offset into lnotab */
3817 int a_lineno; /* last lineno of emitted instruction */
3818 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003819};
3820
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003821static void
3822dfs(struct compiler *c, basicblock *b, struct assembler *a)
3823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 int i;
3825 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 if (b->b_seen)
3828 return;
3829 b->b_seen = 1;
3830 if (b->b_next != NULL)
3831 dfs(c, b->b_next, a);
3832 for (i = 0; i < b->b_iused; i++) {
3833 instr = &b->b_instr[i];
3834 if (instr->i_jrel || instr->i_jabs)
3835 dfs(c, instr->i_target, a);
3836 }
3837 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838}
3839
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003840static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3842{
Larry Hastings3a907972013-11-23 14:49:22 -08003843 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 struct instr *instr;
3845 if (b->b_seen || b->b_startdepth >= depth)
3846 return maxdepth;
3847 b->b_seen = 1;
3848 b->b_startdepth = depth;
3849 for (i = 0; i < b->b_iused; i++) {
3850 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08003851 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
3852 if (effect == PY_INVALID_STACK_EFFECT) {
3853 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
3854 Py_FatalError("PyCompile_OpcodeStackEffect()");
3855 }
3856 depth += effect;
3857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 if (depth > maxdepth)
3859 maxdepth = depth;
3860 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3861 if (instr->i_jrel || instr->i_jabs) {
3862 target_depth = depth;
3863 if (instr->i_opcode == FOR_ITER) {
3864 target_depth = depth-2;
3865 } else if (instr->i_opcode == SETUP_FINALLY ||
3866 instr->i_opcode == SETUP_EXCEPT) {
3867 target_depth = depth+3;
3868 if (target_depth > maxdepth)
3869 maxdepth = target_depth;
3870 }
3871 maxdepth = stackdepth_walk(c, instr->i_target,
3872 target_depth, maxdepth);
3873 if (instr->i_opcode == JUMP_ABSOLUTE ||
3874 instr->i_opcode == JUMP_FORWARD) {
3875 goto out; /* remaining code is dead */
3876 }
3877 }
3878 }
3879 if (b->b_next)
3880 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 b->b_seen = 0;
3883 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884}
3885
3886/* Find the flow path that needs the largest stack. We assume that
3887 * cycles in the flow graph have no net effect on the stack depth.
3888 */
3889static int
3890stackdepth(struct compiler *c)
3891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 basicblock *b, *entryblock;
3893 entryblock = NULL;
3894 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3895 b->b_seen = 0;
3896 b->b_startdepth = INT_MIN;
3897 entryblock = b;
3898 }
3899 if (!entryblock)
3900 return 0;
3901 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902}
3903
3904static int
3905assemble_init(struct assembler *a, int nblocks, int firstlineno)
3906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 memset(a, 0, sizeof(struct assembler));
3908 a->a_lineno = firstlineno;
3909 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3910 if (!a->a_bytecode)
3911 return 0;
3912 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3913 if (!a->a_lnotab)
3914 return 0;
Christian Heimes724b8282013-12-04 08:42:46 +01003915 if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003916 PyErr_NoMemory();
3917 return 0;
3918 }
3919 a->a_postorder = (basicblock **)PyObject_Malloc(
3920 sizeof(basicblock *) * nblocks);
3921 if (!a->a_postorder) {
3922 PyErr_NoMemory();
3923 return 0;
3924 }
3925 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003926}
3927
3928static void
3929assemble_free(struct assembler *a)
3930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 Py_XDECREF(a->a_bytecode);
3932 Py_XDECREF(a->a_lnotab);
3933 if (a->a_postorder)
3934 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935}
3936
3937/* Return the size of a basic block in bytes. */
3938
3939static int
3940instrsize(struct instr *instr)
3941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 if (!instr->i_hasarg)
3943 return 1; /* 1 byte for the opcode*/
3944 if (instr->i_oparg > 0xffff)
3945 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3946 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947}
3948
3949static int
3950blocksize(basicblock *b)
3951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 int i;
3953 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 for (i = 0; i < b->b_iused; i++)
3956 size += instrsize(&b->b_instr[i]);
3957 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003958}
3959
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003960/* Appends a pair to the end of the line number table, a_lnotab, representing
3961 the instruction's bytecode offset and line number. See
3962 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003963
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003964static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003965assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003968 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 d_bytecode = a->a_offset - a->a_lineno_off;
3972 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 assert(d_bytecode >= 0);
3975 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 if(d_bytecode == 0 && d_lineno == 0)
3978 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 if (d_bytecode > 255) {
3981 int j, nbytes, ncodes = d_bytecode / 255;
3982 nbytes = a->a_lnotab_off + 2 * ncodes;
3983 len = PyBytes_GET_SIZE(a->a_lnotab);
3984 if (nbytes >= len) {
3985 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3986 len = nbytes;
3987 else if (len <= INT_MAX / 2)
3988 len *= 2;
3989 else {
3990 PyErr_NoMemory();
3991 return 0;
3992 }
3993 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3994 return 0;
3995 }
3996 lnotab = (unsigned char *)
3997 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3998 for (j = 0; j < ncodes; j++) {
3999 *lnotab++ = 255;
4000 *lnotab++ = 0;
4001 }
4002 d_bytecode -= ncodes * 255;
4003 a->a_lnotab_off += ncodes * 2;
4004 }
4005 assert(d_bytecode <= 255);
4006 if (d_lineno > 255) {
4007 int j, nbytes, ncodes = d_lineno / 255;
4008 nbytes = a->a_lnotab_off + 2 * ncodes;
4009 len = PyBytes_GET_SIZE(a->a_lnotab);
4010 if (nbytes >= len) {
4011 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
4012 len = nbytes;
4013 else if (len <= INT_MAX / 2)
4014 len *= 2;
4015 else {
4016 PyErr_NoMemory();
4017 return 0;
4018 }
4019 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
4020 return 0;
4021 }
4022 lnotab = (unsigned char *)
4023 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4024 *lnotab++ = d_bytecode;
4025 *lnotab++ = 255;
4026 d_bytecode = 0;
4027 for (j = 1; j < ncodes; j++) {
4028 *lnotab++ = 0;
4029 *lnotab++ = 255;
4030 }
4031 d_lineno -= ncodes * 255;
4032 a->a_lnotab_off += ncodes * 2;
4033 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 len = PyBytes_GET_SIZE(a->a_lnotab);
4036 if (a->a_lnotab_off + 2 >= len) {
4037 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4038 return 0;
4039 }
4040 lnotab = (unsigned char *)
4041 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 a->a_lnotab_off += 2;
4044 if (d_bytecode) {
4045 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004046 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 }
4048 else { /* First line of a block; def stmt, etc. */
4049 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004050 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 }
4052 a->a_lineno = i->i_lineno;
4053 a->a_lineno_off = a->a_offset;
4054 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004055}
4056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057/* assemble_emit()
4058 Extend the bytecode with a new instruction.
4059 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004060*/
4061
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004062static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 int size, arg = 0, ext = 0;
4066 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4067 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 size = instrsize(i);
4070 if (i->i_hasarg) {
4071 arg = i->i_oparg;
4072 ext = arg >> 16;
4073 }
4074 if (i->i_lineno && !assemble_lnotab(a, i))
4075 return 0;
4076 if (a->a_offset + size >= len) {
4077 if (len > PY_SSIZE_T_MAX / 2)
4078 return 0;
4079 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4080 return 0;
4081 }
4082 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4083 a->a_offset += size;
4084 if (size == 6) {
4085 assert(i->i_hasarg);
4086 *code++ = (char)EXTENDED_ARG;
4087 *code++ = ext & 0xff;
4088 *code++ = ext >> 8;
4089 arg &= 0xffff;
4090 }
4091 *code++ = i->i_opcode;
4092 if (i->i_hasarg) {
4093 assert(size == 3 || size == 6);
4094 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004095 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 }
4097 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004098}
4099
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004100static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004101assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 basicblock *b;
4104 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4105 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 /* Compute the size of each block and fixup jump args.
4108 Replace block pointer with position in bytecode. */
4109 do {
4110 totsize = 0;
4111 for (i = a->a_nblocks - 1; i >= 0; i--) {
4112 b = a->a_postorder[i];
4113 bsize = blocksize(b);
4114 b->b_offset = totsize;
4115 totsize += bsize;
4116 }
4117 last_extended_arg_count = extended_arg_count;
4118 extended_arg_count = 0;
4119 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4120 bsize = b->b_offset;
4121 for (i = 0; i < b->b_iused; i++) {
4122 struct instr *instr = &b->b_instr[i];
4123 /* Relative jumps are computed relative to
4124 the instruction pointer after fetching
4125 the jump instruction.
4126 */
4127 bsize += instrsize(instr);
4128 if (instr->i_jabs)
4129 instr->i_oparg = instr->i_target->b_offset;
4130 else if (instr->i_jrel) {
4131 int delta = instr->i_target->b_offset - bsize;
4132 instr->i_oparg = delta;
4133 }
4134 else
4135 continue;
4136 if (instr->i_oparg > 0xffff)
4137 extended_arg_count++;
4138 }
4139 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 /* XXX: This is an awful hack that could hurt performance, but
4142 on the bright side it should work until we come up
4143 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 The issue is that in the first loop blocksize() is called
4146 which calls instrsize() which requires i_oparg be set
4147 appropriately. There is a bootstrap problem because
4148 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 So we loop until we stop seeing new EXTENDED_ARGs.
4151 The only EXTENDED_ARGs that could be popping up are
4152 ones in jump instructions. So this should converge
4153 fairly quickly.
4154 */
4155 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004156}
4157
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004158static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01004159dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 PyObject *tuple, *k, *v;
4162 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 tuple = PyTuple_New(size);
4165 if (tuple == NULL)
4166 return NULL;
4167 while (PyDict_Next(dict, &pos, &k, &v)) {
4168 i = PyLong_AS_LONG(v);
4169 /* The keys of the dictionary are tuples. (see compiler_add_o)
4170 The object we want is always first, though. */
4171 k = PyTuple_GET_ITEM(k, 0);
4172 Py_INCREF(k);
4173 assert((i - offset) < size);
4174 assert((i - offset) >= 0);
4175 PyTuple_SET_ITEM(tuple, i - offset, k);
4176 }
4177 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004178}
4179
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004180static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004184 int flags = 0;
4185 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004187 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 if (!ste->ste_unoptimized)
4189 flags |= CO_OPTIMIZED;
4190 if (ste->ste_nested)
4191 flags |= CO_NESTED;
4192 if (ste->ste_generator)
4193 flags |= CO_GENERATOR;
4194 if (ste->ste_varargs)
4195 flags |= CO_VARARGS;
4196 if (ste->ste_varkeywords)
4197 flags |= CO_VARKEYWORDS;
4198 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 /* (Only) inherit compilerflags in PyCF_MASK */
4201 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 n = PyDict_Size(c->u->u_freevars);
4204 if (n < 0)
4205 return -1;
4206 if (n == 0) {
4207 n = PyDict_Size(c->u->u_cellvars);
4208 if (n < 0)
Victor Stinnerad9a0662013-11-19 22:23:20 +01004209 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 if (n == 0) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004211 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 }
4213 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004216}
4217
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218static PyCodeObject *
4219makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 PyObject *tmp;
4222 PyCodeObject *co = NULL;
4223 PyObject *consts = NULL;
4224 PyObject *names = NULL;
4225 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 PyObject *name = NULL;
4227 PyObject *freevars = NULL;
4228 PyObject *cellvars = NULL;
4229 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004230 Py_ssize_t nlocals;
4231 int nlocals_int;
4232 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01004233 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 tmp = dict_keys_inorder(c->u->u_consts, 0);
4236 if (!tmp)
4237 goto error;
4238 consts = PySequence_List(tmp); /* optimize_code requires a list */
4239 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 names = dict_keys_inorder(c->u->u_names, 0);
4242 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4243 if (!consts || !names || !varnames)
4244 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4247 if (!cellvars)
4248 goto error;
4249 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4250 if (!freevars)
4251 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 nlocals = PyDict_Size(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01004254 assert(nlocals < INT_MAX);
4255 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
4256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 flags = compute_code_flags(c);
4258 if (flags < 0)
4259 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4262 if (!bytecode)
4263 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4266 if (!tmp)
4267 goto error;
4268 Py_DECREF(consts);
4269 consts = tmp;
4270
Victor Stinnerf8e32212013-11-19 23:56:34 +01004271 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
4272 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
4273 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01004274 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 bytecode, consts, names, varnames,
4276 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004277 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 c->u->u_firstlineno,
4279 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 Py_XDECREF(consts);
4282 Py_XDECREF(names);
4283 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 Py_XDECREF(name);
4285 Py_XDECREF(freevars);
4286 Py_XDECREF(cellvars);
4287 Py_XDECREF(bytecode);
4288 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004289}
4290
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004291
4292/* For debugging purposes only */
4293#if 0
4294static void
4295dump_instr(const struct instr *i)
4296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 const char *jrel = i->i_jrel ? "jrel " : "";
4298 const char *jabs = i->i_jabs ? "jabs " : "";
4299 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 *arg = '\0';
4302 if (i->i_hasarg)
4303 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4306 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004307}
4308
4309static void
4310dump_basicblock(const basicblock *b)
4311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 const char *seen = b->b_seen ? "seen " : "";
4313 const char *b_return = b->b_return ? "return " : "";
4314 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4315 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4316 if (b->b_instr) {
4317 int i;
4318 for (i = 0; i < b->b_iused; i++) {
4319 fprintf(stderr, " [%02d] ", i);
4320 dump_instr(b->b_instr + i);
4321 }
4322 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004323}
4324#endif
4325
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326static PyCodeObject *
4327assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 basicblock *b, *entryblock;
4330 struct assembler a;
4331 int i, j, nblocks;
4332 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 /* Make sure every block that falls off the end returns None.
4335 XXX NEXT_BLOCK() isn't quite right, because if the last
4336 block ends with a jump or return b_next shouldn't set.
4337 */
4338 if (!c->u->u_curblock->b_return) {
4339 NEXT_BLOCK(c);
4340 if (addNone)
4341 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4342 ADDOP(c, RETURN_VALUE);
4343 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 nblocks = 0;
4346 entryblock = NULL;
4347 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4348 nblocks++;
4349 entryblock = b;
4350 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 /* Set firstlineno if it wasn't explicitly set. */
4353 if (!c->u->u_firstlineno) {
4354 if (entryblock && entryblock->b_instr)
4355 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4356 else
4357 c->u->u_firstlineno = 1;
4358 }
4359 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4360 goto error;
4361 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 /* Can't modify the bytecode after computing jump offsets. */
4364 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 /* Emit code in reverse postorder from dfs. */
4367 for (i = a.a_nblocks - 1; i >= 0; i--) {
4368 b = a.a_postorder[i];
4369 for (j = 0; j < b->b_iused; j++)
4370 if (!assemble_emit(&a, &b->b_instr[j]))
4371 goto error;
4372 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4375 goto error;
4376 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4377 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004380 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 assemble_free(&a);
4382 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004383}
Georg Brandl8334fd92010-12-04 10:26:46 +00004384
4385#undef PyAST_Compile
4386PyAPI_FUNC(PyCodeObject *)
4387PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4388 PyArena *arena)
4389{
4390 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4391}
4392