blob: 9176e3131db76355bf4f9f98070e92640e28ed10 [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,
97 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 int u_argcount; /* number of arguments for block */
123 int u_kwonlyargcount; /* number of keyword only arguments for block */
124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000197static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 asdl_seq *args,
199 asdl_seq *keywords,
200 expr_ty starargs,
201 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204static PyCodeObject *assemble(struct compiler *, int addNone);
205static PyObject *__doc__;
206
Benjamin Petersonb173f782009-05-05 22:31:58 +0000207#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* Name mangling: __private becomes _classname__private.
213 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyObject *result;
215 size_t nlen, plen, ipriv;
216 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200218 PyUnicode_READ_CHAR(ident, 0) != '_' ||
219 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_INCREF(ident);
221 return ident;
222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200223 nlen = PyUnicode_GET_LENGTH(ident);
224 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 The only time a name with a dot can occur is when
228 we are compiling an import statement that has a
229 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 TODO(jhylton): Decide whether we want to support
232 mangling of the module name, e.g. __M.X.
233 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
235 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
236 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_INCREF(ident);
238 return ident; /* Don't mangle __whatever__ */
239 }
240 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 ipriv = 0;
242 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
243 ipriv++;
244 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle if class is just underscores */
247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000249
Antoine Pitrou55bff892013-04-06 21:21:04 +0200250 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
251 PyErr_SetString(PyExc_OverflowError,
252 "private identifier too large to be mangled");
253 return NULL;
254 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
257 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
258 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
259
260 result = PyUnicode_New(1 + nlen + plen, maxchar);
261 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
264 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200265 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
266 Py_DECREF(result);
267 return NULL;
268 }
269 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
270 Py_DECREF(result);
271 return NULL;
272 }
Victor Stinner8f825062012-04-27 13:55:39 +0200273 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000275}
276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277static int
278compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 c->c_stack = PyList_New(0);
283 if (!c->c_stack)
284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287}
288
289PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200290PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
291 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 struct compiler c;
294 PyCodeObject *co = NULL;
295 PyCompilerFlags local_flags;
296 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (!__doc__) {
299 __doc__ = PyUnicode_InternFromString("__doc__");
300 if (!__doc__)
301 return NULL;
302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!compiler_init(&c))
305 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200306 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 c.c_filename = filename;
308 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200309 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (c.c_future == NULL)
311 goto finally;
312 if (!flags) {
313 local_flags.cf_flags = 0;
314 flags = &local_flags;
315 }
316 merged = c.c_future->ff_features | flags->cf_flags;
317 c.c_future->ff_features = merged;
318 flags->cf_flags = merged;
319 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000320 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322
Victor Stinner14e461d2013-08-26 22:28:21 +0200323 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (c.c_st == NULL) {
325 if (!PyErr_Occurred())
326 PyErr_SetString(PyExc_SystemError, "no symtable");
327 goto finally;
328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Thomas Wouters1175c432006-02-27 22:49:54 +0000332 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 compiler_free(&c);
334 assert(co || PyErr_Occurred());
335 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336}
337
338PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200339PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
340 int optimize, PyArena *arena)
341{
342 PyObject *filename;
343 PyCodeObject *co;
344 filename = PyUnicode_DecodeFSDefault(filename_str);
345 if (filename == NULL)
346 return NULL;
347 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
348 Py_DECREF(filename);
349 return co;
350
351}
352
353PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354PyNode_Compile(struct _node *n, const char *filename)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyCodeObject *co = NULL;
357 mod_ty mod;
358 PyArena *arena = PyArena_New();
359 if (!arena)
360 return NULL;
361 mod = PyAST_FromNode(n, NULL, filename, arena);
362 if (mod)
363 co = PyAST_Compile(mod, filename, NULL, arena);
364 PyArena_Free(arena);
365 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000366}
367
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000368static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c->c_st)
372 PySymtable_Free(c->c_st);
373 if (c->c_future)
374 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200375 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000377}
378
Guido van Rossum79f25d91997-04-29 20:08:16 +0000379static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ssize_t i, n;
383 PyObject *v, *k;
384 PyObject *dict = PyDict_New();
385 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 n = PyList_Size(list);
388 for (i = 0; i < n; i++) {
389 v = PyLong_FromLong(i);
390 if (!v) {
391 Py_DECREF(dict);
392 return NULL;
393 }
394 k = PyList_GET_ITEM(list, i);
395 k = PyTuple_Pack(2, k, k->ob_type);
396 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
397 Py_XDECREF(k);
398 Py_DECREF(v);
399 Py_DECREF(dict);
400 return NULL;
401 }
402 Py_DECREF(k);
403 Py_DECREF(v);
404 }
405 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406}
407
408/* Return new dict containing names from src that match scope(s).
409
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412values are integers, starting at offset and increasing by one for
413each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414*/
415
416static PyObject *
417dictbytype(PyObject *src, int scope_type, int flag, int offset)
418{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700419 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500421 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 assert(offset >= 0);
424 if (dest == NULL)
425 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426
Meador Inge2ca63152012-07-18 14:20:11 -0500427 /* Sort the keys so that we have a deterministic order on the indexes
428 saved in the returned dictionary. These indexes are used as indexes
429 into the free and cell var storage. Therefore if they aren't
430 deterministic, then the generated bytecode is not deterministic.
431 */
432 sorted_keys = PyDict_Keys(src);
433 if (sorted_keys == NULL)
434 return NULL;
435 if (PyList_Sort(sorted_keys) != 0) {
436 Py_DECREF(sorted_keys);
437 return NULL;
438 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500439 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500440
441 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* XXX this should probably be a macro in symtable.h */
443 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500444 k = PyList_GET_ITEM(sorted_keys, key_i);
445 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(PyLong_Check(v));
447 vi = PyLong_AS_LONG(v);
448 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (scope == scope_type || vi & flag) {
451 PyObject *tuple, *item = PyLong_FromLong(i);
452 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500453 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 Py_DECREF(dest);
455 return NULL;
456 }
457 i++;
458 tuple = PyTuple_Pack(2, k, k->ob_type);
459 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500460 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 Py_DECREF(item);
462 Py_DECREF(dest);
463 Py_XDECREF(tuple);
464 return NULL;
465 }
466 Py_DECREF(item);
467 Py_DECREF(tuple);
468 }
469 }
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000472}
473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474static void
475compiler_unit_check(struct compiler_unit *u)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 basicblock *block;
478 for (block = u->u_blocks; block != NULL; block = block->b_list) {
479 assert((void *)block != (void *)0xcbcbcbcb);
480 assert((void *)block != (void *)0xfbfbfbfb);
481 assert((void *)block != (void *)0xdbdbdbdb);
482 if (block->b_instr != NULL) {
483 assert(block->b_ialloc > 0);
484 assert(block->b_iused > 0);
485 assert(block->b_ialloc >= block->b_iused);
486 }
487 else {
488 assert (block->b_iused == 0);
489 assert (block->b_ialloc == 0);
490 }
491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492}
493
494static void
495compiler_unit_free(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 compiler_unit_check(u);
500 b = u->u_blocks;
501 while (b != NULL) {
502 if (b->b_instr)
503 PyObject_Free((void *)b->b_instr);
504 next = b->b_list;
505 PyObject_Free((void *)b);
506 b = next;
507 }
508 Py_CLEAR(u->u_ste);
509 Py_CLEAR(u->u_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100510 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_CLEAR(u->u_consts);
512 Py_CLEAR(u->u_names);
513 Py_CLEAR(u->u_varnames);
514 Py_CLEAR(u->u_freevars);
515 Py_CLEAR(u->u_cellvars);
516 Py_CLEAR(u->u_private);
517 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100521compiler_enter_scope(struct compiler *c, identifier name,
522 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
527 struct compiler_unit));
528 if (!u) {
529 PyErr_NoMemory();
530 return 0;
531 }
532 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100533 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 u->u_argcount = 0;
535 u->u_kwonlyargcount = 0;
536 u->u_ste = PySymtable_Lookup(c->c_st, key);
537 if (!u->u_ste) {
538 compiler_unit_free(u);
539 return 0;
540 }
541 Py_INCREF(name);
542 u->u_name = name;
543 u->u_varnames = list2dict(u->u_ste->ste_varnames);
544 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
545 if (!u->u_varnames || !u->u_cellvars) {
546 compiler_unit_free(u);
547 return 0;
548 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500549 if (u->u_ste->ste_needs_class_closure) {
550 /* Cook up a implicit __class__ cell. */
551 _Py_IDENTIFIER(__class__);
552 PyObject *tuple, *name, *zero;
553 int res;
554 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
555 assert(PyDict_Size(u->u_cellvars) == 0);
556 name = _PyUnicode_FromId(&PyId___class__);
557 if (!name) {
558 compiler_unit_free(u);
559 return 0;
560 }
561 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
562 if (!tuple) {
563 compiler_unit_free(u);
564 return 0;
565 }
566 zero = PyLong_FromLong(0);
567 if (!zero) {
568 Py_DECREF(tuple);
569 compiler_unit_free(u);
570 return 0;
571 }
572 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
573 Py_DECREF(tuple);
574 Py_DECREF(zero);
575 if (res < 0) {
576 compiler_unit_free(u);
577 return 0;
578 }
579 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
582 PyDict_Size(u->u_cellvars));
583 if (!u->u_freevars) {
584 compiler_unit_free(u);
585 return 0;
586 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 u->u_blocks = NULL;
589 u->u_nfblocks = 0;
590 u->u_firstlineno = lineno;
591 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000592 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_lineno_set = 0;
594 u->u_consts = PyDict_New();
595 if (!u->u_consts) {
596 compiler_unit_free(u);
597 return 0;
598 }
599 u->u_names = PyDict_New();
600 if (!u->u_names) {
601 compiler_unit_free(u);
602 return 0;
603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* Push the old compiler_unit on the stack. */
608 if (c->u) {
609 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
610 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
611 Py_XDECREF(capsule);
612 compiler_unit_free(u);
613 return 0;
614 }
615 Py_DECREF(capsule);
616 u->u_private = c->u->u_private;
617 Py_XINCREF(u->u_private);
618 }
619 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 c->c_nestlevel++;
622 if (compiler_use_new_block(c) == NULL)
623 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626}
627
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000628static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629compiler_exit_scope(struct compiler *c)
630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 int n;
632 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 c->c_nestlevel--;
635 compiler_unit_free(c->u);
636 /* Restore c->u to the parent unit. */
637 n = PyList_GET_SIZE(c->c_stack) - 1;
638 if (n >= 0) {
639 capsule = PyList_GET_ITEM(c->c_stack, n);
640 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
641 assert(c->u);
642 /* we are deleting from a list so this really shouldn't fail */
643 if (PySequence_DelItem(c->c_stack, n) < 0)
644 Py_FatalError("compiler_exit_scope()");
645 compiler_unit_check(c->u);
646 }
647 else
648 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650}
651
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100652static PyObject *
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400653compiler_scope_qualname(struct compiler *c, identifier scope_name)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100654{
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400655 Py_ssize_t stack_size;
656 int global_scope;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100657 _Py_static_string(dot, ".");
658 _Py_static_string(locals, "<locals>");
659 struct compiler_unit *u;
660 PyObject *capsule, *name, *seq, *dot_str, *locals_str;
661
662 u = c->u;
663 if (u->u_qualname != NULL) {
664 Py_INCREF(u->u_qualname);
665 return u->u_qualname;
666 }
667
668 seq = PyList_New(0);
669 if (seq == NULL)
670 return NULL;
671
672 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400673 assert(stack_size >= 1);
674 global_scope = stack_size == 1;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400675 if (scope_name != NULL && !global_scope) {
676 int scope;
677 PyObject *mangled;
678 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100679 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
680 assert(u);
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400681 mangled = _Py_Mangle(u->u_private, scope_name);
682 if (!mangled)
683 return NULL;
684 scope = PyST_GetScope(u->u_ste, mangled);
685 Py_DECREF(mangled);
686 assert(scope != GLOBAL_IMPLICIT);
687 if (scope == GLOBAL_EXPLICIT)
688 global_scope = 1;
689 }
690 if (!global_scope) {
691 Py_ssize_t i;
692 for (i = 1; i < stack_size; i++) {
693 capsule = PyList_GET_ITEM(c->c_stack, i);
694 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
695 assert(u);
696 assert(u->u_scope_type != COMPILER_SCOPE_MODULE);
697 if (PyList_Append(seq, u->u_name))
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698 goto _error;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400699 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION) {
700 locals_str = _PyUnicode_FromId(&locals);
701 if (locals_str == NULL)
702 goto _error;
703 if (PyList_Append(seq, locals_str))
704 goto _error;
705 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 }
707 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100709 u = c->u;
710 if (PyList_Append(seq, u->u_name))
711 goto _error;
712 dot_str = _PyUnicode_FromId(&dot);
713 if (dot_str == NULL)
714 goto _error;
715 name = PyUnicode_Join(dot_str, seq);
716 Py_DECREF(seq);
717 u->u_qualname = name;
718 Py_XINCREF(name);
719 return name;
720
721_error:
722 Py_XDECREF(seq);
723 return NULL;
724}
725
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000726/* Allocate a new block and return a pointer to it.
727 Returns NULL on error.
728*/
729
730static basicblock *
731compiler_new_block(struct compiler *c)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 basicblock *b;
734 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 u = c->u;
737 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
738 if (b == NULL) {
739 PyErr_NoMemory();
740 return NULL;
741 }
742 memset((void *)b, 0, sizeof(basicblock));
743 /* Extend the singly linked list of blocks with new block. */
744 b->b_list = u->u_blocks;
745 u->u_blocks = b;
746 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747}
748
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749static basicblock *
750compiler_use_new_block(struct compiler *c)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 basicblock *block = compiler_new_block(c);
753 if (block == NULL)
754 return NULL;
755 c->u->u_curblock = block;
756 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757}
758
759static basicblock *
760compiler_next_block(struct compiler *c)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 basicblock *block = compiler_new_block(c);
763 if (block == NULL)
764 return NULL;
765 c->u->u_curblock->b_next = block;
766 c->u->u_curblock = block;
767 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768}
769
770static basicblock *
771compiler_use_next_block(struct compiler *c, basicblock *block)
772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 assert(block != NULL);
774 c->u->u_curblock->b_next = block;
775 c->u->u_curblock = block;
776 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777}
778
779/* Returns the offset of the next instruction in the current block's
780 b_instr array. Resizes the b_instr as necessary.
781 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000782*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783
784static int
785compiler_next_instr(struct compiler *c, basicblock *b)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 assert(b != NULL);
788 if (b->b_instr == NULL) {
789 b->b_instr = (struct instr *)PyObject_Malloc(
790 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
791 if (b->b_instr == NULL) {
792 PyErr_NoMemory();
793 return -1;
794 }
795 b->b_ialloc = DEFAULT_BLOCK_SIZE;
796 memset((char *)b->b_instr, 0,
797 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
798 }
799 else if (b->b_iused == b->b_ialloc) {
800 struct instr *tmp;
801 size_t oldsize, newsize;
802 oldsize = b->b_ialloc * sizeof(struct instr);
803 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (oldsize > (PY_SIZE_MAX >> 1)) {
806 PyErr_NoMemory();
807 return -1;
808 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (newsize == 0) {
811 PyErr_NoMemory();
812 return -1;
813 }
814 b->b_ialloc <<= 1;
815 tmp = (struct instr *)PyObject_Realloc(
816 (void *)b->b_instr, newsize);
817 if (tmp == NULL) {
818 PyErr_NoMemory();
819 return -1;
820 }
821 b->b_instr = tmp;
822 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
823 }
824 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000825}
826
Christian Heimes2202f872008-02-06 14:31:34 +0000827/* Set the i_lineno member of the instruction at offset off if the
828 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000829 already been set. If it has been set, the call has no effect.
830
Christian Heimes2202f872008-02-06 14:31:34 +0000831 The line number is reset in the following cases:
832 - when entering a new scope
833 - on each statement
834 - on each expression that start a new line
835 - before the "except" clause
836 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000837*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000839static void
840compiler_set_lineno(struct compiler *c, int off)
841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 basicblock *b;
843 if (c->u->u_lineno_set)
844 return;
845 c->u->u_lineno_set = 1;
846 b = c->u->u_curblock;
847 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848}
849
850static int
851opcode_stack_effect(int opcode, int oparg)
852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 switch (opcode) {
854 case POP_TOP:
855 return -1;
856 case ROT_TWO:
857 case ROT_THREE:
858 return 0;
859 case DUP_TOP:
860 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000861 case DUP_TOP_TWO:
862 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 case UNARY_POSITIVE:
865 case UNARY_NEGATIVE:
866 case UNARY_NOT:
867 case UNARY_INVERT:
868 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case SET_ADD:
871 case LIST_APPEND:
872 return -1;
873 case MAP_ADD:
874 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case BINARY_POWER:
877 case BINARY_MULTIPLY:
878 case BINARY_MODULO:
879 case BINARY_ADD:
880 case BINARY_SUBTRACT:
881 case BINARY_SUBSCR:
882 case BINARY_FLOOR_DIVIDE:
883 case BINARY_TRUE_DIVIDE:
884 return -1;
885 case INPLACE_FLOOR_DIVIDE:
886 case INPLACE_TRUE_DIVIDE:
887 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case INPLACE_ADD:
890 case INPLACE_SUBTRACT:
891 case INPLACE_MULTIPLY:
892 case INPLACE_MODULO:
893 return -1;
894 case STORE_SUBSCR:
895 return -3;
896 case STORE_MAP:
897 return -2;
898 case DELETE_SUBSCR:
899 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case BINARY_LSHIFT:
902 case BINARY_RSHIFT:
903 case BINARY_AND:
904 case BINARY_XOR:
905 case BINARY_OR:
906 return -1;
907 case INPLACE_POWER:
908 return -1;
909 case GET_ITER:
910 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 case PRINT_EXPR:
913 return -1;
914 case LOAD_BUILD_CLASS:
915 return 1;
916 case INPLACE_LSHIFT:
917 case INPLACE_RSHIFT:
918 case INPLACE_AND:
919 case INPLACE_XOR:
920 case INPLACE_OR:
921 return -1;
922 case BREAK_LOOP:
923 return 0;
924 case SETUP_WITH:
925 return 7;
926 case WITH_CLEANUP:
927 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case RETURN_VALUE:
929 return -1;
930 case IMPORT_STAR:
931 return -1;
932 case YIELD_VALUE:
933 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500934 case YIELD_FROM:
935 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case POP_BLOCK:
937 return 0;
938 case POP_EXCEPT:
939 return 0; /* -3 except if bad bytecode */
940 case END_FINALLY:
941 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 case STORE_NAME:
944 return -1;
945 case DELETE_NAME:
946 return 0;
947 case UNPACK_SEQUENCE:
948 return oparg-1;
949 case UNPACK_EX:
950 return (oparg&0xFF) + (oparg>>8);
951 case FOR_ITER:
952 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 case STORE_ATTR:
955 return -2;
956 case DELETE_ATTR:
957 return -1;
958 case STORE_GLOBAL:
959 return -1;
960 case DELETE_GLOBAL:
961 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 case LOAD_CONST:
963 return 1;
964 case LOAD_NAME:
965 return 1;
966 case BUILD_TUPLE:
967 case BUILD_LIST:
968 case BUILD_SET:
969 return 1-oparg;
970 case BUILD_MAP:
971 return 1;
972 case LOAD_ATTR:
973 return 0;
974 case COMPARE_OP:
975 return -1;
976 case IMPORT_NAME:
977 return -1;
978 case IMPORT_FROM:
979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case JUMP_FORWARD:
982 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
983 case JUMP_IF_FALSE_OR_POP: /* "" */
984 case JUMP_ABSOLUTE:
985 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case POP_JUMP_IF_FALSE:
988 case POP_JUMP_IF_TRUE:
989 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 case LOAD_GLOBAL:
992 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 case CONTINUE_LOOP:
995 return 0;
996 case SETUP_LOOP:
997 return 0;
998 case SETUP_EXCEPT:
999 case SETUP_FINALLY:
1000 return 6; /* can push 3 values for the new exception
1001 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case LOAD_FAST:
1004 return 1;
1005 case STORE_FAST:
1006 return -1;
1007 case DELETE_FAST:
1008 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 case RAISE_VARARGS:
1011 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001012#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 case CALL_FUNCTION:
1014 return -NARGS(oparg);
1015 case CALL_FUNCTION_VAR:
1016 case CALL_FUNCTION_KW:
1017 return -NARGS(oparg)-1;
1018 case CALL_FUNCTION_VAR_KW:
1019 return -NARGS(oparg)-2;
1020 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001021 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001023 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001024#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 case BUILD_SLICE:
1026 if (oparg == 3)
1027 return -2;
1028 else
1029 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case LOAD_CLOSURE:
1032 return 1;
1033 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001034 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 return 1;
1036 case STORE_DEREF:
1037 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001038 case DELETE_DEREF:
1039 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 default:
1041 fprintf(stderr, "opcode = %d\n", opcode);
1042 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 }
1045 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046}
1047
1048/* Add an opcode with no argument.
1049 Returns 0 on failure, 1 on success.
1050*/
1051
1052static int
1053compiler_addop(struct compiler *c, int opcode)
1054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 basicblock *b;
1056 struct instr *i;
1057 int off;
1058 off = compiler_next_instr(c, c->u->u_curblock);
1059 if (off < 0)
1060 return 0;
1061 b = c->u->u_curblock;
1062 i = &b->b_instr[off];
1063 i->i_opcode = opcode;
1064 i->i_hasarg = 0;
1065 if (opcode == RETURN_VALUE)
1066 b->b_return = 1;
1067 compiler_set_lineno(c, off);
1068 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069}
1070
1071static int
1072compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyObject *t, *v;
1075 Py_ssize_t arg;
1076 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001077
Serhiy Storchaka95949422013-08-27 19:40:23 +03001078 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1080 if (PyFloat_Check(o)) {
1081 d = PyFloat_AS_DOUBLE(o);
1082 /* all we need is to make the tuple different in either the 0.0
1083 * or -0.0 case from all others, just to avoid the "coercion".
1084 */
1085 if (d == 0.0 && copysign(1.0, d) < 0.0)
1086 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1087 else
1088 t = PyTuple_Pack(2, o, o->ob_type);
1089 }
1090 else if (PyComplex_Check(o)) {
1091 Py_complex z;
1092 int real_negzero, imag_negzero;
1093 /* For the complex case we must make complex(x, 0.)
1094 different from complex(x, -0.) and complex(0., y)
1095 different from complex(-0., y), for any x and y.
1096 All four complex zeros must be distinguished.*/
1097 z = PyComplex_AsCComplex(o);
1098 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1099 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1100 if (real_negzero && imag_negzero) {
1101 t = PyTuple_Pack(5, o, o->ob_type,
1102 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 else if (imag_negzero) {
1105 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 else if (real_negzero) {
1108 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1109 }
1110 else {
1111 t = PyTuple_Pack(2, o, o->ob_type);
1112 }
1113 }
1114 else {
1115 t = PyTuple_Pack(2, o, o->ob_type);
1116 }
1117 if (t == NULL)
1118 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 v = PyDict_GetItem(dict, t);
1121 if (!v) {
1122 if (PyErr_Occurred())
1123 return -1;
1124 arg = PyDict_Size(dict);
1125 v = PyLong_FromLong(arg);
1126 if (!v) {
1127 Py_DECREF(t);
1128 return -1;
1129 }
1130 if (PyDict_SetItem(dict, t, v) < 0) {
1131 Py_DECREF(t);
1132 Py_DECREF(v);
1133 return -1;
1134 }
1135 Py_DECREF(v);
1136 }
1137 else
1138 arg = PyLong_AsLong(v);
1139 Py_DECREF(t);
1140 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141}
1142
1143static int
1144compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146{
1147 int arg = compiler_add_o(c, dict, o);
1148 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001149 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 return compiler_addop_i(c, opcode, arg);
1151}
1152
1153static int
1154compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156{
1157 int arg;
1158 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1159 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001160 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 arg = compiler_add_o(c, dict, mangled);
1162 Py_DECREF(mangled);
1163 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 return compiler_addop_i(c, opcode, arg);
1166}
1167
1168/* Add an opcode with an integer argument.
1169 Returns 0 on failure, 1 on success.
1170*/
1171
1172static int
1173compiler_addop_i(struct compiler *c, int opcode, int oparg)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 struct instr *i;
1176 int off;
1177 off = compiler_next_instr(c, c->u->u_curblock);
1178 if (off < 0)
1179 return 0;
1180 i = &c->u->u_curblock->b_instr[off];
1181 i->i_opcode = opcode;
1182 i->i_oparg = oparg;
1183 i->i_hasarg = 1;
1184 compiler_set_lineno(c, off);
1185 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186}
1187
1188static int
1189compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 struct instr *i;
1192 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 assert(b != NULL);
1195 off = compiler_next_instr(c, c->u->u_curblock);
1196 if (off < 0)
1197 return 0;
1198 i = &c->u->u_curblock->b_instr[off];
1199 i->i_opcode = opcode;
1200 i->i_target = b;
1201 i->i_hasarg = 1;
1202 if (absolute)
1203 i->i_jabs = 1;
1204 else
1205 i->i_jrel = 1;
1206 compiler_set_lineno(c, off);
1207 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208}
1209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1211 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 it as the current block. NEXT_BLOCK() also creates an implicit jump
1213 from the current block to the new block.
1214*/
1215
Thomas Wouters89f507f2006-12-13 04:49:30 +00001216/* The returns inside these macros make it impossible to decref objects
1217 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218*/
1219
1220
1221#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (compiler_use_new_block((C)) == NULL) \
1223 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224}
1225
1226#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (compiler_next_block((C)) == NULL) \
1228 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229}
1230
1231#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!compiler_addop((C), (OP))) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001236#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!compiler_addop((C), (OP))) { \
1238 compiler_exit_scope(c); \
1239 return 0; \
1240 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001241}
1242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1245 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246}
1247
1248#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1250 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251}
1252
1253#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (!compiler_addop_i((C), (OP), (O))) \
1255 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256}
1257
1258#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (!compiler_addop_j((C), (OP), (O), 1)) \
1260 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261}
1262
1263#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_addop_j((C), (OP), (O), 0)) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1269 the ASDL name to synthesize the name of the C type and the visit function.
1270*/
1271
1272#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!compiler_visit_ ## TYPE((C), (V))) \
1274 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275}
1276
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001277#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (!compiler_visit_ ## TYPE((C), (V))) { \
1279 compiler_exit_scope(c); \
1280 return 0; \
1281 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001282}
1283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!compiler_visit_slice((C), (V), (CTX))) \
1286 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
1289#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 int _i; \
1291 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1292 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1293 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1294 if (!compiler_visit_ ## TYPE((C), elt)) \
1295 return 0; \
1296 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297}
1298
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001299#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 int _i; \
1301 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1302 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1303 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1304 if (!compiler_visit_ ## TYPE((C), elt)) { \
1305 compiler_exit_scope(c); \
1306 return 0; \
1307 } \
1308 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001309}
1310
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311static int
1312compiler_isdocstring(stmt_ty s)
1313{
1314 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001315 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316 return s->v.Expr.value->kind == Str_kind;
1317}
1318
1319/* Compile a sequence of statements, checking for a docstring. */
1320
1321static int
1322compiler_body(struct compiler *c, asdl_seq *stmts)
1323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 int i = 0;
1325 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (!asdl_seq_LEN(stmts))
1328 return 1;
1329 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001330 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* don't generate docstrings if -OO */
1332 i = 1;
1333 VISIT(c, expr, st->v.Expr.value);
1334 if (!compiler_nameop(c, __doc__, Store))
1335 return 0;
1336 }
1337 for (; i < asdl_seq_LEN(stmts); i++)
1338 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1339 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340}
1341
1342static PyCodeObject *
1343compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 PyCodeObject *co;
1346 int addNone = 1;
1347 static PyObject *module;
1348 if (!module) {
1349 module = PyUnicode_InternFromString("<module>");
1350 if (!module)
1351 return NULL;
1352 }
1353 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001354 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 return NULL;
1356 switch (mod->kind) {
1357 case Module_kind:
1358 if (!compiler_body(c, mod->v.Module.body)) {
1359 compiler_exit_scope(c);
1360 return 0;
1361 }
1362 break;
1363 case Interactive_kind:
1364 c->c_interactive = 1;
1365 VISIT_SEQ_IN_SCOPE(c, stmt,
1366 mod->v.Interactive.body);
1367 break;
1368 case Expression_kind:
1369 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1370 addNone = 0;
1371 break;
1372 case Suite_kind:
1373 PyErr_SetString(PyExc_SystemError,
1374 "suite should not be possible");
1375 return 0;
1376 default:
1377 PyErr_Format(PyExc_SystemError,
1378 "module kind %d should not be possible",
1379 mod->kind);
1380 return 0;
1381 }
1382 co = assemble(c, addNone);
1383 compiler_exit_scope(c);
1384 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001385}
1386
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387/* The test for LOCAL must come before the test for FREE in order to
1388 handle classes where name is both local and free. The local var is
1389 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001390*/
1391
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392static int
1393get_ref_type(struct compiler *c, PyObject *name)
1394{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001395 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001396 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1397 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1398 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001399 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (scope == 0) {
1401 char buf[350];
1402 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001403 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 "symbols: %s\nlocals: %s\nglobals: %s",
1405 PyBytes_AS_STRING(name),
1406 PyBytes_AS_STRING(c->u->u_name),
1407 PyObject_REPR(c->u->u_ste->ste_id),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyObject_REPR(c->u->u_ste->ste_symbols),
1409 PyObject_REPR(c->u->u_varnames),
1410 PyObject_REPR(c->u->u_names)
1411 );
1412 Py_FatalError(buf);
1413 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416}
1417
1418static int
1419compiler_lookup_arg(PyObject *dict, PyObject *name)
1420{
1421 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001422 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001424 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001426 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001428 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001429 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430}
1431
1432static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001433compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001436 if (qualname == NULL)
1437 qualname = co->co_name;
1438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 if (free == 0) {
1440 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001441 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 ADDOP_I(c, MAKE_FUNCTION, args);
1443 return 1;
1444 }
1445 for (i = 0; i < free; ++i) {
1446 /* Bypass com_addop_varname because it will generate
1447 LOAD_DEREF but LOAD_CLOSURE is needed.
1448 */
1449 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1450 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 /* Special case: If a class contains a method with a
1453 free variable that has the same name as a method,
1454 the name will be considered free *and* local in the
1455 class. It should be handled by the closure, as
1456 well as by the normal name loookup logic.
1457 */
1458 reftype = get_ref_type(c, name);
1459 if (reftype == CELL)
1460 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1461 else /* (reftype == FREE) */
1462 arg = compiler_lookup_arg(c->u->u_freevars, name);
1463 if (arg == -1) {
1464 fprintf(stderr,
1465 "lookup %s in %s %d %d\n"
1466 "freevars of %s: %s\n",
1467 PyObject_REPR(name),
1468 PyBytes_AS_STRING(c->u->u_name),
1469 reftype, arg,
1470 _PyUnicode_AsString(co->co_name),
1471 PyObject_REPR(co->co_freevars));
1472 Py_FatalError("compiler_make_closure()");
1473 }
1474 ADDOP_I(c, LOAD_CLOSURE, arg);
1475 }
1476 ADDOP_I(c, BUILD_TUPLE, free);
1477 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001478 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 ADDOP_I(c, MAKE_CLOSURE, args);
1480 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481}
1482
1483static int
1484compiler_decorators(struct compiler *c, asdl_seq* decos)
1485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (!decos)
1489 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1492 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1493 }
1494 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495}
1496
1497static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001498compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 int i, default_count = 0;
1502 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1503 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1504 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1505 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001506 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1507 if (!mangled)
1508 return -1;
1509 ADDOP_O(c, LOAD_CONST, mangled, consts);
1510 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!compiler_visit_expr(c, default_)) {
1512 return -1;
1513 }
1514 default_count++;
1515 }
1516 }
1517 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001518}
1519
1520static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001521compiler_visit_argannotation(struct compiler *c, identifier id,
1522 expr_ty annotation, PyObject *names)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (annotation) {
1525 VISIT(c, expr, annotation);
1526 if (PyList_Append(names, id))
1527 return -1;
1528 }
1529 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001530}
1531
1532static int
1533compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1534 PyObject *names)
1535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 int i, error;
1537 for (i = 0; i < asdl_seq_LEN(args); i++) {
1538 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1539 error = compiler_visit_argannotation(
1540 c,
1541 arg->arg,
1542 arg->annotation,
1543 names);
1544 if (error)
1545 return error;
1546 }
1547 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001548}
1549
1550static int
1551compiler_visit_annotations(struct compiler *c, arguments_ty args,
1552 expr_ty returns)
1553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 /* Push arg annotations and a list of the argument names. Return the #
1555 of items pushed. The expressions are evaluated out-of-order wrt the
1556 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1559 */
1560 static identifier return_str;
1561 PyObject *names;
1562 int len;
1563 names = PyList_New(0);
1564 if (!names)
1565 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (compiler_visit_argannotations(c, args->args, names))
1568 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001569 if (args->vararg && args->vararg->annotation &&
1570 compiler_visit_argannotation(c, args->vararg->arg,
1571 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 goto error;
1573 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1574 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001575 if (args->kwarg && args->kwarg->annotation &&
1576 compiler_visit_argannotation(c, args->kwarg->arg,
1577 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (!return_str) {
1581 return_str = PyUnicode_InternFromString("return");
1582 if (!return_str)
1583 goto error;
1584 }
1585 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1586 goto error;
1587 }
1588
1589 len = PyList_GET_SIZE(names);
1590 if (len > 65534) {
1591 /* len must fit in 16 bits, and len is incremented below */
1592 PyErr_SetString(PyExc_SyntaxError,
1593 "too many annotations");
1594 goto error;
1595 }
1596 if (len) {
1597 /* convert names to a tuple and place on stack */
1598 PyObject *elt;
1599 int i;
1600 PyObject *s = PyTuple_New(len);
1601 if (!s)
1602 goto error;
1603 for (i = 0; i < len; i++) {
1604 elt = PyList_GET_ITEM(names, i);
1605 Py_INCREF(elt);
1606 PyTuple_SET_ITEM(s, i, elt);
1607 }
1608 ADDOP_O(c, LOAD_CONST, s, consts);
1609 Py_DECREF(s);
1610 len++; /* include the just-pushed tuple */
1611 }
1612 Py_DECREF(names);
1613 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001614
1615error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 Py_DECREF(names);
1617 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001618}
1619
1620static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621compiler_function(struct compiler *c, stmt_ty s)
1622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001624 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 arguments_ty args = s->v.FunctionDef.args;
1626 expr_ty returns = s->v.FunctionDef.returns;
1627 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1628 stmt_ty st;
1629 int i, n, docstring, kw_default_count = 0, arglength;
1630 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (!compiler_decorators(c, decos))
1635 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001636 if (args->defaults)
1637 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (args->kwonlyargs) {
1639 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1640 args->kw_defaults);
1641 if (res < 0)
1642 return 0;
1643 kw_default_count = res;
1644 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 num_annotations = compiler_visit_annotations(c, args, returns);
1646 if (num_annotations < 0)
1647 return 0;
1648 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001649
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001650 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1651 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 s->lineno))
1653 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1656 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001657 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 first_const = st->v.Expr.value->v.Str.s;
1659 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1660 compiler_exit_scope(c);
1661 return 0;
1662 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 c->u->u_argcount = asdl_seq_LEN(args->args);
1665 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1666 n = asdl_seq_LEN(s->v.FunctionDef.body);
1667 /* if there was a docstring, we need to skip the first statement */
1668 for (i = docstring; i < n; i++) {
1669 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1670 VISIT_IN_SCOPE(c, stmt, st);
1671 }
1672 co = assemble(c, 1);
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04001673 qualname = compiler_scope_qualname(c, s->v.FunctionDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001675 if (qualname == NULL || co == NULL) {
1676 Py_XDECREF(qualname);
1677 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001679 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 arglength = asdl_seq_LEN(args->defaults);
1682 arglength |= kw_default_count << 8;
1683 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001684 compiler_make_closure(c, co, arglength, qualname);
1685 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* decorators */
1689 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1690 ADDOP_I(c, CALL_FUNCTION, 1);
1691 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694}
1695
1696static int
1697compiler_class(struct compiler *c, stmt_ty s)
1698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 PyCodeObject *co;
1700 PyObject *str;
1701 int i;
1702 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (!compiler_decorators(c, decos))
1705 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* ultimately generate code for:
1708 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1709 where:
1710 <func> is a function/closure created from the class body;
1711 it has a single argument (__locals__) where the dict
1712 (or MutableSequence) representing the locals is passed
1713 <name> is the class name
1714 <bases> is the positional arguments and *varargs argument
1715 <keywords> is the keyword arguments and **kwds argument
1716 This borrows from compiler_call.
1717 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001720 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1721 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 return 0;
1723 /* this block represents what we do in the new scope */
1724 {
1725 /* use the class name for name mangling */
1726 Py_INCREF(s->v.ClassDef.name);
1727 Py_XDECREF(c->u->u_private);
1728 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* load (global) __name__ ... */
1730 str = PyUnicode_InternFromString("__name__");
1731 if (!str || !compiler_nameop(c, str, Load)) {
1732 Py_XDECREF(str);
1733 compiler_exit_scope(c);
1734 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001735 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 Py_DECREF(str);
1737 /* ... and store it as __module__ */
1738 str = PyUnicode_InternFromString("__module__");
1739 if (!str || !compiler_nameop(c, str, Store)) {
1740 Py_XDECREF(str);
1741 compiler_exit_scope(c);
1742 return 0;
1743 }
1744 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001745 /* store the __qualname__ */
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04001746 str = compiler_scope_qualname(c, s->v.ClassDef.name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001747 if (!str) {
1748 compiler_exit_scope(c);
1749 return 0;
1750 }
1751 ADDOP_O(c, LOAD_CONST, str, consts);
1752 Py_DECREF(str);
1753 str = PyUnicode_InternFromString("__qualname__");
1754 if (!str || !compiler_nameop(c, str, Store)) {
1755 Py_XDECREF(str);
1756 compiler_exit_scope(c);
1757 return 0;
1758 }
1759 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 /* compile the body proper */
1761 if (!compiler_body(c, s->v.ClassDef.body)) {
1762 compiler_exit_scope(c);
1763 return 0;
1764 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001765 if (c->u->u_ste->ste_needs_class_closure) {
1766 /* return the (empty) __class__ cell */
1767 str = PyUnicode_InternFromString("__class__");
1768 if (str == NULL) {
1769 compiler_exit_scope(c);
1770 return 0;
1771 }
1772 i = compiler_lookup_arg(c->u->u_cellvars, str);
1773 Py_DECREF(str);
1774 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* Return the cell where to store __class__ */
1776 ADDOP_I(c, LOAD_CLOSURE, i);
1777 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001778 else {
1779 assert(PyDict_Size(c->u->u_cellvars) == 0);
1780 /* This happens when nobody references the cell. Return None. */
1781 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1784 /* create the code object */
1785 co = assemble(c, 1);
1786 }
1787 /* leave the new scope */
1788 compiler_exit_scope(c);
1789 if (co == NULL)
1790 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* 2. load the 'build_class' function */
1793 ADDOP(c, LOAD_BUILD_CLASS);
1794
1795 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001796 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 Py_DECREF(co);
1798
1799 /* 4. load class name */
1800 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1801
1802 /* 5. generate the rest of the code for the call */
1803 if (!compiler_call_helper(c, 2,
1804 s->v.ClassDef.bases,
1805 s->v.ClassDef.keywords,
1806 s->v.ClassDef.starargs,
1807 s->v.ClassDef.kwargs))
1808 return 0;
1809
1810 /* 6. apply decorators */
1811 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1812 ADDOP_I(c, CALL_FUNCTION, 1);
1813 }
1814
1815 /* 7. store into <name> */
1816 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1817 return 0;
1818 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819}
1820
1821static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001822compiler_ifexp(struct compiler *c, expr_ty e)
1823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 basicblock *end, *next;
1825
1826 assert(e->kind == IfExp_kind);
1827 end = compiler_new_block(c);
1828 if (end == NULL)
1829 return 0;
1830 next = compiler_new_block(c);
1831 if (next == NULL)
1832 return 0;
1833 VISIT(c, expr, e->v.IfExp.test);
1834 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1835 VISIT(c, expr, e->v.IfExp.body);
1836 ADDOP_JREL(c, JUMP_FORWARD, end);
1837 compiler_use_next_block(c, next);
1838 VISIT(c, expr, e->v.IfExp.orelse);
1839 compiler_use_next_block(c, end);
1840 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001841}
1842
1843static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844compiler_lambda(struct compiler *c, expr_ty e)
1845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001847 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 static identifier name;
1849 int kw_default_count = 0, arglength;
1850 arguments_ty args = e->v.Lambda.args;
1851 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 if (!name) {
1854 name = PyUnicode_InternFromString("<lambda>");
1855 if (!name)
1856 return 0;
1857 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001859 if (args->defaults)
1860 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (args->kwonlyargs) {
1862 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1863 args->kw_defaults);
1864 if (res < 0) return 0;
1865 kw_default_count = res;
1866 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001867 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1868 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 /* Make None the first constant, so the lambda can't have a
1872 docstring. */
1873 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1874 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 c->u->u_argcount = asdl_seq_LEN(args->args);
1877 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1878 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1879 if (c->u->u_ste->ste_generator) {
1880 ADDOP_IN_SCOPE(c, POP_TOP);
1881 }
1882 else {
1883 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1884 }
1885 co = assemble(c, 1);
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04001886 qualname = compiler_scope_qualname(c, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001888 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 arglength = asdl_seq_LEN(args->defaults);
1892 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001893 compiler_make_closure(c, co, arglength, qualname);
1894 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 Py_DECREF(co);
1896
1897 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898}
1899
1900static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901compiler_if(struct compiler *c, stmt_ty s)
1902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 basicblock *end, *next;
1904 int constant;
1905 assert(s->kind == If_kind);
1906 end = compiler_new_block(c);
1907 if (end == NULL)
1908 return 0;
1909
Georg Brandl8334fd92010-12-04 10:26:46 +00001910 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 /* constant = 0: "if 0"
1912 * constant = 1: "if 1", "if 2", ...
1913 * constant = -1: rest */
1914 if (constant == 0) {
1915 if (s->v.If.orelse)
1916 VISIT_SEQ(c, stmt, s->v.If.orelse);
1917 } else if (constant == 1) {
1918 VISIT_SEQ(c, stmt, s->v.If.body);
1919 } else {
1920 if (s->v.If.orelse) {
1921 next = compiler_new_block(c);
1922 if (next == NULL)
1923 return 0;
1924 }
1925 else
1926 next = end;
1927 VISIT(c, expr, s->v.If.test);
1928 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1929 VISIT_SEQ(c, stmt, s->v.If.body);
1930 ADDOP_JREL(c, JUMP_FORWARD, end);
1931 if (s->v.If.orelse) {
1932 compiler_use_next_block(c, next);
1933 VISIT_SEQ(c, stmt, s->v.If.orelse);
1934 }
1935 }
1936 compiler_use_next_block(c, end);
1937 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938}
1939
1940static int
1941compiler_for(struct compiler *c, stmt_ty s)
1942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 start = compiler_new_block(c);
1946 cleanup = compiler_new_block(c);
1947 end = compiler_new_block(c);
1948 if (start == NULL || end == NULL || cleanup == NULL)
1949 return 0;
1950 ADDOP_JREL(c, SETUP_LOOP, end);
1951 if (!compiler_push_fblock(c, LOOP, start))
1952 return 0;
1953 VISIT(c, expr, s->v.For.iter);
1954 ADDOP(c, GET_ITER);
1955 compiler_use_next_block(c, start);
1956 ADDOP_JREL(c, FOR_ITER, cleanup);
1957 VISIT(c, expr, s->v.For.target);
1958 VISIT_SEQ(c, stmt, s->v.For.body);
1959 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1960 compiler_use_next_block(c, cleanup);
1961 ADDOP(c, POP_BLOCK);
1962 compiler_pop_fblock(c, LOOP, start);
1963 VISIT_SEQ(c, stmt, s->v.For.orelse);
1964 compiler_use_next_block(c, end);
1965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966}
1967
1968static int
1969compiler_while(struct compiler *c, stmt_ty s)
1970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001972 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (constant == 0) {
1975 if (s->v.While.orelse)
1976 VISIT_SEQ(c, stmt, s->v.While.orelse);
1977 return 1;
1978 }
1979 loop = compiler_new_block(c);
1980 end = compiler_new_block(c);
1981 if (constant == -1) {
1982 anchor = compiler_new_block(c);
1983 if (anchor == NULL)
1984 return 0;
1985 }
1986 if (loop == NULL || end == NULL)
1987 return 0;
1988 if (s->v.While.orelse) {
1989 orelse = compiler_new_block(c);
1990 if (orelse == NULL)
1991 return 0;
1992 }
1993 else
1994 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 ADDOP_JREL(c, SETUP_LOOP, end);
1997 compiler_use_next_block(c, loop);
1998 if (!compiler_push_fblock(c, LOOP, loop))
1999 return 0;
2000 if (constant == -1) {
2001 VISIT(c, expr, s->v.While.test);
2002 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2003 }
2004 VISIT_SEQ(c, stmt, s->v.While.body);
2005 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 /* XXX should the two POP instructions be in a separate block
2008 if there is no else clause ?
2009 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (constant == -1) {
2012 compiler_use_next_block(c, anchor);
2013 ADDOP(c, POP_BLOCK);
2014 }
2015 compiler_pop_fblock(c, LOOP, loop);
2016 if (orelse != NULL) /* what if orelse is just pass? */
2017 VISIT_SEQ(c, stmt, s->v.While.orelse);
2018 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021}
2022
2023static int
2024compiler_continue(struct compiler *c)
2025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2027 static const char IN_FINALLY_ERROR_MSG[] =
2028 "'continue' not supported inside 'finally' clause";
2029 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (!c->u->u_nfblocks)
2032 return compiler_error(c, LOOP_ERROR_MSG);
2033 i = c->u->u_nfblocks - 1;
2034 switch (c->u->u_fblock[i].fb_type) {
2035 case LOOP:
2036 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2037 break;
2038 case EXCEPT:
2039 case FINALLY_TRY:
2040 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2041 /* Prevent continue anywhere under a finally
2042 even if hidden in a sub-try or except. */
2043 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2044 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2045 }
2046 if (i == -1)
2047 return compiler_error(c, LOOP_ERROR_MSG);
2048 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2049 break;
2050 case FINALLY_END:
2051 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2052 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055}
2056
2057/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058
2059 SETUP_FINALLY L
2060 <code for body>
2061 POP_BLOCK
2062 LOAD_CONST <None>
2063 L: <code for finalbody>
2064 END_FINALLY
2065
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 The special instructions use the block stack. Each block
2067 stack entry contains the instruction that created it (here
2068 SETUP_FINALLY), the level of the value stack at the time the
2069 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 Pushes the current value stack level and the label
2073 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Pops en entry from the block stack, and pops the value
2076 stack until its level is the same as indicated on the
2077 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 Pops a variable number of entries from the *value* stack
2080 and re-raises the exception they specify. The number of
2081 entries popped depends on the (pseudo) exception type.
2082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 The block stack is unwound when an exception is raised:
2084 when a SETUP_FINALLY entry is found, the exception is pushed
2085 onto the value stack (and the exception condition is cleared),
2086 and the interpreter jumps to the label gotten from the block
2087 stack.
2088*/
2089
2090static int
2091compiler_try_finally(struct compiler *c, stmt_ty s)
2092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 basicblock *body, *end;
2094 body = compiler_new_block(c);
2095 end = compiler_new_block(c);
2096 if (body == NULL || end == NULL)
2097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 ADDOP_JREL(c, SETUP_FINALLY, end);
2100 compiler_use_next_block(c, body);
2101 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2102 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002103 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2104 if (!compiler_try_except(c, s))
2105 return 0;
2106 }
2107 else {
2108 VISIT_SEQ(c, stmt, s->v.Try.body);
2109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 ADDOP(c, POP_BLOCK);
2111 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2114 compiler_use_next_block(c, end);
2115 if (!compiler_push_fblock(c, FINALLY_END, end))
2116 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002117 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 ADDOP(c, END_FINALLY);
2119 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122}
2123
2124/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002125 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 (The contents of the value stack is shown in [], with the top
2127 at the right; 'tb' is trace-back info, 'val' the exception's
2128 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129
2130 Value stack Label Instruction Argument
2131 [] SETUP_EXCEPT L1
2132 [] <code for S>
2133 [] POP_BLOCK
2134 [] JUMP_FORWARD L0
2135
2136 [tb, val, exc] L1: DUP )
2137 [tb, val, exc, exc] <evaluate E1> )
2138 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2139 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2140 [tb, val, exc] POP
2141 [tb, val] <assign to V1> (or POP if no V1)
2142 [tb] POP
2143 [] <code for S1>
2144 JUMP_FORWARD L0
2145
2146 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002147 .............................etc.......................
2148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2150
2151 [] L0: <next statement>
2152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 Of course, parts are not generated if Vi or Ei is not present.
2154*/
2155static int
2156compiler_try_except(struct compiler *c, stmt_ty s)
2157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 basicblock *body, *orelse, *except, *end;
2159 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 body = compiler_new_block(c);
2162 except = compiler_new_block(c);
2163 orelse = compiler_new_block(c);
2164 end = compiler_new_block(c);
2165 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2166 return 0;
2167 ADDOP_JREL(c, SETUP_EXCEPT, except);
2168 compiler_use_next_block(c, body);
2169 if (!compiler_push_fblock(c, EXCEPT, body))
2170 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002171 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 ADDOP(c, POP_BLOCK);
2173 compiler_pop_fblock(c, EXCEPT, body);
2174 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002175 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 compiler_use_next_block(c, except);
2177 for (i = 0; i < n; i++) {
2178 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002179 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (!handler->v.ExceptHandler.type && i < n-1)
2181 return compiler_error(c, "default 'except:' must be last");
2182 c->u->u_lineno_set = 0;
2183 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002184 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 except = compiler_new_block(c);
2186 if (except == NULL)
2187 return 0;
2188 if (handler->v.ExceptHandler.type) {
2189 ADDOP(c, DUP_TOP);
2190 VISIT(c, expr, handler->v.ExceptHandler.type);
2191 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2192 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2193 }
2194 ADDOP(c, POP_TOP);
2195 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002196 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002197
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002198 cleanup_end = compiler_new_block(c);
2199 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002200 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002201 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002202
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002203 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2204 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002206 /*
2207 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002208 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002209 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002210 try:
2211 # body
2212 finally:
2213 name = None
2214 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002215 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002217 /* second try: */
2218 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2219 compiler_use_next_block(c, cleanup_body);
2220 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2221 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002223 /* second # body */
2224 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2225 ADDOP(c, POP_BLOCK);
2226 ADDOP(c, POP_EXCEPT);
2227 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002229 /* finally: */
2230 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2231 compiler_use_next_block(c, cleanup_end);
2232 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2233 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002235 /* name = None */
2236 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2237 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002239 /* del name */
2240 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002242 ADDOP(c, END_FINALLY);
2243 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 }
2245 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002246 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002248 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002249 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002250 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251
Guido van Rossumb940e112007-01-10 16:19:56 +00002252 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002253 ADDOP(c, POP_TOP);
2254 compiler_use_next_block(c, cleanup_body);
2255 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2256 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002258 ADDOP(c, POP_EXCEPT);
2259 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 }
2261 ADDOP_JREL(c, JUMP_FORWARD, end);
2262 compiler_use_next_block(c, except);
2263 }
2264 ADDOP(c, END_FINALLY);
2265 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002266 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 compiler_use_next_block(c, end);
2268 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269}
2270
2271static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002272compiler_try(struct compiler *c, stmt_ty s) {
2273 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2274 return compiler_try_finally(c, s);
2275 else
2276 return compiler_try_except(c, s);
2277}
2278
2279
2280static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281compiler_import_as(struct compiler *c, identifier name, identifier asname)
2282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* The IMPORT_NAME opcode was already generated. This function
2284 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 If there is a dot in name, we need to split it and emit a
2287 LOAD_ATTR for each name.
2288 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002289 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2290 PyUnicode_GET_LENGTH(name), 1);
2291 if (dot == -2)
2292 return -1;
2293 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002295 Py_ssize_t pos = dot + 1;
2296 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002298 dot = PyUnicode_FindChar(name, '.', pos,
2299 PyUnicode_GET_LENGTH(name), 1);
2300 if (dot == -2)
2301 return -1;
2302 attr = PyUnicode_Substring(name, pos,
2303 (dot != -1) ? dot :
2304 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 if (!attr)
2306 return -1;
2307 ADDOP_O(c, LOAD_ATTR, attr, names);
2308 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002309 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 }
2311 }
2312 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313}
2314
2315static int
2316compiler_import(struct compiler *c, stmt_ty s)
2317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* The Import node stores a module name like a.b.c as a single
2319 string. This is convenient for all cases except
2320 import a.b.c as d
2321 where we need to parse that string to extract the individual
2322 module names.
2323 XXX Perhaps change the representation to make this case simpler?
2324 */
2325 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 for (i = 0; i < n; i++) {
2328 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2329 int r;
2330 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 level = PyLong_FromLong(0);
2333 if (level == NULL)
2334 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 ADDOP_O(c, LOAD_CONST, level, consts);
2337 Py_DECREF(level);
2338 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2339 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 if (alias->asname) {
2342 r = compiler_import_as(c, alias->name, alias->asname);
2343 if (!r)
2344 return r;
2345 }
2346 else {
2347 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002348 Py_ssize_t dot = PyUnicode_FindChar(
2349 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002350 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002351 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002352 if (tmp == NULL)
2353 return 0;
2354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 Py_DECREF(tmp);
2358 }
2359 if (!r)
2360 return r;
2361 }
2362 }
2363 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364}
2365
2366static int
2367compiler_from_import(struct compiler *c, stmt_ty s)
2368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 PyObject *names = PyTuple_New(n);
2372 PyObject *level;
2373 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 if (!empty_string) {
2376 empty_string = PyUnicode_FromString("");
2377 if (!empty_string)
2378 return 0;
2379 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 if (!names)
2382 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 level = PyLong_FromLong(s->v.ImportFrom.level);
2385 if (!level) {
2386 Py_DECREF(names);
2387 return 0;
2388 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* build up the names */
2391 for (i = 0; i < n; i++) {
2392 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2393 Py_INCREF(alias->name);
2394 PyTuple_SET_ITEM(names, i, alias->name);
2395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2398 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2399 Py_DECREF(level);
2400 Py_DECREF(names);
2401 return compiler_error(c, "from __future__ imports must occur "
2402 "at the beginning of the file");
2403 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 ADDOP_O(c, LOAD_CONST, level, consts);
2406 Py_DECREF(level);
2407 ADDOP_O(c, LOAD_CONST, names, consts);
2408 Py_DECREF(names);
2409 if (s->v.ImportFrom.module) {
2410 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2411 }
2412 else {
2413 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2414 }
2415 for (i = 0; i < n; i++) {
2416 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2417 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002419 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 assert(n == 1);
2421 ADDOP(c, IMPORT_STAR);
2422 return 1;
2423 }
2424
2425 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2426 store_name = alias->name;
2427 if (alias->asname)
2428 store_name = alias->asname;
2429
2430 if (!compiler_nameop(c, store_name, Store)) {
2431 Py_DECREF(names);
2432 return 0;
2433 }
2434 }
2435 /* remove imported module */
2436 ADDOP(c, POP_TOP);
2437 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438}
2439
2440static int
2441compiler_assert(struct compiler *c, stmt_ty s)
2442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 static PyObject *assertion_error = NULL;
2444 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002445 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446
Georg Brandl8334fd92010-12-04 10:26:46 +00002447 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 return 1;
2449 if (assertion_error == NULL) {
2450 assertion_error = PyUnicode_InternFromString("AssertionError");
2451 if (assertion_error == NULL)
2452 return 0;
2453 }
2454 if (s->v.Assert.test->kind == Tuple_kind &&
2455 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002456 msg = PyUnicode_FromString("assertion is always true, "
2457 "perhaps remove parentheses?");
2458 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002460 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2461 c->c_filename, c->u->u_lineno,
2462 NULL, NULL) == -1) {
2463 Py_DECREF(msg);
2464 return 0;
2465 }
2466 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 }
2468 VISIT(c, expr, s->v.Assert.test);
2469 end = compiler_new_block(c);
2470 if (end == NULL)
2471 return 0;
2472 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2473 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2474 if (s->v.Assert.msg) {
2475 VISIT(c, expr, s->v.Assert.msg);
2476 ADDOP_I(c, CALL_FUNCTION, 1);
2477 }
2478 ADDOP_I(c, RAISE_VARARGS, 1);
2479 compiler_use_next_block(c, end);
2480 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481}
2482
2483static int
2484compiler_visit_stmt(struct compiler *c, stmt_ty s)
2485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 /* Always assign a lineno to the next instruction for a stmt. */
2489 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002490 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 switch (s->kind) {
2494 case FunctionDef_kind:
2495 return compiler_function(c, s);
2496 case ClassDef_kind:
2497 return compiler_class(c, s);
2498 case Return_kind:
2499 if (c->u->u_ste->ste_type != FunctionBlock)
2500 return compiler_error(c, "'return' outside function");
2501 if (s->v.Return.value) {
2502 VISIT(c, expr, s->v.Return.value);
2503 }
2504 else
2505 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2506 ADDOP(c, RETURN_VALUE);
2507 break;
2508 case Delete_kind:
2509 VISIT_SEQ(c, expr, s->v.Delete.targets)
2510 break;
2511 case Assign_kind:
2512 n = asdl_seq_LEN(s->v.Assign.targets);
2513 VISIT(c, expr, s->v.Assign.value);
2514 for (i = 0; i < n; i++) {
2515 if (i < n - 1)
2516 ADDOP(c, DUP_TOP);
2517 VISIT(c, expr,
2518 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2519 }
2520 break;
2521 case AugAssign_kind:
2522 return compiler_augassign(c, s);
2523 case For_kind:
2524 return compiler_for(c, s);
2525 case While_kind:
2526 return compiler_while(c, s);
2527 case If_kind:
2528 return compiler_if(c, s);
2529 case Raise_kind:
2530 n = 0;
2531 if (s->v.Raise.exc) {
2532 VISIT(c, expr, s->v.Raise.exc);
2533 n++;
2534 if (s->v.Raise.cause) {
2535 VISIT(c, expr, s->v.Raise.cause);
2536 n++;
2537 }
2538 }
2539 ADDOP_I(c, RAISE_VARARGS, n);
2540 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002541 case Try_kind:
2542 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 case Assert_kind:
2544 return compiler_assert(c, s);
2545 case Import_kind:
2546 return compiler_import(c, s);
2547 case ImportFrom_kind:
2548 return compiler_from_import(c, s);
2549 case Global_kind:
2550 case Nonlocal_kind:
2551 break;
2552 case Expr_kind:
2553 if (c->c_interactive && c->c_nestlevel <= 1) {
2554 VISIT(c, expr, s->v.Expr.value);
2555 ADDOP(c, PRINT_EXPR);
2556 }
2557 else if (s->v.Expr.value->kind != Str_kind &&
2558 s->v.Expr.value->kind != Num_kind) {
2559 VISIT(c, expr, s->v.Expr.value);
2560 ADDOP(c, POP_TOP);
2561 }
2562 break;
2563 case Pass_kind:
2564 break;
2565 case Break_kind:
2566 if (!compiler_in_loop(c))
2567 return compiler_error(c, "'break' outside loop");
2568 ADDOP(c, BREAK_LOOP);
2569 break;
2570 case Continue_kind:
2571 return compiler_continue(c);
2572 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002573 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 }
2575 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576}
2577
2578static int
2579unaryop(unaryop_ty op)
2580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 switch (op) {
2582 case Invert:
2583 return UNARY_INVERT;
2584 case Not:
2585 return UNARY_NOT;
2586 case UAdd:
2587 return UNARY_POSITIVE;
2588 case USub:
2589 return UNARY_NEGATIVE;
2590 default:
2591 PyErr_Format(PyExc_SystemError,
2592 "unary op %d should not be possible", op);
2593 return 0;
2594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595}
2596
2597static int
2598binop(struct compiler *c, operator_ty op)
2599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 switch (op) {
2601 case Add:
2602 return BINARY_ADD;
2603 case Sub:
2604 return BINARY_SUBTRACT;
2605 case Mult:
2606 return BINARY_MULTIPLY;
2607 case Div:
2608 return BINARY_TRUE_DIVIDE;
2609 case Mod:
2610 return BINARY_MODULO;
2611 case Pow:
2612 return BINARY_POWER;
2613 case LShift:
2614 return BINARY_LSHIFT;
2615 case RShift:
2616 return BINARY_RSHIFT;
2617 case BitOr:
2618 return BINARY_OR;
2619 case BitXor:
2620 return BINARY_XOR;
2621 case BitAnd:
2622 return BINARY_AND;
2623 case FloorDiv:
2624 return BINARY_FLOOR_DIVIDE;
2625 default:
2626 PyErr_Format(PyExc_SystemError,
2627 "binary op %d should not be possible", op);
2628 return 0;
2629 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630}
2631
2632static int
2633cmpop(cmpop_ty op)
2634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 switch (op) {
2636 case Eq:
2637 return PyCmp_EQ;
2638 case NotEq:
2639 return PyCmp_NE;
2640 case Lt:
2641 return PyCmp_LT;
2642 case LtE:
2643 return PyCmp_LE;
2644 case Gt:
2645 return PyCmp_GT;
2646 case GtE:
2647 return PyCmp_GE;
2648 case Is:
2649 return PyCmp_IS;
2650 case IsNot:
2651 return PyCmp_IS_NOT;
2652 case In:
2653 return PyCmp_IN;
2654 case NotIn:
2655 return PyCmp_NOT_IN;
2656 default:
2657 return PyCmp_BAD;
2658 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659}
2660
2661static int
2662inplace_binop(struct compiler *c, operator_ty op)
2663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 switch (op) {
2665 case Add:
2666 return INPLACE_ADD;
2667 case Sub:
2668 return INPLACE_SUBTRACT;
2669 case Mult:
2670 return INPLACE_MULTIPLY;
2671 case Div:
2672 return INPLACE_TRUE_DIVIDE;
2673 case Mod:
2674 return INPLACE_MODULO;
2675 case Pow:
2676 return INPLACE_POWER;
2677 case LShift:
2678 return INPLACE_LSHIFT;
2679 case RShift:
2680 return INPLACE_RSHIFT;
2681 case BitOr:
2682 return INPLACE_OR;
2683 case BitXor:
2684 return INPLACE_XOR;
2685 case BitAnd:
2686 return INPLACE_AND;
2687 case FloorDiv:
2688 return INPLACE_FLOOR_DIVIDE;
2689 default:
2690 PyErr_Format(PyExc_SystemError,
2691 "inplace binary op %d should not be possible", op);
2692 return 0;
2693 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694}
2695
2696static int
2697compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 int op, scope, arg;
2700 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 PyObject *dict = c->u->u_names;
2703 PyObject *mangled;
2704 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 mangled = _Py_Mangle(c->u->u_private, name);
2707 if (!mangled)
2708 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002709
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002710 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2711 PyUnicode_CompareWithASCIIString(name, "True") &&
2712 PyUnicode_CompareWithASCIIString(name, "False"));
2713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 op = 0;
2715 optype = OP_NAME;
2716 scope = PyST_GetScope(c->u->u_ste, mangled);
2717 switch (scope) {
2718 case FREE:
2719 dict = c->u->u_freevars;
2720 optype = OP_DEREF;
2721 break;
2722 case CELL:
2723 dict = c->u->u_cellvars;
2724 optype = OP_DEREF;
2725 break;
2726 case LOCAL:
2727 if (c->u->u_ste->ste_type == FunctionBlock)
2728 optype = OP_FAST;
2729 break;
2730 case GLOBAL_IMPLICIT:
2731 if (c->u->u_ste->ste_type == FunctionBlock &&
2732 !c->u->u_ste->ste_unoptimized)
2733 optype = OP_GLOBAL;
2734 break;
2735 case GLOBAL_EXPLICIT:
2736 optype = OP_GLOBAL;
2737 break;
2738 default:
2739 /* scope can be 0 */
2740 break;
2741 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002744 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 switch (optype) {
2747 case OP_DEREF:
2748 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002749 case Load:
2750 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2751 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 case Store: op = STORE_DEREF; break;
2753 case AugLoad:
2754 case AugStore:
2755 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002756 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 case Param:
2758 default:
2759 PyErr_SetString(PyExc_SystemError,
2760 "param invalid for deref variable");
2761 return 0;
2762 }
2763 break;
2764 case OP_FAST:
2765 switch (ctx) {
2766 case Load: op = LOAD_FAST; break;
2767 case Store: op = STORE_FAST; break;
2768 case Del: op = DELETE_FAST; break;
2769 case AugLoad:
2770 case AugStore:
2771 break;
2772 case Param:
2773 default:
2774 PyErr_SetString(PyExc_SystemError,
2775 "param invalid for local variable");
2776 return 0;
2777 }
2778 ADDOP_O(c, op, mangled, varnames);
2779 Py_DECREF(mangled);
2780 return 1;
2781 case OP_GLOBAL:
2782 switch (ctx) {
2783 case Load: op = LOAD_GLOBAL; break;
2784 case Store: op = STORE_GLOBAL; break;
2785 case Del: op = DELETE_GLOBAL; break;
2786 case AugLoad:
2787 case AugStore:
2788 break;
2789 case Param:
2790 default:
2791 PyErr_SetString(PyExc_SystemError,
2792 "param invalid for global variable");
2793 return 0;
2794 }
2795 break;
2796 case OP_NAME:
2797 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002798 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 case Store: op = STORE_NAME; break;
2800 case Del: op = DELETE_NAME; break;
2801 case AugLoad:
2802 case AugStore:
2803 break;
2804 case Param:
2805 default:
2806 PyErr_SetString(PyExc_SystemError,
2807 "param invalid for name variable");
2808 return 0;
2809 }
2810 break;
2811 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 assert(op);
2814 arg = compiler_add_o(c, dict, mangled);
2815 Py_DECREF(mangled);
2816 if (arg < 0)
2817 return 0;
2818 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819}
2820
2821static int
2822compiler_boolop(struct compiler *c, expr_ty e)
2823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 basicblock *end;
2825 int jumpi, i, n;
2826 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 assert(e->kind == BoolOp_kind);
2829 if (e->v.BoolOp.op == And)
2830 jumpi = JUMP_IF_FALSE_OR_POP;
2831 else
2832 jumpi = JUMP_IF_TRUE_OR_POP;
2833 end = compiler_new_block(c);
2834 if (end == NULL)
2835 return 0;
2836 s = e->v.BoolOp.values;
2837 n = asdl_seq_LEN(s) - 1;
2838 assert(n >= 0);
2839 for (i = 0; i < n; ++i) {
2840 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2841 ADDOP_JABS(c, jumpi, end);
2842 }
2843 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2844 compiler_use_next_block(c, end);
2845 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846}
2847
2848static int
2849compiler_list(struct compiler *c, expr_ty e)
2850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 int n = asdl_seq_LEN(e->v.List.elts);
2852 if (e->v.List.ctx == Store) {
2853 int i, seen_star = 0;
2854 for (i = 0; i < n; i++) {
2855 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2856 if (elt->kind == Starred_kind && !seen_star) {
2857 if ((i >= (1 << 8)) ||
2858 (n-i-1 >= (INT_MAX >> 8)))
2859 return compiler_error(c,
2860 "too many expressions in "
2861 "star-unpacking assignment");
2862 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2863 seen_star = 1;
2864 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2865 } else if (elt->kind == Starred_kind) {
2866 return compiler_error(c,
2867 "two starred expressions in assignment");
2868 }
2869 }
2870 if (!seen_star) {
2871 ADDOP_I(c, UNPACK_SEQUENCE, n);
2872 }
2873 }
2874 VISIT_SEQ(c, expr, e->v.List.elts);
2875 if (e->v.List.ctx == Load) {
2876 ADDOP_I(c, BUILD_LIST, n);
2877 }
2878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879}
2880
2881static int
2882compiler_tuple(struct compiler *c, expr_ty e)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 int n = asdl_seq_LEN(e->v.Tuple.elts);
2885 if (e->v.Tuple.ctx == Store) {
2886 int i, seen_star = 0;
2887 for (i = 0; i < n; i++) {
2888 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2889 if (elt->kind == Starred_kind && !seen_star) {
2890 if ((i >= (1 << 8)) ||
2891 (n-i-1 >= (INT_MAX >> 8)))
2892 return compiler_error(c,
2893 "too many expressions in "
2894 "star-unpacking assignment");
2895 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2896 seen_star = 1;
2897 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2898 } else if (elt->kind == Starred_kind) {
2899 return compiler_error(c,
2900 "two starred expressions in assignment");
2901 }
2902 }
2903 if (!seen_star) {
2904 ADDOP_I(c, UNPACK_SEQUENCE, n);
2905 }
2906 }
2907 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2908 if (e->v.Tuple.ctx == Load) {
2909 ADDOP_I(c, BUILD_TUPLE, n);
2910 }
2911 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912}
2913
2914static int
2915compiler_compare(struct compiler *c, expr_ty e)
2916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 int i, n;
2918 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2921 VISIT(c, expr, e->v.Compare.left);
2922 n = asdl_seq_LEN(e->v.Compare.ops);
2923 assert(n > 0);
2924 if (n > 1) {
2925 cleanup = compiler_new_block(c);
2926 if (cleanup == NULL)
2927 return 0;
2928 VISIT(c, expr,
2929 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2930 }
2931 for (i = 1; i < n; i++) {
2932 ADDOP(c, DUP_TOP);
2933 ADDOP(c, ROT_THREE);
2934 ADDOP_I(c, COMPARE_OP,
2935 cmpop((cmpop_ty)(asdl_seq_GET(
2936 e->v.Compare.ops, i - 1))));
2937 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2938 NEXT_BLOCK(c);
2939 if (i < (n - 1))
2940 VISIT(c, expr,
2941 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2942 }
2943 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2944 ADDOP_I(c, COMPARE_OP,
2945 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2946 if (n > 1) {
2947 basicblock *end = compiler_new_block(c);
2948 if (end == NULL)
2949 return 0;
2950 ADDOP_JREL(c, JUMP_FORWARD, end);
2951 compiler_use_next_block(c, cleanup);
2952 ADDOP(c, ROT_TWO);
2953 ADDOP(c, POP_TOP);
2954 compiler_use_next_block(c, end);
2955 }
2956 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957}
2958
2959static int
2960compiler_call(struct compiler *c, expr_ty e)
2961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 VISIT(c, expr, e->v.Call.func);
2963 return compiler_call_helper(c, 0,
2964 e->v.Call.args,
2965 e->v.Call.keywords,
2966 e->v.Call.starargs,
2967 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002968}
2969
2970/* shared code between compiler_call and compiler_class */
2971static int
2972compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 int n, /* Args already pushed */
2974 asdl_seq *args,
2975 asdl_seq *keywords,
2976 expr_ty starargs,
2977 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 n += asdl_seq_LEN(args);
2982 VISIT_SEQ(c, expr, args);
2983 if (keywords) {
2984 VISIT_SEQ(c, keyword, keywords);
2985 n |= asdl_seq_LEN(keywords) << 8;
2986 }
2987 if (starargs) {
2988 VISIT(c, expr, starargs);
2989 code |= 1;
2990 }
2991 if (kwargs) {
2992 VISIT(c, expr, kwargs);
2993 code |= 2;
2994 }
2995 switch (code) {
2996 case 0:
2997 ADDOP_I(c, CALL_FUNCTION, n);
2998 break;
2999 case 1:
3000 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3001 break;
3002 case 2:
3003 ADDOP_I(c, CALL_FUNCTION_KW, n);
3004 break;
3005 case 3:
3006 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3007 break;
3008 }
3009 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010}
3011
Nick Coghlan650f0d02007-04-15 12:05:43 +00003012
3013/* List and set comprehensions and generator expressions work by creating a
3014 nested function to perform the actual iteration. This means that the
3015 iteration variables don't leak into the current scope.
3016 The defined function is called immediately following its definition, with the
3017 result of that call being the result of the expression.
3018 The LC/SC version returns the populated container, while the GE version is
3019 flagged in symtable.c as a generator, so it returns the generator object
3020 when the function is called.
3021 This code *knows* that the loop cannot contain break, continue, or return,
3022 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3023
3024 Possible cleanups:
3025 - iterate over the generator sequence instead of using recursion
3026*/
3027
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029compiler_comprehension_generator(struct compiler *c,
3030 asdl_seq *generators, int gen_index,
3031 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 /* generate code for the iterator, then each of the ifs,
3034 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 comprehension_ty gen;
3037 basicblock *start, *anchor, *skip, *if_cleanup;
3038 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 start = compiler_new_block(c);
3041 skip = compiler_new_block(c);
3042 if_cleanup = compiler_new_block(c);
3043 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3046 anchor == NULL)
3047 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (gen_index == 0) {
3052 /* Receive outermost iter as an implicit argument */
3053 c->u->u_argcount = 1;
3054 ADDOP_I(c, LOAD_FAST, 0);
3055 }
3056 else {
3057 /* Sub-iter - calculate on the fly */
3058 VISIT(c, expr, gen->iter);
3059 ADDOP(c, GET_ITER);
3060 }
3061 compiler_use_next_block(c, start);
3062 ADDOP_JREL(c, FOR_ITER, anchor);
3063 NEXT_BLOCK(c);
3064 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 /* XXX this needs to be cleaned up...a lot! */
3067 n = asdl_seq_LEN(gen->ifs);
3068 for (i = 0; i < n; i++) {
3069 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3070 VISIT(c, expr, e);
3071 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3072 NEXT_BLOCK(c);
3073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 if (++gen_index < asdl_seq_LEN(generators))
3076 if (!compiler_comprehension_generator(c,
3077 generators, gen_index,
3078 elt, val, type))
3079 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 /* only append after the last for generator */
3082 if (gen_index >= asdl_seq_LEN(generators)) {
3083 /* comprehension specific code */
3084 switch (type) {
3085 case COMP_GENEXP:
3086 VISIT(c, expr, elt);
3087 ADDOP(c, YIELD_VALUE);
3088 ADDOP(c, POP_TOP);
3089 break;
3090 case COMP_LISTCOMP:
3091 VISIT(c, expr, elt);
3092 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3093 break;
3094 case COMP_SETCOMP:
3095 VISIT(c, expr, elt);
3096 ADDOP_I(c, SET_ADD, gen_index + 1);
3097 break;
3098 case COMP_DICTCOMP:
3099 /* With 'd[k] = v', v is evaluated before k, so we do
3100 the same. */
3101 VISIT(c, expr, val);
3102 VISIT(c, expr, elt);
3103 ADDOP_I(c, MAP_ADD, gen_index + 1);
3104 break;
3105 default:
3106 return 0;
3107 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 compiler_use_next_block(c, skip);
3110 }
3111 compiler_use_next_block(c, if_cleanup);
3112 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3113 compiler_use_next_block(c, anchor);
3114
3115 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003116}
3117
3118static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003119compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 PyCodeObject *co = NULL;
3123 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003124 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 outermost_iter = ((comprehension_ty)
3127 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003128
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003129 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3130 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 if (type != COMP_GENEXP) {
3134 int op;
3135 switch (type) {
3136 case COMP_LISTCOMP:
3137 op = BUILD_LIST;
3138 break;
3139 case COMP_SETCOMP:
3140 op = BUILD_SET;
3141 break;
3142 case COMP_DICTCOMP:
3143 op = BUILD_MAP;
3144 break;
3145 default:
3146 PyErr_Format(PyExc_SystemError,
3147 "unknown comprehension type %d", type);
3148 goto error_in_scope;
3149 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 ADDOP_I(c, op, 0);
3152 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 if (!compiler_comprehension_generator(c, generators, 0, elt,
3155 val, type))
3156 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 if (type != COMP_GENEXP) {
3159 ADDOP(c, RETURN_VALUE);
3160 }
3161
3162 co = assemble(c, 1);
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04003163 qualname = compiler_scope_qualname(c, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003165 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 goto error;
3167
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003168 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003170 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 Py_DECREF(co);
3172
3173 VISIT(c, expr, outermost_iter);
3174 ADDOP(c, GET_ITER);
3175 ADDOP_I(c, CALL_FUNCTION, 1);
3176 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003177error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003179error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003180 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 Py_XDECREF(co);
3182 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003183}
3184
3185static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186compiler_genexp(struct compiler *c, expr_ty e)
3187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 static identifier name;
3189 if (!name) {
3190 name = PyUnicode_FromString("<genexpr>");
3191 if (!name)
3192 return 0;
3193 }
3194 assert(e->kind == GeneratorExp_kind);
3195 return compiler_comprehension(c, e, COMP_GENEXP, name,
3196 e->v.GeneratorExp.generators,
3197 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198}
3199
3200static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003201compiler_listcomp(struct compiler *c, expr_ty e)
3202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 static identifier name;
3204 if (!name) {
3205 name = PyUnicode_FromString("<listcomp>");
3206 if (!name)
3207 return 0;
3208 }
3209 assert(e->kind == ListComp_kind);
3210 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3211 e->v.ListComp.generators,
3212 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003213}
3214
3215static int
3216compiler_setcomp(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("<setcomp>");
3221 if (!name)
3222 return 0;
3223 }
3224 assert(e->kind == SetComp_kind);
3225 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3226 e->v.SetComp.generators,
3227 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003228}
3229
3230
3231static int
3232compiler_dictcomp(struct compiler *c, expr_ty e)
3233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 static identifier name;
3235 if (!name) {
3236 name = PyUnicode_FromString("<dictcomp>");
3237 if (!name)
3238 return 0;
3239 }
3240 assert(e->kind == DictComp_kind);
3241 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3242 e->v.DictComp.generators,
3243 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003244}
3245
3246
3247static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248compiler_visit_keyword(struct compiler *c, keyword_ty k)
3249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3251 VISIT(c, expr, k->value);
3252 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253}
3254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256 whether they are true or false.
3257
3258 Return values: 1 for true, 0 for false, -1 for non-constant.
3259 */
3260
3261static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003262expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 char *id;
3265 switch (e->kind) {
3266 case Ellipsis_kind:
3267 return 1;
3268 case Num_kind:
3269 return PyObject_IsTrue(e->v.Num.n);
3270 case Str_kind:
3271 return PyObject_IsTrue(e->v.Str.s);
3272 case Name_kind:
3273 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003274 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003275 if (id && strcmp(id, "__debug__") == 0)
3276 return !c->c_optimize;
3277 return -1;
3278 case NameConstant_kind: {
3279 PyObject *o = e->v.NameConstant.value;
3280 if (o == Py_None)
3281 return 0;
3282 else if (o == Py_True)
3283 return 1;
3284 else if (o == Py_False)
3285 return 0;
3286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 default:
3288 return -1;
3289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290}
3291
Guido van Rossumc2e20742006-02-27 22:32:47 +00003292/*
3293 Implements the with statement from PEP 343.
3294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003296
3297 with EXPR as VAR:
3298 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299
Guido van Rossumc2e20742006-02-27 22:32:47 +00003300 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301
Thomas Wouters477c8d52006-05-27 19:21:47 +00003302 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003303 exit = context.__exit__ # not calling it
3304 value = context.__enter__()
3305 try:
3306 VAR = value # if VAR present in the syntax
3307 BLOCK
3308 finally:
3309 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003311 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003313 exit(*exc)
3314 */
3315static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003316compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003317{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003318 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003319 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003320
3321 assert(s->kind == With_kind);
3322
Guido van Rossumc2e20742006-02-27 22:32:47 +00003323 block = compiler_new_block(c);
3324 finally = compiler_new_block(c);
3325 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003326 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003327
Thomas Wouters477c8d52006-05-27 19:21:47 +00003328 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003329 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003330 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003331
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003332 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003333 compiler_use_next_block(c, block);
3334 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003335 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003336 }
3337
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003338 if (item->optional_vars) {
3339 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003340 }
3341 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003343 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003344 }
3345
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003346 pos++;
3347 if (pos == asdl_seq_LEN(s->v.With.items))
3348 /* BLOCK code */
3349 VISIT_SEQ(c, stmt, s->v.With.body)
3350 else if (!compiler_with(c, s, pos))
3351 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003352
3353 /* End of try block; start the finally block */
3354 ADDOP(c, POP_BLOCK);
3355 compiler_pop_fblock(c, FINALLY_TRY, block);
3356
3357 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3358 compiler_use_next_block(c, finally);
3359 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003360 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003361
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003362 /* Finally block starts; context.__exit__ is on the stack under
3363 the exception or return information. Just issue our magic
3364 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003365 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003366
3367 /* Finally block ends. */
3368 ADDOP(c, END_FINALLY);
3369 compiler_pop_fblock(c, FINALLY_END, finally);
3370 return 1;
3371}
3372
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003373static int
3374compiler_visit_expr(struct compiler *c, expr_ty e)
3375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 /* If expr e has a different line number than the last expr/stmt,
3379 set a new line number for the next instruction.
3380 */
3381 if (e->lineno > c->u->u_lineno) {
3382 c->u->u_lineno = e->lineno;
3383 c->u->u_lineno_set = 0;
3384 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003385 /* Updating the column offset is always harmless. */
3386 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 switch (e->kind) {
3388 case BoolOp_kind:
3389 return compiler_boolop(c, e);
3390 case BinOp_kind:
3391 VISIT(c, expr, e->v.BinOp.left);
3392 VISIT(c, expr, e->v.BinOp.right);
3393 ADDOP(c, binop(c, e->v.BinOp.op));
3394 break;
3395 case UnaryOp_kind:
3396 VISIT(c, expr, e->v.UnaryOp.operand);
3397 ADDOP(c, unaryop(e->v.UnaryOp.op));
3398 break;
3399 case Lambda_kind:
3400 return compiler_lambda(c, e);
3401 case IfExp_kind:
3402 return compiler_ifexp(c, e);
3403 case Dict_kind:
3404 n = asdl_seq_LEN(e->v.Dict.values);
3405 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3406 for (i = 0; i < n; i++) {
3407 VISIT(c, expr,
3408 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3409 VISIT(c, expr,
3410 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3411 ADDOP(c, STORE_MAP);
3412 }
3413 break;
3414 case Set_kind:
3415 n = asdl_seq_LEN(e->v.Set.elts);
3416 VISIT_SEQ(c, expr, e->v.Set.elts);
3417 ADDOP_I(c, BUILD_SET, n);
3418 break;
3419 case GeneratorExp_kind:
3420 return compiler_genexp(c, e);
3421 case ListComp_kind:
3422 return compiler_listcomp(c, e);
3423 case SetComp_kind:
3424 return compiler_setcomp(c, e);
3425 case DictComp_kind:
3426 return compiler_dictcomp(c, e);
3427 case Yield_kind:
3428 if (c->u->u_ste->ste_type != FunctionBlock)
3429 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003430 if (e->v.Yield.value) {
3431 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 }
3433 else {
3434 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3435 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003436 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003438 case YieldFrom_kind:
3439 if (c->u->u_ste->ste_type != FunctionBlock)
3440 return compiler_error(c, "'yield' outside function");
3441 VISIT(c, expr, e->v.YieldFrom.value);
3442 ADDOP(c, GET_ITER);
3443 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3444 ADDOP(c, YIELD_FROM);
3445 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 case Compare_kind:
3447 return compiler_compare(c, e);
3448 case Call_kind:
3449 return compiler_call(c, e);
3450 case Num_kind:
3451 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3452 break;
3453 case Str_kind:
3454 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3455 break;
3456 case Bytes_kind:
3457 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3458 break;
3459 case Ellipsis_kind:
3460 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3461 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003462 case NameConstant_kind:
3463 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3464 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 /* The following exprs can be assignment targets. */
3466 case Attribute_kind:
3467 if (e->v.Attribute.ctx != AugStore)
3468 VISIT(c, expr, e->v.Attribute.value);
3469 switch (e->v.Attribute.ctx) {
3470 case AugLoad:
3471 ADDOP(c, DUP_TOP);
3472 /* Fall through to load */
3473 case Load:
3474 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3475 break;
3476 case AugStore:
3477 ADDOP(c, ROT_TWO);
3478 /* Fall through to save */
3479 case Store:
3480 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3481 break;
3482 case Del:
3483 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3484 break;
3485 case Param:
3486 default:
3487 PyErr_SetString(PyExc_SystemError,
3488 "param invalid in attribute expression");
3489 return 0;
3490 }
3491 break;
3492 case Subscript_kind:
3493 switch (e->v.Subscript.ctx) {
3494 case AugLoad:
3495 VISIT(c, expr, e->v.Subscript.value);
3496 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3497 break;
3498 case Load:
3499 VISIT(c, expr, e->v.Subscript.value);
3500 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3501 break;
3502 case AugStore:
3503 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3504 break;
3505 case Store:
3506 VISIT(c, expr, e->v.Subscript.value);
3507 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3508 break;
3509 case Del:
3510 VISIT(c, expr, e->v.Subscript.value);
3511 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3512 break;
3513 case Param:
3514 default:
3515 PyErr_SetString(PyExc_SystemError,
3516 "param invalid in subscript expression");
3517 return 0;
3518 }
3519 break;
3520 case Starred_kind:
3521 switch (e->v.Starred.ctx) {
3522 case Store:
3523 /* In all legitimate cases, the Starred node was already replaced
3524 * by compiler_list/compiler_tuple. XXX: is that okay? */
3525 return compiler_error(c,
3526 "starred assignment target must be in a list or tuple");
3527 default:
3528 return compiler_error(c,
3529 "can use starred expression only as assignment target");
3530 }
3531 break;
3532 case Name_kind:
3533 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3534 /* child nodes of List and Tuple will have expr_context set */
3535 case List_kind:
3536 return compiler_list(c, e);
3537 case Tuple_kind:
3538 return compiler_tuple(c, e);
3539 }
3540 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541}
3542
3543static int
3544compiler_augassign(struct compiler *c, stmt_ty s)
3545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 expr_ty e = s->v.AugAssign.target;
3547 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 switch (e->kind) {
3552 case Attribute_kind:
3553 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3554 AugLoad, e->lineno, e->col_offset, c->c_arena);
3555 if (auge == NULL)
3556 return 0;
3557 VISIT(c, expr, auge);
3558 VISIT(c, expr, s->v.AugAssign.value);
3559 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3560 auge->v.Attribute.ctx = AugStore;
3561 VISIT(c, expr, auge);
3562 break;
3563 case Subscript_kind:
3564 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3565 AugLoad, e->lineno, e->col_offset, c->c_arena);
3566 if (auge == NULL)
3567 return 0;
3568 VISIT(c, expr, auge);
3569 VISIT(c, expr, s->v.AugAssign.value);
3570 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3571 auge->v.Subscript.ctx = AugStore;
3572 VISIT(c, expr, auge);
3573 break;
3574 case Name_kind:
3575 if (!compiler_nameop(c, e->v.Name.id, Load))
3576 return 0;
3577 VISIT(c, expr, s->v.AugAssign.value);
3578 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3579 return compiler_nameop(c, e->v.Name.id, Store);
3580 default:
3581 PyErr_Format(PyExc_SystemError,
3582 "invalid node type (%d) for augmented assignment",
3583 e->kind);
3584 return 0;
3585 }
3586 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587}
3588
3589static int
3590compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 struct fblockinfo *f;
3593 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3594 PyErr_SetString(PyExc_SystemError,
3595 "too many statically nested blocks");
3596 return 0;
3597 }
3598 f = &c->u->u_fblock[c->u->u_nfblocks++];
3599 f->fb_type = t;
3600 f->fb_block = b;
3601 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602}
3603
3604static void
3605compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 struct compiler_unit *u = c->u;
3608 assert(u->u_nfblocks > 0);
3609 u->u_nfblocks--;
3610 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3611 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612}
3613
Thomas Wouters89f507f2006-12-13 04:49:30 +00003614static int
3615compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 int i;
3617 struct compiler_unit *u = c->u;
3618 for (i = 0; i < u->u_nfblocks; ++i) {
3619 if (u->u_fblock[i].fb_type == LOOP)
3620 return 1;
3621 }
3622 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003623}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624/* Raises a SyntaxError and returns 0.
3625 If something goes wrong, a different exception may be raised.
3626*/
3627
3628static int
3629compiler_error(struct compiler *c, const char *errstr)
3630{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003631 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633
Victor Stinner14e461d2013-08-26 22:28:21 +02003634 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 if (!loc) {
3636 Py_INCREF(Py_None);
3637 loc = Py_None;
3638 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003639 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003640 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 if (!u)
3642 goto exit;
3643 v = Py_BuildValue("(zO)", errstr, u);
3644 if (!v)
3645 goto exit;
3646 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 Py_DECREF(loc);
3649 Py_XDECREF(u);
3650 Py_XDECREF(v);
3651 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652}
3653
3654static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655compiler_handle_subscr(struct compiler *c, const char *kind,
3656 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 /* XXX this code is duplicated */
3661 switch (ctx) {
3662 case AugLoad: /* fall through to Load */
3663 case Load: op = BINARY_SUBSCR; break;
3664 case AugStore:/* fall through to Store */
3665 case Store: op = STORE_SUBSCR; break;
3666 case Del: op = DELETE_SUBSCR; break;
3667 case Param:
3668 PyErr_Format(PyExc_SystemError,
3669 "invalid %s kind %d in subscript\n",
3670 kind, ctx);
3671 return 0;
3672 }
3673 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003674 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 }
3676 else if (ctx == AugStore) {
3677 ADDOP(c, ROT_THREE);
3678 }
3679 ADDOP(c, op);
3680 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681}
3682
3683static int
3684compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 int n = 2;
3687 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 /* only handles the cases where BUILD_SLICE is emitted */
3690 if (s->v.Slice.lower) {
3691 VISIT(c, expr, s->v.Slice.lower);
3692 }
3693 else {
3694 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 if (s->v.Slice.upper) {
3698 VISIT(c, expr, s->v.Slice.upper);
3699 }
3700 else {
3701 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3702 }
3703
3704 if (s->v.Slice.step) {
3705 n++;
3706 VISIT(c, expr, s->v.Slice.step);
3707 }
3708 ADDOP_I(c, BUILD_SLICE, n);
3709 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710}
3711
3712static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3714 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 switch (s->kind) {
3717 case Slice_kind:
3718 return compiler_slice(c, s, ctx);
3719 case Index_kind:
3720 VISIT(c, expr, s->v.Index.value);
3721 break;
3722 case ExtSlice_kind:
3723 default:
3724 PyErr_SetString(PyExc_SystemError,
3725 "extended slice invalid in nested slice");
3726 return 0;
3727 }
3728 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729}
3730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731static int
3732compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 char * kindname = NULL;
3735 switch (s->kind) {
3736 case Index_kind:
3737 kindname = "index";
3738 if (ctx != AugStore) {
3739 VISIT(c, expr, s->v.Index.value);
3740 }
3741 break;
3742 case Slice_kind:
3743 kindname = "slice";
3744 if (ctx != AugStore) {
3745 if (!compiler_slice(c, s, ctx))
3746 return 0;
3747 }
3748 break;
3749 case ExtSlice_kind:
3750 kindname = "extended slice";
3751 if (ctx != AugStore) {
3752 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3753 for (i = 0; i < n; i++) {
3754 slice_ty sub = (slice_ty)asdl_seq_GET(
3755 s->v.ExtSlice.dims, i);
3756 if (!compiler_visit_nested_slice(c, sub, ctx))
3757 return 0;
3758 }
3759 ADDOP_I(c, BUILD_TUPLE, n);
3760 }
3761 break;
3762 default:
3763 PyErr_Format(PyExc_SystemError,
3764 "invalid subscript kind %d", s->kind);
3765 return 0;
3766 }
3767 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768}
3769
Thomas Wouters89f507f2006-12-13 04:49:30 +00003770/* End of the compiler section, beginning of the assembler section */
3771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772/* do depth-first search of basic block graph, starting with block.
3773 post records the block indices in post-order.
3774
3775 XXX must handle implicit jumps from one block to next
3776*/
3777
Thomas Wouters89f507f2006-12-13 04:49:30 +00003778struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 PyObject *a_bytecode; /* string containing bytecode */
3780 int a_offset; /* offset into bytecode */
3781 int a_nblocks; /* number of reachable blocks */
3782 basicblock **a_postorder; /* list of blocks in dfs postorder */
3783 PyObject *a_lnotab; /* string containing lnotab */
3784 int a_lnotab_off; /* offset into lnotab */
3785 int a_lineno; /* last lineno of emitted instruction */
3786 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003787};
3788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789static void
3790dfs(struct compiler *c, basicblock *b, struct assembler *a)
3791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 int i;
3793 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 if (b->b_seen)
3796 return;
3797 b->b_seen = 1;
3798 if (b->b_next != NULL)
3799 dfs(c, b->b_next, a);
3800 for (i = 0; i < b->b_iused; i++) {
3801 instr = &b->b_instr[i];
3802 if (instr->i_jrel || instr->i_jabs)
3803 dfs(c, instr->i_target, a);
3804 }
3805 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806}
3807
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003808static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 int i, target_depth;
3812 struct instr *instr;
3813 if (b->b_seen || b->b_startdepth >= depth)
3814 return maxdepth;
3815 b->b_seen = 1;
3816 b->b_startdepth = depth;
3817 for (i = 0; i < b->b_iused; i++) {
3818 instr = &b->b_instr[i];
3819 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3820 if (depth > maxdepth)
3821 maxdepth = depth;
3822 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3823 if (instr->i_jrel || instr->i_jabs) {
3824 target_depth = depth;
3825 if (instr->i_opcode == FOR_ITER) {
3826 target_depth = depth-2;
3827 } else if (instr->i_opcode == SETUP_FINALLY ||
3828 instr->i_opcode == SETUP_EXCEPT) {
3829 target_depth = depth+3;
3830 if (target_depth > maxdepth)
3831 maxdepth = target_depth;
3832 }
3833 maxdepth = stackdepth_walk(c, instr->i_target,
3834 target_depth, maxdepth);
3835 if (instr->i_opcode == JUMP_ABSOLUTE ||
3836 instr->i_opcode == JUMP_FORWARD) {
3837 goto out; /* remaining code is dead */
3838 }
3839 }
3840 }
3841 if (b->b_next)
3842 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 b->b_seen = 0;
3845 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846}
3847
3848/* Find the flow path that needs the largest stack. We assume that
3849 * cycles in the flow graph have no net effect on the stack depth.
3850 */
3851static int
3852stackdepth(struct compiler *c)
3853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 basicblock *b, *entryblock;
3855 entryblock = NULL;
3856 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3857 b->b_seen = 0;
3858 b->b_startdepth = INT_MIN;
3859 entryblock = b;
3860 }
3861 if (!entryblock)
3862 return 0;
3863 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864}
3865
3866static int
3867assemble_init(struct assembler *a, int nblocks, int firstlineno)
3868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 memset(a, 0, sizeof(struct assembler));
3870 a->a_lineno = firstlineno;
3871 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3872 if (!a->a_bytecode)
3873 return 0;
3874 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3875 if (!a->a_lnotab)
3876 return 0;
3877 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3878 PyErr_NoMemory();
3879 return 0;
3880 }
3881 a->a_postorder = (basicblock **)PyObject_Malloc(
3882 sizeof(basicblock *) * nblocks);
3883 if (!a->a_postorder) {
3884 PyErr_NoMemory();
3885 return 0;
3886 }
3887 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888}
3889
3890static void
3891assemble_free(struct assembler *a)
3892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 Py_XDECREF(a->a_bytecode);
3894 Py_XDECREF(a->a_lnotab);
3895 if (a->a_postorder)
3896 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897}
3898
3899/* Return the size of a basic block in bytes. */
3900
3901static int
3902instrsize(struct instr *instr)
3903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 if (!instr->i_hasarg)
3905 return 1; /* 1 byte for the opcode*/
3906 if (instr->i_oparg > 0xffff)
3907 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3908 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909}
3910
3911static int
3912blocksize(basicblock *b)
3913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 int i;
3915 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 for (i = 0; i < b->b_iused; i++)
3918 size += instrsize(&b->b_instr[i]);
3919 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920}
3921
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003922/* Appends a pair to the end of the line number table, a_lnotab, representing
3923 the instruction's bytecode offset and line number. See
3924 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003925
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003926static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 int d_bytecode, d_lineno;
3930 int len;
3931 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 d_bytecode = a->a_offset - a->a_lineno_off;
3934 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 assert(d_bytecode >= 0);
3937 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 if(d_bytecode == 0 && d_lineno == 0)
3940 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 if (d_bytecode > 255) {
3943 int j, nbytes, ncodes = d_bytecode / 255;
3944 nbytes = a->a_lnotab_off + 2 * ncodes;
3945 len = PyBytes_GET_SIZE(a->a_lnotab);
3946 if (nbytes >= len) {
3947 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3948 len = nbytes;
3949 else if (len <= INT_MAX / 2)
3950 len *= 2;
3951 else {
3952 PyErr_NoMemory();
3953 return 0;
3954 }
3955 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3956 return 0;
3957 }
3958 lnotab = (unsigned char *)
3959 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3960 for (j = 0; j < ncodes; j++) {
3961 *lnotab++ = 255;
3962 *lnotab++ = 0;
3963 }
3964 d_bytecode -= ncodes * 255;
3965 a->a_lnotab_off += ncodes * 2;
3966 }
3967 assert(d_bytecode <= 255);
3968 if (d_lineno > 255) {
3969 int j, nbytes, ncodes = d_lineno / 255;
3970 nbytes = a->a_lnotab_off + 2 * ncodes;
3971 len = PyBytes_GET_SIZE(a->a_lnotab);
3972 if (nbytes >= len) {
3973 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3974 len = nbytes;
3975 else if (len <= INT_MAX / 2)
3976 len *= 2;
3977 else {
3978 PyErr_NoMemory();
3979 return 0;
3980 }
3981 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3982 return 0;
3983 }
3984 lnotab = (unsigned char *)
3985 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3986 *lnotab++ = d_bytecode;
3987 *lnotab++ = 255;
3988 d_bytecode = 0;
3989 for (j = 1; j < ncodes; j++) {
3990 *lnotab++ = 0;
3991 *lnotab++ = 255;
3992 }
3993 d_lineno -= ncodes * 255;
3994 a->a_lnotab_off += ncodes * 2;
3995 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 len = PyBytes_GET_SIZE(a->a_lnotab);
3998 if (a->a_lnotab_off + 2 >= len) {
3999 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4000 return 0;
4001 }
4002 lnotab = (unsigned char *)
4003 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 a->a_lnotab_off += 2;
4006 if (d_bytecode) {
4007 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004008 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 }
4010 else { /* First line of a block; def stmt, etc. */
4011 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004012 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 }
4014 a->a_lineno = i->i_lineno;
4015 a->a_lineno_off = a->a_offset;
4016 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004017}
4018
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004019/* assemble_emit()
4020 Extend the bytecode with a new instruction.
4021 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004022*/
4023
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004024static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 int size, arg = 0, ext = 0;
4028 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4029 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 size = instrsize(i);
4032 if (i->i_hasarg) {
4033 arg = i->i_oparg;
4034 ext = arg >> 16;
4035 }
4036 if (i->i_lineno && !assemble_lnotab(a, i))
4037 return 0;
4038 if (a->a_offset + size >= len) {
4039 if (len > PY_SSIZE_T_MAX / 2)
4040 return 0;
4041 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4042 return 0;
4043 }
4044 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4045 a->a_offset += size;
4046 if (size == 6) {
4047 assert(i->i_hasarg);
4048 *code++ = (char)EXTENDED_ARG;
4049 *code++ = ext & 0xff;
4050 *code++ = ext >> 8;
4051 arg &= 0xffff;
4052 }
4053 *code++ = i->i_opcode;
4054 if (i->i_hasarg) {
4055 assert(size == 3 || size == 6);
4056 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004057 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 }
4059 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004060}
4061
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004062static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 basicblock *b;
4066 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4067 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 /* Compute the size of each block and fixup jump args.
4070 Replace block pointer with position in bytecode. */
4071 do {
4072 totsize = 0;
4073 for (i = a->a_nblocks - 1; i >= 0; i--) {
4074 b = a->a_postorder[i];
4075 bsize = blocksize(b);
4076 b->b_offset = totsize;
4077 totsize += bsize;
4078 }
4079 last_extended_arg_count = extended_arg_count;
4080 extended_arg_count = 0;
4081 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4082 bsize = b->b_offset;
4083 for (i = 0; i < b->b_iused; i++) {
4084 struct instr *instr = &b->b_instr[i];
4085 /* Relative jumps are computed relative to
4086 the instruction pointer after fetching
4087 the jump instruction.
4088 */
4089 bsize += instrsize(instr);
4090 if (instr->i_jabs)
4091 instr->i_oparg = instr->i_target->b_offset;
4092 else if (instr->i_jrel) {
4093 int delta = instr->i_target->b_offset - bsize;
4094 instr->i_oparg = delta;
4095 }
4096 else
4097 continue;
4098 if (instr->i_oparg > 0xffff)
4099 extended_arg_count++;
4100 }
4101 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 /* XXX: This is an awful hack that could hurt performance, but
4104 on the bright side it should work until we come up
4105 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 The issue is that in the first loop blocksize() is called
4108 which calls instrsize() which requires i_oparg be set
4109 appropriately. There is a bootstrap problem because
4110 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 So we loop until we stop seeing new EXTENDED_ARGs.
4113 The only EXTENDED_ARGs that could be popping up are
4114 ones in jump instructions. So this should converge
4115 fairly quickly.
4116 */
4117 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004118}
4119
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004120static PyObject *
4121dict_keys_inorder(PyObject *dict, int offset)
4122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 PyObject *tuple, *k, *v;
4124 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 tuple = PyTuple_New(size);
4127 if (tuple == NULL)
4128 return NULL;
4129 while (PyDict_Next(dict, &pos, &k, &v)) {
4130 i = PyLong_AS_LONG(v);
4131 /* The keys of the dictionary are tuples. (see compiler_add_o)
4132 The object we want is always first, though. */
4133 k = PyTuple_GET_ITEM(k, 0);
4134 Py_INCREF(k);
4135 assert((i - offset) < size);
4136 assert((i - offset) >= 0);
4137 PyTuple_SET_ITEM(tuple, i - offset, k);
4138 }
4139 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004140}
4141
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004142static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004143compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 PySTEntryObject *ste = c->u->u_ste;
4146 int flags = 0, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004148 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 if (!ste->ste_unoptimized)
4150 flags |= CO_OPTIMIZED;
4151 if (ste->ste_nested)
4152 flags |= CO_NESTED;
4153 if (ste->ste_generator)
4154 flags |= CO_GENERATOR;
4155 if (ste->ste_varargs)
4156 flags |= CO_VARARGS;
4157 if (ste->ste_varkeywords)
4158 flags |= CO_VARKEYWORDS;
4159 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 /* (Only) inherit compilerflags in PyCF_MASK */
4162 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 n = PyDict_Size(c->u->u_freevars);
4165 if (n < 0)
4166 return -1;
4167 if (n == 0) {
4168 n = PyDict_Size(c->u->u_cellvars);
4169 if (n < 0)
4170 return -1;
4171 if (n == 0) {
4172 flags |= CO_NOFREE;
4173 }
4174 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004177}
4178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179static PyCodeObject *
4180makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 PyObject *tmp;
4183 PyCodeObject *co = NULL;
4184 PyObject *consts = NULL;
4185 PyObject *names = NULL;
4186 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 PyObject *name = NULL;
4188 PyObject *freevars = NULL;
4189 PyObject *cellvars = NULL;
4190 PyObject *bytecode = NULL;
4191 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 tmp = dict_keys_inorder(c->u->u_consts, 0);
4194 if (!tmp)
4195 goto error;
4196 consts = PySequence_List(tmp); /* optimize_code requires a list */
4197 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 names = dict_keys_inorder(c->u->u_names, 0);
4200 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4201 if (!consts || !names || !varnames)
4202 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4205 if (!cellvars)
4206 goto error;
4207 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4208 if (!freevars)
4209 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 nlocals = PyDict_Size(c->u->u_varnames);
4211 flags = compute_code_flags(c);
4212 if (flags < 0)
4213 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4216 if (!bytecode)
4217 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4220 if (!tmp)
4221 goto error;
4222 Py_DECREF(consts);
4223 consts = tmp;
4224
4225 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4226 nlocals, stackdepth(c), flags,
4227 bytecode, consts, names, varnames,
4228 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004229 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 c->u->u_firstlineno,
4231 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004232 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 Py_XDECREF(consts);
4234 Py_XDECREF(names);
4235 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 Py_XDECREF(name);
4237 Py_XDECREF(freevars);
4238 Py_XDECREF(cellvars);
4239 Py_XDECREF(bytecode);
4240 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004241}
4242
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004243
4244/* For debugging purposes only */
4245#if 0
4246static void
4247dump_instr(const struct instr *i)
4248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 const char *jrel = i->i_jrel ? "jrel " : "";
4250 const char *jabs = i->i_jabs ? "jabs " : "";
4251 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 *arg = '\0';
4254 if (i->i_hasarg)
4255 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4258 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004259}
4260
4261static void
4262dump_basicblock(const basicblock *b)
4263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 const char *seen = b->b_seen ? "seen " : "";
4265 const char *b_return = b->b_return ? "return " : "";
4266 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4267 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4268 if (b->b_instr) {
4269 int i;
4270 for (i = 0; i < b->b_iused; i++) {
4271 fprintf(stderr, " [%02d] ", i);
4272 dump_instr(b->b_instr + i);
4273 }
4274 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004275}
4276#endif
4277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004278static PyCodeObject *
4279assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 basicblock *b, *entryblock;
4282 struct assembler a;
4283 int i, j, nblocks;
4284 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 /* Make sure every block that falls off the end returns None.
4287 XXX NEXT_BLOCK() isn't quite right, because if the last
4288 block ends with a jump or return b_next shouldn't set.
4289 */
4290 if (!c->u->u_curblock->b_return) {
4291 NEXT_BLOCK(c);
4292 if (addNone)
4293 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4294 ADDOP(c, RETURN_VALUE);
4295 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 nblocks = 0;
4298 entryblock = NULL;
4299 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4300 nblocks++;
4301 entryblock = b;
4302 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 /* Set firstlineno if it wasn't explicitly set. */
4305 if (!c->u->u_firstlineno) {
4306 if (entryblock && entryblock->b_instr)
4307 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4308 else
4309 c->u->u_firstlineno = 1;
4310 }
4311 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4312 goto error;
4313 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 /* Can't modify the bytecode after computing jump offsets. */
4316 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 /* Emit code in reverse postorder from dfs. */
4319 for (i = a.a_nblocks - 1; i >= 0; i--) {
4320 b = a.a_postorder[i];
4321 for (j = 0; j < b->b_iused; j++)
4322 if (!assemble_emit(&a, &b->b_instr[j]))
4323 goto error;
4324 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4327 goto error;
4328 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4329 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004332 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 assemble_free(&a);
4334 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004335}
Georg Brandl8334fd92010-12-04 10:26:46 +00004336
4337#undef PyAST_Compile
4338PyAPI_FUNC(PyCodeObject *)
4339PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4340 PyArena *arena)
4341{
4342 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4343}
4344
4345