blob: 4fc75759260f6e4cdcb112b1a79e9da80d0cee23 [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 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 const char *c_filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500153 PyObject *c_filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 struct symtable *c_st;
155 PyFutureFeatures *c_future; /* pointer to module's __future__ */
156 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157
Georg Brandl8334fd92010-12-04 10:26:46 +0000158 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 int c_interactive; /* true if in interactive mode */
160 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 struct compiler_unit *u; /* compiler state for current block */
163 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
164 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000165};
166
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100167static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168static void compiler_free(struct compiler *);
169static basicblock *compiler_new_block(struct compiler *);
170static int compiler_next_instr(struct compiler *, basicblock *);
171static int compiler_addop(struct compiler *, int);
172static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
173static int compiler_addop_i(struct compiler *, int, int);
174static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175static basicblock *compiler_use_new_block(struct compiler *);
176static int compiler_error(struct compiler *, const char *);
177static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
178
179static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
180static int compiler_visit_stmt(struct compiler *, stmt_ty);
181static int compiler_visit_keyword(struct compiler *, keyword_ty);
182static int compiler_visit_expr(struct compiler *, expr_ty);
183static int compiler_augassign(struct compiler *, stmt_ty);
184static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186
187static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191/* Returns true if there is a loop on the fblock stack. */
192static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193
194static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000195static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500197static int compiler_with(struct compiler *, stmt_ty, int);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000198static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 asdl_seq *args,
200 asdl_seq *keywords,
201 expr_ty starargs,
202 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500203static int compiler_try_except(struct compiler *, stmt_ty);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205static PyCodeObject *assemble(struct compiler *, int addNone);
206static PyObject *__doc__;
207
Benjamin Petersonb173f782009-05-05 22:31:58 +0000208#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 /* Name mangling: __private becomes _classname__private.
214 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200215 PyObject *result;
216 size_t nlen, plen, ipriv;
217 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200219 PyUnicode_READ_CHAR(ident, 0) != '_' ||
220 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 Py_INCREF(ident);
222 return ident;
223 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200224 nlen = PyUnicode_GET_LENGTH(ident);
225 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 The only time a name with a dot can occur is when
229 we are compiling an import statement that has a
230 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 TODO(jhylton): Decide whether we want to support
233 mangling of the module name, e.g. __M.X.
234 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200235 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
236 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
237 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident; /* Don't mangle __whatever__ */
240 }
241 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 ipriv = 0;
243 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
244 ipriv++;
245 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_INCREF(ident);
247 return ident; /* Don't mangle if class is just underscores */
248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000250
Antoine Pitrou55bff892013-04-06 21:21:04 +0200251 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
252 PyErr_SetString(PyExc_OverflowError,
253 "private identifier too large to be mangled");
254 return NULL;
255 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200257 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
258 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
259 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
260
261 result = PyUnicode_New(1 + nlen + plen, maxchar);
262 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
265 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200266 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
267 Py_DECREF(result);
268 return NULL;
269 }
270 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
271 Py_DECREF(result);
272 return NULL;
273 }
Victor Stinner8f825062012-04-27 13:55:39 +0200274 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000276}
277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278static int
279compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 c->c_stack = PyList_New(0);
284 if (!c->c_stack)
285 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288}
289
290PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +0000291PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
292 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 struct compiler c;
295 PyCodeObject *co = NULL;
296 PyCompilerFlags local_flags;
297 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (!__doc__) {
300 __doc__ = PyUnicode_InternFromString("__doc__");
301 if (!__doc__)
302 return NULL;
303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!compiler_init(&c))
306 return NULL;
307 c.c_filename = filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500308 c.c_filename_obj = PyUnicode_DecodeFSDefault(filename);
309 if (!c.c_filename_obj)
310 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 c.c_arena = arena;
312 c.c_future = PyFuture_FromAST(mod, filename);
313 if (c.c_future == NULL)
314 goto finally;
315 if (!flags) {
316 local_flags.cf_flags = 0;
317 flags = &local_flags;
318 }
319 merged = c.c_future->ff_features | flags->cf_flags;
320 c.c_future->ff_features = merged;
321 flags->cf_flags = merged;
322 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000323 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 c.c_st = PySymtable_Build(mod, filename, c.c_future);
327 if (c.c_st == NULL) {
328 if (!PyErr_Occurred())
329 PyErr_SetString(PyExc_SystemError, "no symtable");
330 goto finally;
331 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334
Thomas Wouters1175c432006-02-27 22:49:54 +0000335 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 compiler_free(&c);
337 assert(co || PyErr_Occurred());
338 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339}
340
341PyCodeObject *
342PyNode_Compile(struct _node *n, const char *filename)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 PyCodeObject *co = NULL;
345 mod_ty mod;
346 PyArena *arena = PyArena_New();
347 if (!arena)
348 return NULL;
349 mod = PyAST_FromNode(n, NULL, filename, arena);
350 if (mod)
351 co = PyAST_Compile(mod, filename, NULL, arena);
352 PyArena_Free(arena);
353 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000354}
355
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000356static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (c->c_st)
360 PySymtable_Free(c->c_st);
361 if (c->c_future)
362 PyObject_Free(c->c_future);
Benjamin Peterson43b06862011-05-27 09:08:01 -0500363 if (c->c_filename_obj)
364 Py_DECREF(c->c_filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000366}
367
Guido van Rossum79f25d91997-04-29 20:08:16 +0000368static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 Py_ssize_t i, n;
372 PyObject *v, *k;
373 PyObject *dict = PyDict_New();
374 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 n = PyList_Size(list);
377 for (i = 0; i < n; i++) {
378 v = PyLong_FromLong(i);
379 if (!v) {
380 Py_DECREF(dict);
381 return NULL;
382 }
383 k = PyList_GET_ITEM(list, i);
384 k = PyTuple_Pack(2, k, k->ob_type);
385 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
386 Py_XDECREF(k);
387 Py_DECREF(v);
388 Py_DECREF(dict);
389 return NULL;
390 }
391 Py_DECREF(k);
392 Py_DECREF(v);
393 }
394 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395}
396
397/* Return new dict containing names from src that match scope(s).
398
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000399src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000401values are integers, starting at offset and increasing by one for
402each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403*/
404
405static PyObject *
406dictbytype(PyObject *src, int scope_type, int flag, int offset)
407{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700408 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500410 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 assert(offset >= 0);
413 if (dest == NULL)
414 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415
Meador Inge2ca63152012-07-18 14:20:11 -0500416 /* Sort the keys so that we have a deterministic order on the indexes
417 saved in the returned dictionary. These indexes are used as indexes
418 into the free and cell var storage. Therefore if they aren't
419 deterministic, then the generated bytecode is not deterministic.
420 */
421 sorted_keys = PyDict_Keys(src);
422 if (sorted_keys == NULL)
423 return NULL;
424 if (PyList_Sort(sorted_keys) != 0) {
425 Py_DECREF(sorted_keys);
426 return NULL;
427 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500428 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500429
430 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 /* XXX this should probably be a macro in symtable.h */
432 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500433 k = PyList_GET_ITEM(sorted_keys, key_i);
434 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 assert(PyLong_Check(v));
436 vi = PyLong_AS_LONG(v);
437 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (scope == scope_type || vi & flag) {
440 PyObject *tuple, *item = PyLong_FromLong(i);
441 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500442 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_DECREF(dest);
444 return NULL;
445 }
446 i++;
447 tuple = PyTuple_Pack(2, k, k->ob_type);
448 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500449 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 Py_DECREF(item);
451 Py_DECREF(dest);
452 Py_XDECREF(tuple);
453 return NULL;
454 }
455 Py_DECREF(item);
456 Py_DECREF(tuple);
457 }
458 }
Meador Inge2ca63152012-07-18 14:20:11 -0500459 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000461}
462
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463static void
464compiler_unit_check(struct compiler_unit *u)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 basicblock *block;
467 for (block = u->u_blocks; block != NULL; block = block->b_list) {
468 assert((void *)block != (void *)0xcbcbcbcb);
469 assert((void *)block != (void *)0xfbfbfbfb);
470 assert((void *)block != (void *)0xdbdbdbdb);
471 if (block->b_instr != NULL) {
472 assert(block->b_ialloc > 0);
473 assert(block->b_iused > 0);
474 assert(block->b_ialloc >= block->b_iused);
475 }
476 else {
477 assert (block->b_iused == 0);
478 assert (block->b_ialloc == 0);
479 }
480 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481}
482
483static void
484compiler_unit_free(struct compiler_unit *u)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 compiler_unit_check(u);
489 b = u->u_blocks;
490 while (b != NULL) {
491 if (b->b_instr)
492 PyObject_Free((void *)b->b_instr);
493 next = b->b_list;
494 PyObject_Free((void *)b);
495 b = next;
496 }
497 Py_CLEAR(u->u_ste);
498 Py_CLEAR(u->u_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100499 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 Py_CLEAR(u->u_consts);
501 Py_CLEAR(u->u_names);
502 Py_CLEAR(u->u_varnames);
503 Py_CLEAR(u->u_freevars);
504 Py_CLEAR(u->u_cellvars);
505 Py_CLEAR(u->u_private);
506 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507}
508
509static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100510compiler_enter_scope(struct compiler *c, identifier name,
511 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
516 struct compiler_unit));
517 if (!u) {
518 PyErr_NoMemory();
519 return 0;
520 }
521 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100522 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 u->u_argcount = 0;
524 u->u_kwonlyargcount = 0;
525 u->u_ste = PySymtable_Lookup(c->c_st, key);
526 if (!u->u_ste) {
527 compiler_unit_free(u);
528 return 0;
529 }
530 Py_INCREF(name);
531 u->u_name = name;
532 u->u_varnames = list2dict(u->u_ste->ste_varnames);
533 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
534 if (!u->u_varnames || !u->u_cellvars) {
535 compiler_unit_free(u);
536 return 0;
537 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500538 if (u->u_ste->ste_needs_class_closure) {
539 /* Cook up a implicit __class__ cell. */
540 _Py_IDENTIFIER(__class__);
541 PyObject *tuple, *name, *zero;
542 int res;
543 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
544 assert(PyDict_Size(u->u_cellvars) == 0);
545 name = _PyUnicode_FromId(&PyId___class__);
546 if (!name) {
547 compiler_unit_free(u);
548 return 0;
549 }
550 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
551 if (!tuple) {
552 compiler_unit_free(u);
553 return 0;
554 }
555 zero = PyLong_FromLong(0);
556 if (!zero) {
557 Py_DECREF(tuple);
558 compiler_unit_free(u);
559 return 0;
560 }
561 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
562 Py_DECREF(tuple);
563 Py_DECREF(zero);
564 if (res < 0) {
565 compiler_unit_free(u);
566 return 0;
567 }
568 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
571 PyDict_Size(u->u_cellvars));
572 if (!u->u_freevars) {
573 compiler_unit_free(u);
574 return 0;
575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 u->u_blocks = NULL;
578 u->u_nfblocks = 0;
579 u->u_firstlineno = lineno;
580 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000581 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 u->u_lineno_set = 0;
583 u->u_consts = PyDict_New();
584 if (!u->u_consts) {
585 compiler_unit_free(u);
586 return 0;
587 }
588 u->u_names = PyDict_New();
589 if (!u->u_names) {
590 compiler_unit_free(u);
591 return 0;
592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* Push the old compiler_unit on the stack. */
597 if (c->u) {
598 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
599 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
600 Py_XDECREF(capsule);
601 compiler_unit_free(u);
602 return 0;
603 }
604 Py_DECREF(capsule);
605 u->u_private = c->u->u_private;
606 Py_XINCREF(u->u_private);
607 }
608 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 c->c_nestlevel++;
611 if (compiler_use_new_block(c) == NULL)
612 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615}
616
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000617static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618compiler_exit_scope(struct compiler *c)
619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 int n;
621 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 c->c_nestlevel--;
624 compiler_unit_free(c->u);
625 /* Restore c->u to the parent unit. */
626 n = PyList_GET_SIZE(c->c_stack) - 1;
627 if (n >= 0) {
628 capsule = PyList_GET_ITEM(c->c_stack, n);
629 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
630 assert(c->u);
631 /* we are deleting from a list so this really shouldn't fail */
632 if (PySequence_DelItem(c->c_stack, n) < 0)
633 Py_FatalError("compiler_exit_scope()");
634 compiler_unit_check(c->u);
635 }
636 else
637 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639}
640
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100641static PyObject *
642compiler_scope_qualname(struct compiler *c)
643{
644 Py_ssize_t stack_size, i;
645 _Py_static_string(dot, ".");
646 _Py_static_string(locals, "<locals>");
647 struct compiler_unit *u;
648 PyObject *capsule, *name, *seq, *dot_str, *locals_str;
649
650 u = c->u;
651 if (u->u_qualname != NULL) {
652 Py_INCREF(u->u_qualname);
653 return u->u_qualname;
654 }
655
656 seq = PyList_New(0);
657 if (seq == NULL)
658 return NULL;
659
660 stack_size = PyList_GET_SIZE(c->c_stack);
661 for (i = 0; i < stack_size; i++) {
662 capsule = PyList_GET_ITEM(c->c_stack, i);
663 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
664 assert(u);
665 if (u->u_scope_type == COMPILER_SCOPE_MODULE)
666 continue;
667 if (PyList_Append(seq, u->u_name))
668 goto _error;
669 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION) {
670 locals_str = _PyUnicode_FromId(&locals);
671 if (locals_str == NULL)
672 goto _error;
673 if (PyList_Append(seq, locals_str))
674 goto _error;
675 }
676 }
677 u = c->u;
678 if (PyList_Append(seq, u->u_name))
679 goto _error;
680 dot_str = _PyUnicode_FromId(&dot);
681 if (dot_str == NULL)
682 goto _error;
683 name = PyUnicode_Join(dot_str, seq);
684 Py_DECREF(seq);
685 u->u_qualname = name;
686 Py_XINCREF(name);
687 return name;
688
689_error:
690 Py_XDECREF(seq);
691 return NULL;
692}
693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694/* Allocate a new block and return a pointer to it.
695 Returns NULL on error.
696*/
697
698static basicblock *
699compiler_new_block(struct compiler *c)
700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 basicblock *b;
702 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 u = c->u;
705 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
706 if (b == NULL) {
707 PyErr_NoMemory();
708 return NULL;
709 }
710 memset((void *)b, 0, sizeof(basicblock));
711 /* Extend the singly linked list of blocks with new block. */
712 b->b_list = u->u_blocks;
713 u->u_blocks = b;
714 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000715}
716
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000717static basicblock *
718compiler_use_new_block(struct compiler *c)
719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 basicblock *block = compiler_new_block(c);
721 if (block == NULL)
722 return NULL;
723 c->u->u_curblock = block;
724 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000725}
726
727static basicblock *
728compiler_next_block(struct compiler *c)
729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 basicblock *block = compiler_new_block(c);
731 if (block == NULL)
732 return NULL;
733 c->u->u_curblock->b_next = block;
734 c->u->u_curblock = block;
735 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736}
737
738static basicblock *
739compiler_use_next_block(struct compiler *c, basicblock *block)
740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 assert(block != NULL);
742 c->u->u_curblock->b_next = block;
743 c->u->u_curblock = block;
744 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000745}
746
747/* Returns the offset of the next instruction in the current block's
748 b_instr array. Resizes the b_instr as necessary.
749 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000750*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751
752static int
753compiler_next_instr(struct compiler *c, basicblock *b)
754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 assert(b != NULL);
756 if (b->b_instr == NULL) {
757 b->b_instr = (struct instr *)PyObject_Malloc(
758 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
759 if (b->b_instr == NULL) {
760 PyErr_NoMemory();
761 return -1;
762 }
763 b->b_ialloc = DEFAULT_BLOCK_SIZE;
764 memset((char *)b->b_instr, 0,
765 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
766 }
767 else if (b->b_iused == b->b_ialloc) {
768 struct instr *tmp;
769 size_t oldsize, newsize;
770 oldsize = b->b_ialloc * sizeof(struct instr);
771 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (oldsize > (PY_SIZE_MAX >> 1)) {
774 PyErr_NoMemory();
775 return -1;
776 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (newsize == 0) {
779 PyErr_NoMemory();
780 return -1;
781 }
782 b->b_ialloc <<= 1;
783 tmp = (struct instr *)PyObject_Realloc(
784 (void *)b->b_instr, newsize);
785 if (tmp == NULL) {
786 PyErr_NoMemory();
787 return -1;
788 }
789 b->b_instr = tmp;
790 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
791 }
792 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
Christian Heimes2202f872008-02-06 14:31:34 +0000795/* Set the i_lineno member of the instruction at offset off if the
796 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000797 already been set. If it has been set, the call has no effect.
798
Christian Heimes2202f872008-02-06 14:31:34 +0000799 The line number is reset in the following cases:
800 - when entering a new scope
801 - on each statement
802 - on each expression that start a new line
803 - before the "except" clause
804 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000805*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000806
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000807static void
808compiler_set_lineno(struct compiler *c, int off)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 basicblock *b;
811 if (c->u->u_lineno_set)
812 return;
813 c->u->u_lineno_set = 1;
814 b = c->u->u_curblock;
815 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816}
817
818static int
819opcode_stack_effect(int opcode, int oparg)
820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 switch (opcode) {
822 case POP_TOP:
823 return -1;
824 case ROT_TWO:
825 case ROT_THREE:
826 return 0;
827 case DUP_TOP:
828 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000829 case DUP_TOP_TWO:
830 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 case UNARY_POSITIVE:
833 case UNARY_NEGATIVE:
834 case UNARY_NOT:
835 case UNARY_INVERT:
836 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 case SET_ADD:
839 case LIST_APPEND:
840 return -1;
841 case MAP_ADD:
842 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 case BINARY_POWER:
845 case BINARY_MULTIPLY:
846 case BINARY_MODULO:
847 case BINARY_ADD:
848 case BINARY_SUBTRACT:
849 case BINARY_SUBSCR:
850 case BINARY_FLOOR_DIVIDE:
851 case BINARY_TRUE_DIVIDE:
852 return -1;
853 case INPLACE_FLOOR_DIVIDE:
854 case INPLACE_TRUE_DIVIDE:
855 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 case INPLACE_ADD:
858 case INPLACE_SUBTRACT:
859 case INPLACE_MULTIPLY:
860 case INPLACE_MODULO:
861 return -1;
862 case STORE_SUBSCR:
863 return -3;
864 case STORE_MAP:
865 return -2;
866 case DELETE_SUBSCR:
867 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 case BINARY_LSHIFT:
870 case BINARY_RSHIFT:
871 case BINARY_AND:
872 case BINARY_XOR:
873 case BINARY_OR:
874 return -1;
875 case INPLACE_POWER:
876 return -1;
877 case GET_ITER:
878 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case PRINT_EXPR:
881 return -1;
882 case LOAD_BUILD_CLASS:
883 return 1;
884 case INPLACE_LSHIFT:
885 case INPLACE_RSHIFT:
886 case INPLACE_AND:
887 case INPLACE_XOR:
888 case INPLACE_OR:
889 return -1;
890 case BREAK_LOOP:
891 return 0;
892 case SETUP_WITH:
893 return 7;
894 case WITH_CLEANUP:
895 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case RETURN_VALUE:
897 return -1;
898 case IMPORT_STAR:
899 return -1;
900 case YIELD_VALUE:
901 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500902 case YIELD_FROM:
903 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case POP_BLOCK:
905 return 0;
906 case POP_EXCEPT:
907 return 0; /* -3 except if bad bytecode */
908 case END_FINALLY:
909 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case STORE_NAME:
912 return -1;
913 case DELETE_NAME:
914 return 0;
915 case UNPACK_SEQUENCE:
916 return oparg-1;
917 case UNPACK_EX:
918 return (oparg&0xFF) + (oparg>>8);
919 case FOR_ITER:
920 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case STORE_ATTR:
923 return -2;
924 case DELETE_ATTR:
925 return -1;
926 case STORE_GLOBAL:
927 return -1;
928 case DELETE_GLOBAL:
929 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 case LOAD_CONST:
931 return 1;
932 case LOAD_NAME:
933 return 1;
934 case BUILD_TUPLE:
935 case BUILD_LIST:
936 case BUILD_SET:
937 return 1-oparg;
938 case BUILD_MAP:
939 return 1;
940 case LOAD_ATTR:
941 return 0;
942 case COMPARE_OP:
943 return -1;
944 case IMPORT_NAME:
945 return -1;
946 case IMPORT_FROM:
947 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case JUMP_FORWARD:
950 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
951 case JUMP_IF_FALSE_OR_POP: /* "" */
952 case JUMP_ABSOLUTE:
953 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 case POP_JUMP_IF_FALSE:
956 case POP_JUMP_IF_TRUE:
957 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case LOAD_GLOBAL:
960 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 case CONTINUE_LOOP:
963 return 0;
964 case SETUP_LOOP:
965 return 0;
966 case SETUP_EXCEPT:
967 case SETUP_FINALLY:
968 return 6; /* can push 3 values for the new exception
969 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case LOAD_FAST:
972 return 1;
973 case STORE_FAST:
974 return -1;
975 case DELETE_FAST:
976 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 case RAISE_VARARGS:
979 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000980#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case CALL_FUNCTION:
982 return -NARGS(oparg);
983 case CALL_FUNCTION_VAR:
984 case CALL_FUNCTION_KW:
985 return -NARGS(oparg)-1;
986 case CALL_FUNCTION_VAR_KW:
987 return -NARGS(oparg)-2;
988 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100989 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100991 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000992#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case BUILD_SLICE:
994 if (oparg == 3)
995 return -2;
996 else
997 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case LOAD_CLOSURE:
1000 return 1;
1001 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001002 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 return 1;
1004 case STORE_DEREF:
1005 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001006 case DELETE_DEREF:
1007 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 default:
1009 fprintf(stderr, "opcode = %d\n", opcode);
1010 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 }
1013 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001014}
1015
1016/* Add an opcode with no argument.
1017 Returns 0 on failure, 1 on success.
1018*/
1019
1020static int
1021compiler_addop(struct compiler *c, int opcode)
1022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 basicblock *b;
1024 struct instr *i;
1025 int off;
1026 off = compiler_next_instr(c, c->u->u_curblock);
1027 if (off < 0)
1028 return 0;
1029 b = c->u->u_curblock;
1030 i = &b->b_instr[off];
1031 i->i_opcode = opcode;
1032 i->i_hasarg = 0;
1033 if (opcode == RETURN_VALUE)
1034 b->b_return = 1;
1035 compiler_set_lineno(c, off);
1036 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037}
1038
1039static int
1040compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyObject *t, *v;
1043 Py_ssize_t arg;
1044 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 /* necessary to make sure types aren't coerced (e.g., int and long) */
1047 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1048 if (PyFloat_Check(o)) {
1049 d = PyFloat_AS_DOUBLE(o);
1050 /* all we need is to make the tuple different in either the 0.0
1051 * or -0.0 case from all others, just to avoid the "coercion".
1052 */
1053 if (d == 0.0 && copysign(1.0, d) < 0.0)
1054 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1055 else
1056 t = PyTuple_Pack(2, o, o->ob_type);
1057 }
1058 else if (PyComplex_Check(o)) {
1059 Py_complex z;
1060 int real_negzero, imag_negzero;
1061 /* For the complex case we must make complex(x, 0.)
1062 different from complex(x, -0.) and complex(0., y)
1063 different from complex(-0., y), for any x and y.
1064 All four complex zeros must be distinguished.*/
1065 z = PyComplex_AsCComplex(o);
1066 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1067 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1068 if (real_negzero && imag_negzero) {
1069 t = PyTuple_Pack(5, o, o->ob_type,
1070 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001071 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 else if (imag_negzero) {
1073 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 else if (real_negzero) {
1076 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1077 }
1078 else {
1079 t = PyTuple_Pack(2, o, o->ob_type);
1080 }
1081 }
1082 else {
1083 t = PyTuple_Pack(2, o, o->ob_type);
1084 }
1085 if (t == NULL)
1086 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 v = PyDict_GetItem(dict, t);
1089 if (!v) {
1090 if (PyErr_Occurred())
1091 return -1;
1092 arg = PyDict_Size(dict);
1093 v = PyLong_FromLong(arg);
1094 if (!v) {
1095 Py_DECREF(t);
1096 return -1;
1097 }
1098 if (PyDict_SetItem(dict, t, v) < 0) {
1099 Py_DECREF(t);
1100 Py_DECREF(v);
1101 return -1;
1102 }
1103 Py_DECREF(v);
1104 }
1105 else
1106 arg = PyLong_AsLong(v);
1107 Py_DECREF(t);
1108 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109}
1110
1111static int
1112compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114{
1115 int arg = compiler_add_o(c, dict, o);
1116 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001117 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118 return compiler_addop_i(c, opcode, arg);
1119}
1120
1121static int
1122compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124{
1125 int arg;
1126 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1127 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001128 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 arg = compiler_add_o(c, dict, mangled);
1130 Py_DECREF(mangled);
1131 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001132 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 return compiler_addop_i(c, opcode, arg);
1134}
1135
1136/* Add an opcode with an integer argument.
1137 Returns 0 on failure, 1 on success.
1138*/
1139
1140static int
1141compiler_addop_i(struct compiler *c, int opcode, int oparg)
1142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 struct instr *i;
1144 int off;
1145 off = compiler_next_instr(c, c->u->u_curblock);
1146 if (off < 0)
1147 return 0;
1148 i = &c->u->u_curblock->b_instr[off];
1149 i->i_opcode = opcode;
1150 i->i_oparg = oparg;
1151 i->i_hasarg = 1;
1152 compiler_set_lineno(c, off);
1153 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154}
1155
1156static int
1157compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 struct instr *i;
1160 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 assert(b != NULL);
1163 off = compiler_next_instr(c, c->u->u_curblock);
1164 if (off < 0)
1165 return 0;
1166 i = &c->u->u_curblock->b_instr[off];
1167 i->i_opcode = opcode;
1168 i->i_target = b;
1169 i->i_hasarg = 1;
1170 if (absolute)
1171 i->i_jabs = 1;
1172 else
1173 i->i_jrel = 1;
1174 compiler_set_lineno(c, off);
1175 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176}
1177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1179 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180 it as the current block. NEXT_BLOCK() also creates an implicit jump
1181 from the current block to the new block.
1182*/
1183
Thomas Wouters89f507f2006-12-13 04:49:30 +00001184/* The returns inside these macros make it impossible to decref objects
1185 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186*/
1187
1188
1189#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (compiler_use_new_block((C)) == NULL) \
1191 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192}
1193
1194#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (compiler_next_block((C)) == NULL) \
1196 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197}
1198
1199#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (!compiler_addop((C), (OP))) \
1201 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202}
1203
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001204#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (!compiler_addop((C), (OP))) { \
1206 compiler_exit_scope(c); \
1207 return 0; \
1208 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001209}
1210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1213 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214}
1215
1216#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1218 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219}
1220
1221#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (!compiler_addop_i((C), (OP), (O))) \
1223 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224}
1225
1226#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (!compiler_addop_j((C), (OP), (O), 1)) \
1228 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229}
1230
1231#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!compiler_addop_j((C), (OP), (O), 0)) \
1233 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234}
1235
1236/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1237 the ASDL name to synthesize the name of the C type and the visit function.
1238*/
1239
1240#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (!compiler_visit_ ## TYPE((C), (V))) \
1242 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243}
1244
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001245#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (!compiler_visit_ ## TYPE((C), (V))) { \
1247 compiler_exit_scope(c); \
1248 return 0; \
1249 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001250}
1251
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (!compiler_visit_slice((C), (V), (CTX))) \
1254 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255}
1256
1257#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 int _i; \
1259 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1260 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1261 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1262 if (!compiler_visit_ ## TYPE((C), elt)) \
1263 return 0; \
1264 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001267#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 int _i; \
1269 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1270 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1271 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1272 if (!compiler_visit_ ## TYPE((C), elt)) { \
1273 compiler_exit_scope(c); \
1274 return 0; \
1275 } \
1276 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001277}
1278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279static int
1280compiler_isdocstring(stmt_ty s)
1281{
1282 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001283 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284 return s->v.Expr.value->kind == Str_kind;
1285}
1286
1287/* Compile a sequence of statements, checking for a docstring. */
1288
1289static int
1290compiler_body(struct compiler *c, asdl_seq *stmts)
1291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 int i = 0;
1293 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!asdl_seq_LEN(stmts))
1296 return 1;
1297 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001298 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 /* don't generate docstrings if -OO */
1300 i = 1;
1301 VISIT(c, expr, st->v.Expr.value);
1302 if (!compiler_nameop(c, __doc__, Store))
1303 return 0;
1304 }
1305 for (; i < asdl_seq_LEN(stmts); i++)
1306 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1307 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308}
1309
1310static PyCodeObject *
1311compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyCodeObject *co;
1314 int addNone = 1;
1315 static PyObject *module;
1316 if (!module) {
1317 module = PyUnicode_InternFromString("<module>");
1318 if (!module)
1319 return NULL;
1320 }
1321 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001322 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 return NULL;
1324 switch (mod->kind) {
1325 case Module_kind:
1326 if (!compiler_body(c, mod->v.Module.body)) {
1327 compiler_exit_scope(c);
1328 return 0;
1329 }
1330 break;
1331 case Interactive_kind:
1332 c->c_interactive = 1;
1333 VISIT_SEQ_IN_SCOPE(c, stmt,
1334 mod->v.Interactive.body);
1335 break;
1336 case Expression_kind:
1337 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1338 addNone = 0;
1339 break;
1340 case Suite_kind:
1341 PyErr_SetString(PyExc_SystemError,
1342 "suite should not be possible");
1343 return 0;
1344 default:
1345 PyErr_Format(PyExc_SystemError,
1346 "module kind %d should not be possible",
1347 mod->kind);
1348 return 0;
1349 }
1350 co = assemble(c, addNone);
1351 compiler_exit_scope(c);
1352 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001353}
1354
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355/* The test for LOCAL must come before the test for FREE in order to
1356 handle classes where name is both local and free. The local var is
1357 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001358*/
1359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360static int
1361get_ref_type(struct compiler *c, PyObject *name)
1362{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001363 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001364 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1365 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1366 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001367 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (scope == 0) {
1369 char buf[350];
1370 PyOS_snprintf(buf, sizeof(buf),
1371 "unknown scope for %.100s in %.100s(%s) in %s\n"
1372 "symbols: %s\nlocals: %s\nglobals: %s",
1373 PyBytes_AS_STRING(name),
1374 PyBytes_AS_STRING(c->u->u_name),
1375 PyObject_REPR(c->u->u_ste->ste_id),
1376 c->c_filename,
1377 PyObject_REPR(c->u->u_ste->ste_symbols),
1378 PyObject_REPR(c->u->u_varnames),
1379 PyObject_REPR(c->u->u_names)
1380 );
1381 Py_FatalError(buf);
1382 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385}
1386
1387static int
1388compiler_lookup_arg(PyObject *dict, PyObject *name)
1389{
1390 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001393 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001395 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001397 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001398 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399}
1400
1401static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001402compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001405 if (qualname == NULL)
1406 qualname = co->co_name;
1407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (free == 0) {
1409 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001410 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 ADDOP_I(c, MAKE_FUNCTION, args);
1412 return 1;
1413 }
1414 for (i = 0; i < free; ++i) {
1415 /* Bypass com_addop_varname because it will generate
1416 LOAD_DEREF but LOAD_CLOSURE is needed.
1417 */
1418 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1419 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /* Special case: If a class contains a method with a
1422 free variable that has the same name as a method,
1423 the name will be considered free *and* local in the
1424 class. It should be handled by the closure, as
1425 well as by the normal name loookup logic.
1426 */
1427 reftype = get_ref_type(c, name);
1428 if (reftype == CELL)
1429 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1430 else /* (reftype == FREE) */
1431 arg = compiler_lookup_arg(c->u->u_freevars, name);
1432 if (arg == -1) {
1433 fprintf(stderr,
1434 "lookup %s in %s %d %d\n"
1435 "freevars of %s: %s\n",
1436 PyObject_REPR(name),
1437 PyBytes_AS_STRING(c->u->u_name),
1438 reftype, arg,
1439 _PyUnicode_AsString(co->co_name),
1440 PyObject_REPR(co->co_freevars));
1441 Py_FatalError("compiler_make_closure()");
1442 }
1443 ADDOP_I(c, LOAD_CLOSURE, arg);
1444 }
1445 ADDOP_I(c, BUILD_TUPLE, free);
1446 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001447 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 ADDOP_I(c, MAKE_CLOSURE, args);
1449 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450}
1451
1452static int
1453compiler_decorators(struct compiler *c, asdl_seq* decos)
1454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!decos)
1458 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1461 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1462 }
1463 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464}
1465
1466static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001467compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 int i, default_count = 0;
1471 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1472 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1473 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1474 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001475 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1476 if (!mangled)
1477 return -1;
1478 ADDOP_O(c, LOAD_CONST, mangled, consts);
1479 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (!compiler_visit_expr(c, default_)) {
1481 return -1;
1482 }
1483 default_count++;
1484 }
1485 }
1486 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001487}
1488
1489static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001490compiler_visit_argannotation(struct compiler *c, identifier id,
1491 expr_ty annotation, PyObject *names)
1492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (annotation) {
1494 VISIT(c, expr, annotation);
1495 if (PyList_Append(names, id))
1496 return -1;
1497 }
1498 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001499}
1500
1501static int
1502compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1503 PyObject *names)
1504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 int i, error;
1506 for (i = 0; i < asdl_seq_LEN(args); i++) {
1507 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1508 error = compiler_visit_argannotation(
1509 c,
1510 arg->arg,
1511 arg->annotation,
1512 names);
1513 if (error)
1514 return error;
1515 }
1516 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001517}
1518
1519static int
1520compiler_visit_annotations(struct compiler *c, arguments_ty args,
1521 expr_ty returns)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 /* Push arg annotations and a list of the argument names. Return the #
1524 of items pushed. The expressions are evaluated out-of-order wrt the
1525 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1528 */
1529 static identifier return_str;
1530 PyObject *names;
1531 int len;
1532 names = PyList_New(0);
1533 if (!names)
1534 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (compiler_visit_argannotations(c, args->args, names))
1537 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001538 if (args->vararg && args->vararg->annotation &&
1539 compiler_visit_argannotation(c, args->vararg->arg,
1540 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 goto error;
1542 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1543 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001544 if (args->kwarg && args->kwarg->annotation &&
1545 compiler_visit_argannotation(c, args->kwarg->arg,
1546 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (!return_str) {
1550 return_str = PyUnicode_InternFromString("return");
1551 if (!return_str)
1552 goto error;
1553 }
1554 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1555 goto error;
1556 }
1557
1558 len = PyList_GET_SIZE(names);
1559 if (len > 65534) {
1560 /* len must fit in 16 bits, and len is incremented below */
1561 PyErr_SetString(PyExc_SyntaxError,
1562 "too many annotations");
1563 goto error;
1564 }
1565 if (len) {
1566 /* convert names to a tuple and place on stack */
1567 PyObject *elt;
1568 int i;
1569 PyObject *s = PyTuple_New(len);
1570 if (!s)
1571 goto error;
1572 for (i = 0; i < len; i++) {
1573 elt = PyList_GET_ITEM(names, i);
1574 Py_INCREF(elt);
1575 PyTuple_SET_ITEM(s, i, elt);
1576 }
1577 ADDOP_O(c, LOAD_CONST, s, consts);
1578 Py_DECREF(s);
1579 len++; /* include the just-pushed tuple */
1580 }
1581 Py_DECREF(names);
1582 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001583
1584error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 Py_DECREF(names);
1586 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001587}
1588
1589static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590compiler_function(struct compiler *c, stmt_ty s)
1591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001593 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 arguments_ty args = s->v.FunctionDef.args;
1595 expr_ty returns = s->v.FunctionDef.returns;
1596 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1597 stmt_ty st;
1598 int i, n, docstring, kw_default_count = 0, arglength;
1599 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (!compiler_decorators(c, decos))
1604 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001605 if (args->defaults)
1606 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (args->kwonlyargs) {
1608 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1609 args->kw_defaults);
1610 if (res < 0)
1611 return 0;
1612 kw_default_count = res;
1613 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 num_annotations = compiler_visit_annotations(c, args, returns);
1615 if (num_annotations < 0)
1616 return 0;
1617 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001618
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001619 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1620 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 s->lineno))
1622 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1625 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001626 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 first_const = st->v.Expr.value->v.Str.s;
1628 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1629 compiler_exit_scope(c);
1630 return 0;
1631 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 c->u->u_argcount = asdl_seq_LEN(args->args);
1634 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1635 n = asdl_seq_LEN(s->v.FunctionDef.body);
1636 /* if there was a docstring, we need to skip the first statement */
1637 for (i = docstring; i < n; i++) {
1638 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1639 VISIT_IN_SCOPE(c, stmt, st);
1640 }
1641 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001642 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001644 if (qualname == NULL || co == NULL) {
1645 Py_XDECREF(qualname);
1646 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001648 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 arglength = asdl_seq_LEN(args->defaults);
1651 arglength |= kw_default_count << 8;
1652 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001653 compiler_make_closure(c, co, arglength, qualname);
1654 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 /* decorators */
1658 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1659 ADDOP_I(c, CALL_FUNCTION, 1);
1660 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663}
1664
1665static int
1666compiler_class(struct compiler *c, stmt_ty s)
1667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 PyCodeObject *co;
1669 PyObject *str;
1670 int i;
1671 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (!compiler_decorators(c, decos))
1674 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 /* ultimately generate code for:
1677 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1678 where:
1679 <func> is a function/closure created from the class body;
1680 it has a single argument (__locals__) where the dict
1681 (or MutableSequence) representing the locals is passed
1682 <name> is the class name
1683 <bases> is the positional arguments and *varargs argument
1684 <keywords> is the keyword arguments and **kwds argument
1685 This borrows from compiler_call.
1686 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001689 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1690 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 return 0;
1692 /* this block represents what we do in the new scope */
1693 {
1694 /* use the class name for name mangling */
1695 Py_INCREF(s->v.ClassDef.name);
1696 Py_XDECREF(c->u->u_private);
1697 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 /* load (global) __name__ ... */
1699 str = PyUnicode_InternFromString("__name__");
1700 if (!str || !compiler_nameop(c, str, Load)) {
1701 Py_XDECREF(str);
1702 compiler_exit_scope(c);
1703 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001704 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 Py_DECREF(str);
1706 /* ... and store it as __module__ */
1707 str = PyUnicode_InternFromString("__module__");
1708 if (!str || !compiler_nameop(c, str, Store)) {
1709 Py_XDECREF(str);
1710 compiler_exit_scope(c);
1711 return 0;
1712 }
1713 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001714 /* store the __qualname__ */
1715 str = compiler_scope_qualname(c);
1716 if (!str) {
1717 compiler_exit_scope(c);
1718 return 0;
1719 }
1720 ADDOP_O(c, LOAD_CONST, str, consts);
1721 Py_DECREF(str);
1722 str = PyUnicode_InternFromString("__qualname__");
1723 if (!str || !compiler_nameop(c, str, Store)) {
1724 Py_XDECREF(str);
1725 compiler_exit_scope(c);
1726 return 0;
1727 }
1728 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* compile the body proper */
1730 if (!compiler_body(c, s->v.ClassDef.body)) {
1731 compiler_exit_scope(c);
1732 return 0;
1733 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001734 if (c->u->u_ste->ste_needs_class_closure) {
1735 /* return the (empty) __class__ cell */
1736 str = PyUnicode_InternFromString("__class__");
1737 if (str == NULL) {
1738 compiler_exit_scope(c);
1739 return 0;
1740 }
1741 i = compiler_lookup_arg(c->u->u_cellvars, str);
1742 Py_DECREF(str);
1743 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 /* Return the cell where to store __class__ */
1745 ADDOP_I(c, LOAD_CLOSURE, i);
1746 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001747 else {
1748 assert(PyDict_Size(c->u->u_cellvars) == 0);
1749 /* This happens when nobody references the cell. Return None. */
1750 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1753 /* create the code object */
1754 co = assemble(c, 1);
1755 }
1756 /* leave the new scope */
1757 compiler_exit_scope(c);
1758 if (co == NULL)
1759 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* 2. load the 'build_class' function */
1762 ADDOP(c, LOAD_BUILD_CLASS);
1763
1764 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001765 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 Py_DECREF(co);
1767
1768 /* 4. load class name */
1769 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1770
1771 /* 5. generate the rest of the code for the call */
1772 if (!compiler_call_helper(c, 2,
1773 s->v.ClassDef.bases,
1774 s->v.ClassDef.keywords,
1775 s->v.ClassDef.starargs,
1776 s->v.ClassDef.kwargs))
1777 return 0;
1778
1779 /* 6. apply decorators */
1780 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1781 ADDOP_I(c, CALL_FUNCTION, 1);
1782 }
1783
1784 /* 7. store into <name> */
1785 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1786 return 0;
1787 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788}
1789
1790static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001791compiler_ifexp(struct compiler *c, expr_ty e)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 basicblock *end, *next;
1794
1795 assert(e->kind == IfExp_kind);
1796 end = compiler_new_block(c);
1797 if (end == NULL)
1798 return 0;
1799 next = compiler_new_block(c);
1800 if (next == NULL)
1801 return 0;
1802 VISIT(c, expr, e->v.IfExp.test);
1803 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1804 VISIT(c, expr, e->v.IfExp.body);
1805 ADDOP_JREL(c, JUMP_FORWARD, end);
1806 compiler_use_next_block(c, next);
1807 VISIT(c, expr, e->v.IfExp.orelse);
1808 compiler_use_next_block(c, end);
1809 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001810}
1811
1812static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813compiler_lambda(struct compiler *c, expr_ty e)
1814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001816 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 static identifier name;
1818 int kw_default_count = 0, arglength;
1819 arguments_ty args = e->v.Lambda.args;
1820 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (!name) {
1823 name = PyUnicode_InternFromString("<lambda>");
1824 if (!name)
1825 return 0;
1826 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001828 if (args->defaults)
1829 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (args->kwonlyargs) {
1831 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1832 args->kw_defaults);
1833 if (res < 0) return 0;
1834 kw_default_count = res;
1835 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001836 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1837 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 /* Make None the first constant, so the lambda can't have a
1841 docstring. */
1842 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1843 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 c->u->u_argcount = asdl_seq_LEN(args->args);
1846 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1847 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1848 if (c->u->u_ste->ste_generator) {
1849 ADDOP_IN_SCOPE(c, POP_TOP);
1850 }
1851 else {
1852 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1853 }
1854 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001855 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001857 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 arglength = asdl_seq_LEN(args->defaults);
1861 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001862 compiler_make_closure(c, co, arglength, qualname);
1863 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 Py_DECREF(co);
1865
1866 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867}
1868
1869static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870compiler_if(struct compiler *c, stmt_ty s)
1871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 basicblock *end, *next;
1873 int constant;
1874 assert(s->kind == If_kind);
1875 end = compiler_new_block(c);
1876 if (end == NULL)
1877 return 0;
1878
Georg Brandl8334fd92010-12-04 10:26:46 +00001879 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 /* constant = 0: "if 0"
1881 * constant = 1: "if 1", "if 2", ...
1882 * constant = -1: rest */
1883 if (constant == 0) {
1884 if (s->v.If.orelse)
1885 VISIT_SEQ(c, stmt, s->v.If.orelse);
1886 } else if (constant == 1) {
1887 VISIT_SEQ(c, stmt, s->v.If.body);
1888 } else {
1889 if (s->v.If.orelse) {
1890 next = compiler_new_block(c);
1891 if (next == NULL)
1892 return 0;
1893 }
1894 else
1895 next = end;
1896 VISIT(c, expr, s->v.If.test);
1897 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1898 VISIT_SEQ(c, stmt, s->v.If.body);
1899 ADDOP_JREL(c, JUMP_FORWARD, end);
1900 if (s->v.If.orelse) {
1901 compiler_use_next_block(c, next);
1902 VISIT_SEQ(c, stmt, s->v.If.orelse);
1903 }
1904 }
1905 compiler_use_next_block(c, end);
1906 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907}
1908
1909static int
1910compiler_for(struct compiler *c, stmt_ty s)
1911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 start = compiler_new_block(c);
1915 cleanup = compiler_new_block(c);
1916 end = compiler_new_block(c);
1917 if (start == NULL || end == NULL || cleanup == NULL)
1918 return 0;
1919 ADDOP_JREL(c, SETUP_LOOP, end);
1920 if (!compiler_push_fblock(c, LOOP, start))
1921 return 0;
1922 VISIT(c, expr, s->v.For.iter);
1923 ADDOP(c, GET_ITER);
1924 compiler_use_next_block(c, start);
1925 ADDOP_JREL(c, FOR_ITER, cleanup);
1926 VISIT(c, expr, s->v.For.target);
1927 VISIT_SEQ(c, stmt, s->v.For.body);
1928 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1929 compiler_use_next_block(c, cleanup);
1930 ADDOP(c, POP_BLOCK);
1931 compiler_pop_fblock(c, LOOP, start);
1932 VISIT_SEQ(c, stmt, s->v.For.orelse);
1933 compiler_use_next_block(c, end);
1934 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935}
1936
1937static int
1938compiler_while(struct compiler *c, stmt_ty s)
1939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001941 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (constant == 0) {
1944 if (s->v.While.orelse)
1945 VISIT_SEQ(c, stmt, s->v.While.orelse);
1946 return 1;
1947 }
1948 loop = compiler_new_block(c);
1949 end = compiler_new_block(c);
1950 if (constant == -1) {
1951 anchor = compiler_new_block(c);
1952 if (anchor == NULL)
1953 return 0;
1954 }
1955 if (loop == NULL || end == NULL)
1956 return 0;
1957 if (s->v.While.orelse) {
1958 orelse = compiler_new_block(c);
1959 if (orelse == NULL)
1960 return 0;
1961 }
1962 else
1963 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 ADDOP_JREL(c, SETUP_LOOP, end);
1966 compiler_use_next_block(c, loop);
1967 if (!compiler_push_fblock(c, LOOP, loop))
1968 return 0;
1969 if (constant == -1) {
1970 VISIT(c, expr, s->v.While.test);
1971 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1972 }
1973 VISIT_SEQ(c, stmt, s->v.While.body);
1974 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 /* XXX should the two POP instructions be in a separate block
1977 if there is no else clause ?
1978 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (constant == -1) {
1981 compiler_use_next_block(c, anchor);
1982 ADDOP(c, POP_BLOCK);
1983 }
1984 compiler_pop_fblock(c, LOOP, loop);
1985 if (orelse != NULL) /* what if orelse is just pass? */
1986 VISIT_SEQ(c, stmt, s->v.While.orelse);
1987 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990}
1991
1992static int
1993compiler_continue(struct compiler *c)
1994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1996 static const char IN_FINALLY_ERROR_MSG[] =
1997 "'continue' not supported inside 'finally' clause";
1998 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (!c->u->u_nfblocks)
2001 return compiler_error(c, LOOP_ERROR_MSG);
2002 i = c->u->u_nfblocks - 1;
2003 switch (c->u->u_fblock[i].fb_type) {
2004 case LOOP:
2005 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2006 break;
2007 case EXCEPT:
2008 case FINALLY_TRY:
2009 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2010 /* Prevent continue anywhere under a finally
2011 even if hidden in a sub-try or except. */
2012 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2013 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2014 }
2015 if (i == -1)
2016 return compiler_error(c, LOOP_ERROR_MSG);
2017 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2018 break;
2019 case FINALLY_END:
2020 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2021 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024}
2025
2026/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027
2028 SETUP_FINALLY L
2029 <code for body>
2030 POP_BLOCK
2031 LOAD_CONST <None>
2032 L: <code for finalbody>
2033 END_FINALLY
2034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 The special instructions use the block stack. Each block
2036 stack entry contains the instruction that created it (here
2037 SETUP_FINALLY), the level of the value stack at the time the
2038 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 Pushes the current value stack level and the label
2042 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002043 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 Pops en entry from the block stack, and pops the value
2045 stack until its level is the same as indicated on the
2046 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 Pops a variable number of entries from the *value* stack
2049 and re-raises the exception they specify. The number of
2050 entries popped depends on the (pseudo) exception type.
2051
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 The block stack is unwound when an exception is raised:
2053 when a SETUP_FINALLY entry is found, the exception is pushed
2054 onto the value stack (and the exception condition is cleared),
2055 and the interpreter jumps to the label gotten from the block
2056 stack.
2057*/
2058
2059static int
2060compiler_try_finally(struct compiler *c, stmt_ty s)
2061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 basicblock *body, *end;
2063 body = compiler_new_block(c);
2064 end = compiler_new_block(c);
2065 if (body == NULL || end == NULL)
2066 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 ADDOP_JREL(c, SETUP_FINALLY, end);
2069 compiler_use_next_block(c, body);
2070 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2071 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002072 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2073 if (!compiler_try_except(c, s))
2074 return 0;
2075 }
2076 else {
2077 VISIT_SEQ(c, stmt, s->v.Try.body);
2078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 ADDOP(c, POP_BLOCK);
2080 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2083 compiler_use_next_block(c, end);
2084 if (!compiler_push_fblock(c, FINALLY_END, end))
2085 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002086 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 ADDOP(c, END_FINALLY);
2088 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091}
2092
2093/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002094 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 (The contents of the value stack is shown in [], with the top
2096 at the right; 'tb' is trace-back info, 'val' the exception's
2097 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098
2099 Value stack Label Instruction Argument
2100 [] SETUP_EXCEPT L1
2101 [] <code for S>
2102 [] POP_BLOCK
2103 [] JUMP_FORWARD L0
2104
2105 [tb, val, exc] L1: DUP )
2106 [tb, val, exc, exc] <evaluate E1> )
2107 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2108 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2109 [tb, val, exc] POP
2110 [tb, val] <assign to V1> (or POP if no V1)
2111 [tb] POP
2112 [] <code for S1>
2113 JUMP_FORWARD L0
2114
2115 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116 .............................etc.......................
2117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2119
2120 [] L0: <next statement>
2121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 Of course, parts are not generated if Vi or Ei is not present.
2123*/
2124static int
2125compiler_try_except(struct compiler *c, stmt_ty s)
2126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 basicblock *body, *orelse, *except, *end;
2128 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 body = compiler_new_block(c);
2131 except = compiler_new_block(c);
2132 orelse = compiler_new_block(c);
2133 end = compiler_new_block(c);
2134 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2135 return 0;
2136 ADDOP_JREL(c, SETUP_EXCEPT, except);
2137 compiler_use_next_block(c, body);
2138 if (!compiler_push_fblock(c, EXCEPT, body))
2139 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002140 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 ADDOP(c, POP_BLOCK);
2142 compiler_pop_fblock(c, EXCEPT, body);
2143 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002144 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 compiler_use_next_block(c, except);
2146 for (i = 0; i < n; i++) {
2147 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002148 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (!handler->v.ExceptHandler.type && i < n-1)
2150 return compiler_error(c, "default 'except:' must be last");
2151 c->u->u_lineno_set = 0;
2152 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002153 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 except = compiler_new_block(c);
2155 if (except == NULL)
2156 return 0;
2157 if (handler->v.ExceptHandler.type) {
2158 ADDOP(c, DUP_TOP);
2159 VISIT(c, expr, handler->v.ExceptHandler.type);
2160 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2161 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2162 }
2163 ADDOP(c, POP_TOP);
2164 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002165 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002166
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002167 cleanup_end = compiler_new_block(c);
2168 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002169 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002170 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002171
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002172 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2173 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002175 /*
2176 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002177 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002178 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002179 try:
2180 # body
2181 finally:
2182 name = None
2183 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002184 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002186 /* second try: */
2187 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2188 compiler_use_next_block(c, cleanup_body);
2189 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2190 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002192 /* second # body */
2193 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2194 ADDOP(c, POP_BLOCK);
2195 ADDOP(c, POP_EXCEPT);
2196 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002198 /* finally: */
2199 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2200 compiler_use_next_block(c, cleanup_end);
2201 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2202 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002204 /* name = None */
2205 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2206 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002208 /* del name */
2209 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002211 ADDOP(c, END_FINALLY);
2212 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 }
2214 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002215 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002217 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002218 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002219 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220
Guido van Rossumb940e112007-01-10 16:19:56 +00002221 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002222 ADDOP(c, POP_TOP);
2223 compiler_use_next_block(c, cleanup_body);
2224 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2225 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002227 ADDOP(c, POP_EXCEPT);
2228 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 }
2230 ADDOP_JREL(c, JUMP_FORWARD, end);
2231 compiler_use_next_block(c, except);
2232 }
2233 ADDOP(c, END_FINALLY);
2234 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002235 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 compiler_use_next_block(c, end);
2237 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238}
2239
2240static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002241compiler_try(struct compiler *c, stmt_ty s) {
2242 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2243 return compiler_try_finally(c, s);
2244 else
2245 return compiler_try_except(c, s);
2246}
2247
2248
2249static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250compiler_import_as(struct compiler *c, identifier name, identifier asname)
2251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* The IMPORT_NAME opcode was already generated. This function
2253 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 If there is a dot in name, we need to split it and emit a
2256 LOAD_ATTR for each name.
2257 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002258 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2259 PyUnicode_GET_LENGTH(name), 1);
2260 if (dot == -2)
2261 return -1;
2262 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002264 Py_ssize_t pos = dot + 1;
2265 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002267 dot = PyUnicode_FindChar(name, '.', pos,
2268 PyUnicode_GET_LENGTH(name), 1);
2269 if (dot == -2)
2270 return -1;
2271 attr = PyUnicode_Substring(name, pos,
2272 (dot != -1) ? dot :
2273 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (!attr)
2275 return -1;
2276 ADDOP_O(c, LOAD_ATTR, attr, names);
2277 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002278 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 }
2280 }
2281 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282}
2283
2284static int
2285compiler_import(struct compiler *c, stmt_ty s)
2286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* The Import node stores a module name like a.b.c as a single
2288 string. This is convenient for all cases except
2289 import a.b.c as d
2290 where we need to parse that string to extract the individual
2291 module names.
2292 XXX Perhaps change the representation to make this case simpler?
2293 */
2294 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 for (i = 0; i < n; i++) {
2297 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2298 int r;
2299 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 level = PyLong_FromLong(0);
2302 if (level == NULL)
2303 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 ADDOP_O(c, LOAD_CONST, level, consts);
2306 Py_DECREF(level);
2307 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2308 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 if (alias->asname) {
2311 r = compiler_import_as(c, alias->name, alias->asname);
2312 if (!r)
2313 return r;
2314 }
2315 else {
2316 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002317 Py_ssize_t dot = PyUnicode_FindChar(
2318 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2319 if (dot != -1)
2320 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002322 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 Py_DECREF(tmp);
2324 }
2325 if (!r)
2326 return r;
2327 }
2328 }
2329 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330}
2331
2332static int
2333compiler_from_import(struct compiler *c, stmt_ty s)
2334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 PyObject *names = PyTuple_New(n);
2338 PyObject *level;
2339 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 if (!empty_string) {
2342 empty_string = PyUnicode_FromString("");
2343 if (!empty_string)
2344 return 0;
2345 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 if (!names)
2348 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 level = PyLong_FromLong(s->v.ImportFrom.level);
2351 if (!level) {
2352 Py_DECREF(names);
2353 return 0;
2354 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 /* build up the names */
2357 for (i = 0; i < n; i++) {
2358 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2359 Py_INCREF(alias->name);
2360 PyTuple_SET_ITEM(names, i, alias->name);
2361 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2364 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2365 Py_DECREF(level);
2366 Py_DECREF(names);
2367 return compiler_error(c, "from __future__ imports must occur "
2368 "at the beginning of the file");
2369 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 ADDOP_O(c, LOAD_CONST, level, consts);
2372 Py_DECREF(level);
2373 ADDOP_O(c, LOAD_CONST, names, consts);
2374 Py_DECREF(names);
2375 if (s->v.ImportFrom.module) {
2376 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2377 }
2378 else {
2379 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2380 }
2381 for (i = 0; i < n; i++) {
2382 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2383 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002385 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 assert(n == 1);
2387 ADDOP(c, IMPORT_STAR);
2388 return 1;
2389 }
2390
2391 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2392 store_name = alias->name;
2393 if (alias->asname)
2394 store_name = alias->asname;
2395
2396 if (!compiler_nameop(c, store_name, Store)) {
2397 Py_DECREF(names);
2398 return 0;
2399 }
2400 }
2401 /* remove imported module */
2402 ADDOP(c, POP_TOP);
2403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404}
2405
2406static int
2407compiler_assert(struct compiler *c, stmt_ty s)
2408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 static PyObject *assertion_error = NULL;
2410 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411
Georg Brandl8334fd92010-12-04 10:26:46 +00002412 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return 1;
2414 if (assertion_error == NULL) {
2415 assertion_error = PyUnicode_InternFromString("AssertionError");
2416 if (assertion_error == NULL)
2417 return 0;
2418 }
2419 if (s->v.Assert.test->kind == Tuple_kind &&
2420 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2421 const char* msg =
2422 "assertion is always true, perhaps remove parentheses?";
2423 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2424 c->u->u_lineno, NULL, NULL) == -1)
2425 return 0;
2426 }
2427 VISIT(c, expr, s->v.Assert.test);
2428 end = compiler_new_block(c);
2429 if (end == NULL)
2430 return 0;
2431 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2432 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2433 if (s->v.Assert.msg) {
2434 VISIT(c, expr, s->v.Assert.msg);
2435 ADDOP_I(c, CALL_FUNCTION, 1);
2436 }
2437 ADDOP_I(c, RAISE_VARARGS, 1);
2438 compiler_use_next_block(c, end);
2439 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440}
2441
2442static int
2443compiler_visit_stmt(struct compiler *c, stmt_ty s)
2444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* Always assign a lineno to the next instruction for a stmt. */
2448 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002449 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 switch (s->kind) {
2453 case FunctionDef_kind:
2454 return compiler_function(c, s);
2455 case ClassDef_kind:
2456 return compiler_class(c, s);
2457 case Return_kind:
2458 if (c->u->u_ste->ste_type != FunctionBlock)
2459 return compiler_error(c, "'return' outside function");
2460 if (s->v.Return.value) {
2461 VISIT(c, expr, s->v.Return.value);
2462 }
2463 else
2464 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2465 ADDOP(c, RETURN_VALUE);
2466 break;
2467 case Delete_kind:
2468 VISIT_SEQ(c, expr, s->v.Delete.targets)
2469 break;
2470 case Assign_kind:
2471 n = asdl_seq_LEN(s->v.Assign.targets);
2472 VISIT(c, expr, s->v.Assign.value);
2473 for (i = 0; i < n; i++) {
2474 if (i < n - 1)
2475 ADDOP(c, DUP_TOP);
2476 VISIT(c, expr,
2477 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2478 }
2479 break;
2480 case AugAssign_kind:
2481 return compiler_augassign(c, s);
2482 case For_kind:
2483 return compiler_for(c, s);
2484 case While_kind:
2485 return compiler_while(c, s);
2486 case If_kind:
2487 return compiler_if(c, s);
2488 case Raise_kind:
2489 n = 0;
2490 if (s->v.Raise.exc) {
2491 VISIT(c, expr, s->v.Raise.exc);
2492 n++;
2493 if (s->v.Raise.cause) {
2494 VISIT(c, expr, s->v.Raise.cause);
2495 n++;
2496 }
2497 }
2498 ADDOP_I(c, RAISE_VARARGS, n);
2499 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002500 case Try_kind:
2501 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 case Assert_kind:
2503 return compiler_assert(c, s);
2504 case Import_kind:
2505 return compiler_import(c, s);
2506 case ImportFrom_kind:
2507 return compiler_from_import(c, s);
2508 case Global_kind:
2509 case Nonlocal_kind:
2510 break;
2511 case Expr_kind:
2512 if (c->c_interactive && c->c_nestlevel <= 1) {
2513 VISIT(c, expr, s->v.Expr.value);
2514 ADDOP(c, PRINT_EXPR);
2515 }
2516 else if (s->v.Expr.value->kind != Str_kind &&
2517 s->v.Expr.value->kind != Num_kind) {
2518 VISIT(c, expr, s->v.Expr.value);
2519 ADDOP(c, POP_TOP);
2520 }
2521 break;
2522 case Pass_kind:
2523 break;
2524 case Break_kind:
2525 if (!compiler_in_loop(c))
2526 return compiler_error(c, "'break' outside loop");
2527 ADDOP(c, BREAK_LOOP);
2528 break;
2529 case Continue_kind:
2530 return compiler_continue(c);
2531 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002532 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 }
2534 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535}
2536
2537static int
2538unaryop(unaryop_ty op)
2539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 switch (op) {
2541 case Invert:
2542 return UNARY_INVERT;
2543 case Not:
2544 return UNARY_NOT;
2545 case UAdd:
2546 return UNARY_POSITIVE;
2547 case USub:
2548 return UNARY_NEGATIVE;
2549 default:
2550 PyErr_Format(PyExc_SystemError,
2551 "unary op %d should not be possible", op);
2552 return 0;
2553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002554}
2555
2556static int
2557binop(struct compiler *c, operator_ty op)
2558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 switch (op) {
2560 case Add:
2561 return BINARY_ADD;
2562 case Sub:
2563 return BINARY_SUBTRACT;
2564 case Mult:
2565 return BINARY_MULTIPLY;
2566 case Div:
2567 return BINARY_TRUE_DIVIDE;
2568 case Mod:
2569 return BINARY_MODULO;
2570 case Pow:
2571 return BINARY_POWER;
2572 case LShift:
2573 return BINARY_LSHIFT;
2574 case RShift:
2575 return BINARY_RSHIFT;
2576 case BitOr:
2577 return BINARY_OR;
2578 case BitXor:
2579 return BINARY_XOR;
2580 case BitAnd:
2581 return BINARY_AND;
2582 case FloorDiv:
2583 return BINARY_FLOOR_DIVIDE;
2584 default:
2585 PyErr_Format(PyExc_SystemError,
2586 "binary op %d should not be possible", op);
2587 return 0;
2588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589}
2590
2591static int
2592cmpop(cmpop_ty op)
2593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 switch (op) {
2595 case Eq:
2596 return PyCmp_EQ;
2597 case NotEq:
2598 return PyCmp_NE;
2599 case Lt:
2600 return PyCmp_LT;
2601 case LtE:
2602 return PyCmp_LE;
2603 case Gt:
2604 return PyCmp_GT;
2605 case GtE:
2606 return PyCmp_GE;
2607 case Is:
2608 return PyCmp_IS;
2609 case IsNot:
2610 return PyCmp_IS_NOT;
2611 case In:
2612 return PyCmp_IN;
2613 case NotIn:
2614 return PyCmp_NOT_IN;
2615 default:
2616 return PyCmp_BAD;
2617 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618}
2619
2620static int
2621inplace_binop(struct compiler *c, operator_ty op)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 switch (op) {
2624 case Add:
2625 return INPLACE_ADD;
2626 case Sub:
2627 return INPLACE_SUBTRACT;
2628 case Mult:
2629 return INPLACE_MULTIPLY;
2630 case Div:
2631 return INPLACE_TRUE_DIVIDE;
2632 case Mod:
2633 return INPLACE_MODULO;
2634 case Pow:
2635 return INPLACE_POWER;
2636 case LShift:
2637 return INPLACE_LSHIFT;
2638 case RShift:
2639 return INPLACE_RSHIFT;
2640 case BitOr:
2641 return INPLACE_OR;
2642 case BitXor:
2643 return INPLACE_XOR;
2644 case BitAnd:
2645 return INPLACE_AND;
2646 case FloorDiv:
2647 return INPLACE_FLOOR_DIVIDE;
2648 default:
2649 PyErr_Format(PyExc_SystemError,
2650 "inplace binary op %d should not be possible", op);
2651 return 0;
2652 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653}
2654
2655static int
2656compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 int op, scope, arg;
2659 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 PyObject *dict = c->u->u_names;
2662 PyObject *mangled;
2663 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 mangled = _Py_Mangle(c->u->u_private, name);
2666 if (!mangled)
2667 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002668
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002669 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2670 PyUnicode_CompareWithASCIIString(name, "True") &&
2671 PyUnicode_CompareWithASCIIString(name, "False"));
2672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 op = 0;
2674 optype = OP_NAME;
2675 scope = PyST_GetScope(c->u->u_ste, mangled);
2676 switch (scope) {
2677 case FREE:
2678 dict = c->u->u_freevars;
2679 optype = OP_DEREF;
2680 break;
2681 case CELL:
2682 dict = c->u->u_cellvars;
2683 optype = OP_DEREF;
2684 break;
2685 case LOCAL:
2686 if (c->u->u_ste->ste_type == FunctionBlock)
2687 optype = OP_FAST;
2688 break;
2689 case GLOBAL_IMPLICIT:
2690 if (c->u->u_ste->ste_type == FunctionBlock &&
2691 !c->u->u_ste->ste_unoptimized)
2692 optype = OP_GLOBAL;
2693 break;
2694 case GLOBAL_EXPLICIT:
2695 optype = OP_GLOBAL;
2696 break;
2697 default:
2698 /* scope can be 0 */
2699 break;
2700 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002703 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 switch (optype) {
2706 case OP_DEREF:
2707 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002708 case Load:
2709 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2710 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 case Store: op = STORE_DEREF; break;
2712 case AugLoad:
2713 case AugStore:
2714 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002715 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 case Param:
2717 default:
2718 PyErr_SetString(PyExc_SystemError,
2719 "param invalid for deref variable");
2720 return 0;
2721 }
2722 break;
2723 case OP_FAST:
2724 switch (ctx) {
2725 case Load: op = LOAD_FAST; break;
2726 case Store: op = STORE_FAST; break;
2727 case Del: op = DELETE_FAST; break;
2728 case AugLoad:
2729 case AugStore:
2730 break;
2731 case Param:
2732 default:
2733 PyErr_SetString(PyExc_SystemError,
2734 "param invalid for local variable");
2735 return 0;
2736 }
2737 ADDOP_O(c, op, mangled, varnames);
2738 Py_DECREF(mangled);
2739 return 1;
2740 case OP_GLOBAL:
2741 switch (ctx) {
2742 case Load: op = LOAD_GLOBAL; break;
2743 case Store: op = STORE_GLOBAL; break;
2744 case Del: op = DELETE_GLOBAL; break;
2745 case AugLoad:
2746 case AugStore:
2747 break;
2748 case Param:
2749 default:
2750 PyErr_SetString(PyExc_SystemError,
2751 "param invalid for global variable");
2752 return 0;
2753 }
2754 break;
2755 case OP_NAME:
2756 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002757 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 case Store: op = STORE_NAME; break;
2759 case Del: op = DELETE_NAME; break;
2760 case AugLoad:
2761 case AugStore:
2762 break;
2763 case Param:
2764 default:
2765 PyErr_SetString(PyExc_SystemError,
2766 "param invalid for name variable");
2767 return 0;
2768 }
2769 break;
2770 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 assert(op);
2773 arg = compiler_add_o(c, dict, mangled);
2774 Py_DECREF(mangled);
2775 if (arg < 0)
2776 return 0;
2777 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778}
2779
2780static int
2781compiler_boolop(struct compiler *c, expr_ty e)
2782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 basicblock *end;
2784 int jumpi, i, n;
2785 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 assert(e->kind == BoolOp_kind);
2788 if (e->v.BoolOp.op == And)
2789 jumpi = JUMP_IF_FALSE_OR_POP;
2790 else
2791 jumpi = JUMP_IF_TRUE_OR_POP;
2792 end = compiler_new_block(c);
2793 if (end == NULL)
2794 return 0;
2795 s = e->v.BoolOp.values;
2796 n = asdl_seq_LEN(s) - 1;
2797 assert(n >= 0);
2798 for (i = 0; i < n; ++i) {
2799 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2800 ADDOP_JABS(c, jumpi, end);
2801 }
2802 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2803 compiler_use_next_block(c, end);
2804 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805}
2806
2807static int
2808compiler_list(struct compiler *c, expr_ty e)
2809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 int n = asdl_seq_LEN(e->v.List.elts);
2811 if (e->v.List.ctx == Store) {
2812 int i, seen_star = 0;
2813 for (i = 0; i < n; i++) {
2814 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2815 if (elt->kind == Starred_kind && !seen_star) {
2816 if ((i >= (1 << 8)) ||
2817 (n-i-1 >= (INT_MAX >> 8)))
2818 return compiler_error(c,
2819 "too many expressions in "
2820 "star-unpacking assignment");
2821 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2822 seen_star = 1;
2823 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2824 } else if (elt->kind == Starred_kind) {
2825 return compiler_error(c,
2826 "two starred expressions in assignment");
2827 }
2828 }
2829 if (!seen_star) {
2830 ADDOP_I(c, UNPACK_SEQUENCE, n);
2831 }
2832 }
2833 VISIT_SEQ(c, expr, e->v.List.elts);
2834 if (e->v.List.ctx == Load) {
2835 ADDOP_I(c, BUILD_LIST, n);
2836 }
2837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838}
2839
2840static int
2841compiler_tuple(struct compiler *c, expr_ty e)
2842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 int n = asdl_seq_LEN(e->v.Tuple.elts);
2844 if (e->v.Tuple.ctx == Store) {
2845 int i, seen_star = 0;
2846 for (i = 0; i < n; i++) {
2847 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2848 if (elt->kind == Starred_kind && !seen_star) {
2849 if ((i >= (1 << 8)) ||
2850 (n-i-1 >= (INT_MAX >> 8)))
2851 return compiler_error(c,
2852 "too many expressions in "
2853 "star-unpacking assignment");
2854 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2855 seen_star = 1;
2856 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2857 } else if (elt->kind == Starred_kind) {
2858 return compiler_error(c,
2859 "two starred expressions in assignment");
2860 }
2861 }
2862 if (!seen_star) {
2863 ADDOP_I(c, UNPACK_SEQUENCE, n);
2864 }
2865 }
2866 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2867 if (e->v.Tuple.ctx == Load) {
2868 ADDOP_I(c, BUILD_TUPLE, n);
2869 }
2870 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871}
2872
2873static int
2874compiler_compare(struct compiler *c, expr_ty e)
2875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 int i, n;
2877 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2880 VISIT(c, expr, e->v.Compare.left);
2881 n = asdl_seq_LEN(e->v.Compare.ops);
2882 assert(n > 0);
2883 if (n > 1) {
2884 cleanup = compiler_new_block(c);
2885 if (cleanup == NULL)
2886 return 0;
2887 VISIT(c, expr,
2888 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2889 }
2890 for (i = 1; i < n; i++) {
2891 ADDOP(c, DUP_TOP);
2892 ADDOP(c, ROT_THREE);
2893 ADDOP_I(c, COMPARE_OP,
2894 cmpop((cmpop_ty)(asdl_seq_GET(
2895 e->v.Compare.ops, i - 1))));
2896 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2897 NEXT_BLOCK(c);
2898 if (i < (n - 1))
2899 VISIT(c, expr,
2900 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2901 }
2902 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2903 ADDOP_I(c, COMPARE_OP,
2904 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2905 if (n > 1) {
2906 basicblock *end = compiler_new_block(c);
2907 if (end == NULL)
2908 return 0;
2909 ADDOP_JREL(c, JUMP_FORWARD, end);
2910 compiler_use_next_block(c, cleanup);
2911 ADDOP(c, ROT_TWO);
2912 ADDOP(c, POP_TOP);
2913 compiler_use_next_block(c, end);
2914 }
2915 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916}
2917
2918static int
2919compiler_call(struct compiler *c, expr_ty e)
2920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 VISIT(c, expr, e->v.Call.func);
2922 return compiler_call_helper(c, 0,
2923 e->v.Call.args,
2924 e->v.Call.keywords,
2925 e->v.Call.starargs,
2926 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002927}
2928
2929/* shared code between compiler_call and compiler_class */
2930static int
2931compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 int n, /* Args already pushed */
2933 asdl_seq *args,
2934 asdl_seq *keywords,
2935 expr_ty starargs,
2936 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 n += asdl_seq_LEN(args);
2941 VISIT_SEQ(c, expr, args);
2942 if (keywords) {
2943 VISIT_SEQ(c, keyword, keywords);
2944 n |= asdl_seq_LEN(keywords) << 8;
2945 }
2946 if (starargs) {
2947 VISIT(c, expr, starargs);
2948 code |= 1;
2949 }
2950 if (kwargs) {
2951 VISIT(c, expr, kwargs);
2952 code |= 2;
2953 }
2954 switch (code) {
2955 case 0:
2956 ADDOP_I(c, CALL_FUNCTION, n);
2957 break;
2958 case 1:
2959 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2960 break;
2961 case 2:
2962 ADDOP_I(c, CALL_FUNCTION_KW, n);
2963 break;
2964 case 3:
2965 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2966 break;
2967 }
2968 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969}
2970
Nick Coghlan650f0d02007-04-15 12:05:43 +00002971
2972/* List and set comprehensions and generator expressions work by creating a
2973 nested function to perform the actual iteration. This means that the
2974 iteration variables don't leak into the current scope.
2975 The defined function is called immediately following its definition, with the
2976 result of that call being the result of the expression.
2977 The LC/SC version returns the populated container, while the GE version is
2978 flagged in symtable.c as a generator, so it returns the generator object
2979 when the function is called.
2980 This code *knows* that the loop cannot contain break, continue, or return,
2981 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2982
2983 Possible cleanups:
2984 - iterate over the generator sequence instead of using recursion
2985*/
2986
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988compiler_comprehension_generator(struct compiler *c,
2989 asdl_seq *generators, int gen_index,
2990 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 /* generate code for the iterator, then each of the ifs,
2993 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 comprehension_ty gen;
2996 basicblock *start, *anchor, *skip, *if_cleanup;
2997 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 start = compiler_new_block(c);
3000 skip = compiler_new_block(c);
3001 if_cleanup = compiler_new_block(c);
3002 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3005 anchor == NULL)
3006 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 if (gen_index == 0) {
3011 /* Receive outermost iter as an implicit argument */
3012 c->u->u_argcount = 1;
3013 ADDOP_I(c, LOAD_FAST, 0);
3014 }
3015 else {
3016 /* Sub-iter - calculate on the fly */
3017 VISIT(c, expr, gen->iter);
3018 ADDOP(c, GET_ITER);
3019 }
3020 compiler_use_next_block(c, start);
3021 ADDOP_JREL(c, FOR_ITER, anchor);
3022 NEXT_BLOCK(c);
3023 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 /* XXX this needs to be cleaned up...a lot! */
3026 n = asdl_seq_LEN(gen->ifs);
3027 for (i = 0; i < n; i++) {
3028 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3029 VISIT(c, expr, e);
3030 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3031 NEXT_BLOCK(c);
3032 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 if (++gen_index < asdl_seq_LEN(generators))
3035 if (!compiler_comprehension_generator(c,
3036 generators, gen_index,
3037 elt, val, type))
3038 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 /* only append after the last for generator */
3041 if (gen_index >= asdl_seq_LEN(generators)) {
3042 /* comprehension specific code */
3043 switch (type) {
3044 case COMP_GENEXP:
3045 VISIT(c, expr, elt);
3046 ADDOP(c, YIELD_VALUE);
3047 ADDOP(c, POP_TOP);
3048 break;
3049 case COMP_LISTCOMP:
3050 VISIT(c, expr, elt);
3051 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3052 break;
3053 case COMP_SETCOMP:
3054 VISIT(c, expr, elt);
3055 ADDOP_I(c, SET_ADD, gen_index + 1);
3056 break;
3057 case COMP_DICTCOMP:
3058 /* With 'd[k] = v', v is evaluated before k, so we do
3059 the same. */
3060 VISIT(c, expr, val);
3061 VISIT(c, expr, elt);
3062 ADDOP_I(c, MAP_ADD, gen_index + 1);
3063 break;
3064 default:
3065 return 0;
3066 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 compiler_use_next_block(c, skip);
3069 }
3070 compiler_use_next_block(c, if_cleanup);
3071 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3072 compiler_use_next_block(c, anchor);
3073
3074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075}
3076
3077static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003078compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 PyCodeObject *co = NULL;
3082 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003083 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 outermost_iter = ((comprehension_ty)
3086 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003087
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003088 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3089 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 if (type != COMP_GENEXP) {
3093 int op;
3094 switch (type) {
3095 case COMP_LISTCOMP:
3096 op = BUILD_LIST;
3097 break;
3098 case COMP_SETCOMP:
3099 op = BUILD_SET;
3100 break;
3101 case COMP_DICTCOMP:
3102 op = BUILD_MAP;
3103 break;
3104 default:
3105 PyErr_Format(PyExc_SystemError,
3106 "unknown comprehension type %d", type);
3107 goto error_in_scope;
3108 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 ADDOP_I(c, op, 0);
3111 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 if (!compiler_comprehension_generator(c, generators, 0, elt,
3114 val, type))
3115 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 if (type != COMP_GENEXP) {
3118 ADDOP(c, RETURN_VALUE);
3119 }
3120
3121 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003122 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003124 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 goto error;
3126
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003127 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003129 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 Py_DECREF(co);
3131
3132 VISIT(c, expr, outermost_iter);
3133 ADDOP(c, GET_ITER);
3134 ADDOP_I(c, CALL_FUNCTION, 1);
3135 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003136error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003138error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003139 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 Py_XDECREF(co);
3141 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003142}
3143
3144static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145compiler_genexp(struct compiler *c, expr_ty e)
3146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 static identifier name;
3148 if (!name) {
3149 name = PyUnicode_FromString("<genexpr>");
3150 if (!name)
3151 return 0;
3152 }
3153 assert(e->kind == GeneratorExp_kind);
3154 return compiler_comprehension(c, e, COMP_GENEXP, name,
3155 e->v.GeneratorExp.generators,
3156 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157}
3158
3159static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003160compiler_listcomp(struct compiler *c, expr_ty e)
3161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 static identifier name;
3163 if (!name) {
3164 name = PyUnicode_FromString("<listcomp>");
3165 if (!name)
3166 return 0;
3167 }
3168 assert(e->kind == ListComp_kind);
3169 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3170 e->v.ListComp.generators,
3171 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003172}
3173
3174static int
3175compiler_setcomp(struct compiler *c, expr_ty e)
3176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 static identifier name;
3178 if (!name) {
3179 name = PyUnicode_FromString("<setcomp>");
3180 if (!name)
3181 return 0;
3182 }
3183 assert(e->kind == SetComp_kind);
3184 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3185 e->v.SetComp.generators,
3186 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003187}
3188
3189
3190static int
3191compiler_dictcomp(struct compiler *c, expr_ty e)
3192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 static identifier name;
3194 if (!name) {
3195 name = PyUnicode_FromString("<dictcomp>");
3196 if (!name)
3197 return 0;
3198 }
3199 assert(e->kind == DictComp_kind);
3200 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3201 e->v.DictComp.generators,
3202 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003203}
3204
3205
3206static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207compiler_visit_keyword(struct compiler *c, keyword_ty k)
3208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3210 VISIT(c, expr, k->value);
3211 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212}
3213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003215 whether they are true or false.
3216
3217 Return values: 1 for true, 0 for false, -1 for non-constant.
3218 */
3219
3220static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003221expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 char *id;
3224 switch (e->kind) {
3225 case Ellipsis_kind:
3226 return 1;
3227 case Num_kind:
3228 return PyObject_IsTrue(e->v.Num.n);
3229 case Str_kind:
3230 return PyObject_IsTrue(e->v.Str.s);
3231 case Name_kind:
3232 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003233 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003234 if (id && strcmp(id, "__debug__") == 0)
3235 return !c->c_optimize;
3236 return -1;
3237 case NameConstant_kind: {
3238 PyObject *o = e->v.NameConstant.value;
3239 if (o == Py_None)
3240 return 0;
3241 else if (o == Py_True)
3242 return 1;
3243 else if (o == Py_False)
3244 return 0;
3245 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 default:
3247 return -1;
3248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249}
3250
Guido van Rossumc2e20742006-02-27 22:32:47 +00003251/*
3252 Implements the with statement from PEP 343.
3253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003255
3256 with EXPR as VAR:
3257 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258
Guido van Rossumc2e20742006-02-27 22:32:47 +00003259 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260
Thomas Wouters477c8d52006-05-27 19:21:47 +00003261 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003262 exit = context.__exit__ # not calling it
3263 value = context.__enter__()
3264 try:
3265 VAR = value # if VAR present in the syntax
3266 BLOCK
3267 finally:
3268 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003270 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003272 exit(*exc)
3273 */
3274static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003275compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003276{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003277 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003278 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003279
3280 assert(s->kind == With_kind);
3281
Guido van Rossumc2e20742006-02-27 22:32:47 +00003282 block = compiler_new_block(c);
3283 finally = compiler_new_block(c);
3284 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003285 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003286
Thomas Wouters477c8d52006-05-27 19:21:47 +00003287 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003288 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003289 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003290
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003291 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003292 compiler_use_next_block(c, block);
3293 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003294 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003295 }
3296
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003297 if (item->optional_vars) {
3298 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003299 }
3300 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003302 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003303 }
3304
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003305 pos++;
3306 if (pos == asdl_seq_LEN(s->v.With.items))
3307 /* BLOCK code */
3308 VISIT_SEQ(c, stmt, s->v.With.body)
3309 else if (!compiler_with(c, s, pos))
3310 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003311
3312 /* End of try block; start the finally block */
3313 ADDOP(c, POP_BLOCK);
3314 compiler_pop_fblock(c, FINALLY_TRY, block);
3315
3316 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3317 compiler_use_next_block(c, finally);
3318 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003319 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003320
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003321 /* Finally block starts; context.__exit__ is on the stack under
3322 the exception or return information. Just issue our magic
3323 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003324 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003325
3326 /* Finally block ends. */
3327 ADDOP(c, END_FINALLY);
3328 compiler_pop_fblock(c, FINALLY_END, finally);
3329 return 1;
3330}
3331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332static int
3333compiler_visit_expr(struct compiler *c, expr_ty e)
3334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 /* If expr e has a different line number than the last expr/stmt,
3338 set a new line number for the next instruction.
3339 */
3340 if (e->lineno > c->u->u_lineno) {
3341 c->u->u_lineno = e->lineno;
3342 c->u->u_lineno_set = 0;
3343 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003344 /* Updating the column offset is always harmless. */
3345 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 switch (e->kind) {
3347 case BoolOp_kind:
3348 return compiler_boolop(c, e);
3349 case BinOp_kind:
3350 VISIT(c, expr, e->v.BinOp.left);
3351 VISIT(c, expr, e->v.BinOp.right);
3352 ADDOP(c, binop(c, e->v.BinOp.op));
3353 break;
3354 case UnaryOp_kind:
3355 VISIT(c, expr, e->v.UnaryOp.operand);
3356 ADDOP(c, unaryop(e->v.UnaryOp.op));
3357 break;
3358 case Lambda_kind:
3359 return compiler_lambda(c, e);
3360 case IfExp_kind:
3361 return compiler_ifexp(c, e);
3362 case Dict_kind:
3363 n = asdl_seq_LEN(e->v.Dict.values);
3364 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3365 for (i = 0; i < n; i++) {
3366 VISIT(c, expr,
3367 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3368 VISIT(c, expr,
3369 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3370 ADDOP(c, STORE_MAP);
3371 }
3372 break;
3373 case Set_kind:
3374 n = asdl_seq_LEN(e->v.Set.elts);
3375 VISIT_SEQ(c, expr, e->v.Set.elts);
3376 ADDOP_I(c, BUILD_SET, n);
3377 break;
3378 case GeneratorExp_kind:
3379 return compiler_genexp(c, e);
3380 case ListComp_kind:
3381 return compiler_listcomp(c, e);
3382 case SetComp_kind:
3383 return compiler_setcomp(c, e);
3384 case DictComp_kind:
3385 return compiler_dictcomp(c, e);
3386 case Yield_kind:
3387 if (c->u->u_ste->ste_type != FunctionBlock)
3388 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003389 if (e->v.Yield.value) {
3390 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 }
3392 else {
3393 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3394 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003395 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003397 case YieldFrom_kind:
3398 if (c->u->u_ste->ste_type != FunctionBlock)
3399 return compiler_error(c, "'yield' outside function");
3400 VISIT(c, expr, e->v.YieldFrom.value);
3401 ADDOP(c, GET_ITER);
3402 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3403 ADDOP(c, YIELD_FROM);
3404 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 case Compare_kind:
3406 return compiler_compare(c, e);
3407 case Call_kind:
3408 return compiler_call(c, e);
3409 case Num_kind:
3410 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3411 break;
3412 case Str_kind:
3413 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3414 break;
3415 case Bytes_kind:
3416 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3417 break;
3418 case Ellipsis_kind:
3419 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3420 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003421 case NameConstant_kind:
3422 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3423 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 /* The following exprs can be assignment targets. */
3425 case Attribute_kind:
3426 if (e->v.Attribute.ctx != AugStore)
3427 VISIT(c, expr, e->v.Attribute.value);
3428 switch (e->v.Attribute.ctx) {
3429 case AugLoad:
3430 ADDOP(c, DUP_TOP);
3431 /* Fall through to load */
3432 case Load:
3433 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3434 break;
3435 case AugStore:
3436 ADDOP(c, ROT_TWO);
3437 /* Fall through to save */
3438 case Store:
3439 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3440 break;
3441 case Del:
3442 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3443 break;
3444 case Param:
3445 default:
3446 PyErr_SetString(PyExc_SystemError,
3447 "param invalid in attribute expression");
3448 return 0;
3449 }
3450 break;
3451 case Subscript_kind:
3452 switch (e->v.Subscript.ctx) {
3453 case AugLoad:
3454 VISIT(c, expr, e->v.Subscript.value);
3455 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3456 break;
3457 case Load:
3458 VISIT(c, expr, e->v.Subscript.value);
3459 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3460 break;
3461 case AugStore:
3462 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3463 break;
3464 case Store:
3465 VISIT(c, expr, e->v.Subscript.value);
3466 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3467 break;
3468 case Del:
3469 VISIT(c, expr, e->v.Subscript.value);
3470 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3471 break;
3472 case Param:
3473 default:
3474 PyErr_SetString(PyExc_SystemError,
3475 "param invalid in subscript expression");
3476 return 0;
3477 }
3478 break;
3479 case Starred_kind:
3480 switch (e->v.Starred.ctx) {
3481 case Store:
3482 /* In all legitimate cases, the Starred node was already replaced
3483 * by compiler_list/compiler_tuple. XXX: is that okay? */
3484 return compiler_error(c,
3485 "starred assignment target must be in a list or tuple");
3486 default:
3487 return compiler_error(c,
3488 "can use starred expression only as assignment target");
3489 }
3490 break;
3491 case Name_kind:
3492 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3493 /* child nodes of List and Tuple will have expr_context set */
3494 case List_kind:
3495 return compiler_list(c, e);
3496 case Tuple_kind:
3497 return compiler_tuple(c, e);
3498 }
3499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500}
3501
3502static int
3503compiler_augassign(struct compiler *c, stmt_ty s)
3504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 expr_ty e = s->v.AugAssign.target;
3506 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 switch (e->kind) {
3511 case Attribute_kind:
3512 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3513 AugLoad, e->lineno, e->col_offset, c->c_arena);
3514 if (auge == NULL)
3515 return 0;
3516 VISIT(c, expr, auge);
3517 VISIT(c, expr, s->v.AugAssign.value);
3518 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3519 auge->v.Attribute.ctx = AugStore;
3520 VISIT(c, expr, auge);
3521 break;
3522 case Subscript_kind:
3523 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3524 AugLoad, e->lineno, e->col_offset, c->c_arena);
3525 if (auge == NULL)
3526 return 0;
3527 VISIT(c, expr, auge);
3528 VISIT(c, expr, s->v.AugAssign.value);
3529 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3530 auge->v.Subscript.ctx = AugStore;
3531 VISIT(c, expr, auge);
3532 break;
3533 case Name_kind:
3534 if (!compiler_nameop(c, e->v.Name.id, Load))
3535 return 0;
3536 VISIT(c, expr, s->v.AugAssign.value);
3537 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3538 return compiler_nameop(c, e->v.Name.id, Store);
3539 default:
3540 PyErr_Format(PyExc_SystemError,
3541 "invalid node type (%d) for augmented assignment",
3542 e->kind);
3543 return 0;
3544 }
3545 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546}
3547
3548static int
3549compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 struct fblockinfo *f;
3552 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3553 PyErr_SetString(PyExc_SystemError,
3554 "too many statically nested blocks");
3555 return 0;
3556 }
3557 f = &c->u->u_fblock[c->u->u_nfblocks++];
3558 f->fb_type = t;
3559 f->fb_block = b;
3560 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561}
3562
3563static void
3564compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 struct compiler_unit *u = c->u;
3567 assert(u->u_nfblocks > 0);
3568 u->u_nfblocks--;
3569 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3570 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571}
3572
Thomas Wouters89f507f2006-12-13 04:49:30 +00003573static int
3574compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 int i;
3576 struct compiler_unit *u = c->u;
3577 for (i = 0; i < u->u_nfblocks; ++i) {
3578 if (u->u_fblock[i].fb_type == LOOP)
3579 return 1;
3580 }
3581 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003582}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583/* Raises a SyntaxError and returns 0.
3584 If something goes wrong, a different exception may be raised.
3585*/
3586
3587static int
3588compiler_error(struct compiler *c, const char *errstr)
3589{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003590 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3594 if (!loc) {
3595 Py_INCREF(Py_None);
3596 loc = Py_None;
3597 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003598 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003599 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 if (!u)
3601 goto exit;
3602 v = Py_BuildValue("(zO)", errstr, u);
3603 if (!v)
3604 goto exit;
3605 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 Py_DECREF(loc);
3608 Py_XDECREF(u);
3609 Py_XDECREF(v);
3610 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611}
3612
3613static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614compiler_handle_subscr(struct compiler *c, const char *kind,
3615 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 /* XXX this code is duplicated */
3620 switch (ctx) {
3621 case AugLoad: /* fall through to Load */
3622 case Load: op = BINARY_SUBSCR; break;
3623 case AugStore:/* fall through to Store */
3624 case Store: op = STORE_SUBSCR; break;
3625 case Del: op = DELETE_SUBSCR; break;
3626 case Param:
3627 PyErr_Format(PyExc_SystemError,
3628 "invalid %s kind %d in subscript\n",
3629 kind, ctx);
3630 return 0;
3631 }
3632 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003633 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 }
3635 else if (ctx == AugStore) {
3636 ADDOP(c, ROT_THREE);
3637 }
3638 ADDOP(c, op);
3639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640}
3641
3642static int
3643compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 int n = 2;
3646 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 /* only handles the cases where BUILD_SLICE is emitted */
3649 if (s->v.Slice.lower) {
3650 VISIT(c, expr, s->v.Slice.lower);
3651 }
3652 else {
3653 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3654 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 if (s->v.Slice.upper) {
3657 VISIT(c, expr, s->v.Slice.upper);
3658 }
3659 else {
3660 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3661 }
3662
3663 if (s->v.Slice.step) {
3664 n++;
3665 VISIT(c, expr, s->v.Slice.step);
3666 }
3667 ADDOP_I(c, BUILD_SLICE, n);
3668 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669}
3670
3671static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3673 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 switch (s->kind) {
3676 case Slice_kind:
3677 return compiler_slice(c, s, ctx);
3678 case Index_kind:
3679 VISIT(c, expr, s->v.Index.value);
3680 break;
3681 case ExtSlice_kind:
3682 default:
3683 PyErr_SetString(PyExc_SystemError,
3684 "extended slice invalid in nested slice");
3685 return 0;
3686 }
3687 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688}
3689
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690static int
3691compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 char * kindname = NULL;
3694 switch (s->kind) {
3695 case Index_kind:
3696 kindname = "index";
3697 if (ctx != AugStore) {
3698 VISIT(c, expr, s->v.Index.value);
3699 }
3700 break;
3701 case Slice_kind:
3702 kindname = "slice";
3703 if (ctx != AugStore) {
3704 if (!compiler_slice(c, s, ctx))
3705 return 0;
3706 }
3707 break;
3708 case ExtSlice_kind:
3709 kindname = "extended slice";
3710 if (ctx != AugStore) {
3711 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3712 for (i = 0; i < n; i++) {
3713 slice_ty sub = (slice_ty)asdl_seq_GET(
3714 s->v.ExtSlice.dims, i);
3715 if (!compiler_visit_nested_slice(c, sub, ctx))
3716 return 0;
3717 }
3718 ADDOP_I(c, BUILD_TUPLE, n);
3719 }
3720 break;
3721 default:
3722 PyErr_Format(PyExc_SystemError,
3723 "invalid subscript kind %d", s->kind);
3724 return 0;
3725 }
3726 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727}
3728
Thomas Wouters89f507f2006-12-13 04:49:30 +00003729/* End of the compiler section, beginning of the assembler section */
3730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731/* do depth-first search of basic block graph, starting with block.
3732 post records the block indices in post-order.
3733
3734 XXX must handle implicit jumps from one block to next
3735*/
3736
Thomas Wouters89f507f2006-12-13 04:49:30 +00003737struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 PyObject *a_bytecode; /* string containing bytecode */
3739 int a_offset; /* offset into bytecode */
3740 int a_nblocks; /* number of reachable blocks */
3741 basicblock **a_postorder; /* list of blocks in dfs postorder */
3742 PyObject *a_lnotab; /* string containing lnotab */
3743 int a_lnotab_off; /* offset into lnotab */
3744 int a_lineno; /* last lineno of emitted instruction */
3745 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003746};
3747
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748static void
3749dfs(struct compiler *c, basicblock *b, struct assembler *a)
3750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 int i;
3752 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 if (b->b_seen)
3755 return;
3756 b->b_seen = 1;
3757 if (b->b_next != NULL)
3758 dfs(c, b->b_next, a);
3759 for (i = 0; i < b->b_iused; i++) {
3760 instr = &b->b_instr[i];
3761 if (instr->i_jrel || instr->i_jabs)
3762 dfs(c, instr->i_target, a);
3763 }
3764 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765}
3766
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003767static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 int i, target_depth;
3771 struct instr *instr;
3772 if (b->b_seen || b->b_startdepth >= depth)
3773 return maxdepth;
3774 b->b_seen = 1;
3775 b->b_startdepth = depth;
3776 for (i = 0; i < b->b_iused; i++) {
3777 instr = &b->b_instr[i];
3778 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3779 if (depth > maxdepth)
3780 maxdepth = depth;
3781 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3782 if (instr->i_jrel || instr->i_jabs) {
3783 target_depth = depth;
3784 if (instr->i_opcode == FOR_ITER) {
3785 target_depth = depth-2;
3786 } else if (instr->i_opcode == SETUP_FINALLY ||
3787 instr->i_opcode == SETUP_EXCEPT) {
3788 target_depth = depth+3;
3789 if (target_depth > maxdepth)
3790 maxdepth = target_depth;
3791 }
3792 maxdepth = stackdepth_walk(c, instr->i_target,
3793 target_depth, maxdepth);
3794 if (instr->i_opcode == JUMP_ABSOLUTE ||
3795 instr->i_opcode == JUMP_FORWARD) {
3796 goto out; /* remaining code is dead */
3797 }
3798 }
3799 }
3800 if (b->b_next)
3801 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 b->b_seen = 0;
3804 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805}
3806
3807/* Find the flow path that needs the largest stack. We assume that
3808 * cycles in the flow graph have no net effect on the stack depth.
3809 */
3810static int
3811stackdepth(struct compiler *c)
3812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 basicblock *b, *entryblock;
3814 entryblock = NULL;
3815 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3816 b->b_seen = 0;
3817 b->b_startdepth = INT_MIN;
3818 entryblock = b;
3819 }
3820 if (!entryblock)
3821 return 0;
3822 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003823}
3824
3825static int
3826assemble_init(struct assembler *a, int nblocks, int firstlineno)
3827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 memset(a, 0, sizeof(struct assembler));
3829 a->a_lineno = firstlineno;
3830 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3831 if (!a->a_bytecode)
3832 return 0;
3833 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3834 if (!a->a_lnotab)
3835 return 0;
3836 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3837 PyErr_NoMemory();
3838 return 0;
3839 }
3840 a->a_postorder = (basicblock **)PyObject_Malloc(
3841 sizeof(basicblock *) * nblocks);
3842 if (!a->a_postorder) {
3843 PyErr_NoMemory();
3844 return 0;
3845 }
3846 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847}
3848
3849static void
3850assemble_free(struct assembler *a)
3851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 Py_XDECREF(a->a_bytecode);
3853 Py_XDECREF(a->a_lnotab);
3854 if (a->a_postorder)
3855 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003856}
3857
3858/* Return the size of a basic block in bytes. */
3859
3860static int
3861instrsize(struct instr *instr)
3862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 if (!instr->i_hasarg)
3864 return 1; /* 1 byte for the opcode*/
3865 if (instr->i_oparg > 0xffff)
3866 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3867 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868}
3869
3870static int
3871blocksize(basicblock *b)
3872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 int i;
3874 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 for (i = 0; i < b->b_iused; i++)
3877 size += instrsize(&b->b_instr[i]);
3878 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003879}
3880
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003881/* Appends a pair to the end of the line number table, a_lnotab, representing
3882 the instruction's bytecode offset and line number. See
3883 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003884
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003885static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 int d_bytecode, d_lineno;
3889 int len;
3890 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 d_bytecode = a->a_offset - a->a_lineno_off;
3893 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 assert(d_bytecode >= 0);
3896 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 if(d_bytecode == 0 && d_lineno == 0)
3899 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 if (d_bytecode > 255) {
3902 int j, nbytes, ncodes = d_bytecode / 255;
3903 nbytes = a->a_lnotab_off + 2 * ncodes;
3904 len = PyBytes_GET_SIZE(a->a_lnotab);
3905 if (nbytes >= len) {
3906 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3907 len = nbytes;
3908 else if (len <= INT_MAX / 2)
3909 len *= 2;
3910 else {
3911 PyErr_NoMemory();
3912 return 0;
3913 }
3914 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3915 return 0;
3916 }
3917 lnotab = (unsigned char *)
3918 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3919 for (j = 0; j < ncodes; j++) {
3920 *lnotab++ = 255;
3921 *lnotab++ = 0;
3922 }
3923 d_bytecode -= ncodes * 255;
3924 a->a_lnotab_off += ncodes * 2;
3925 }
3926 assert(d_bytecode <= 255);
3927 if (d_lineno > 255) {
3928 int j, nbytes, ncodes = d_lineno / 255;
3929 nbytes = a->a_lnotab_off + 2 * ncodes;
3930 len = PyBytes_GET_SIZE(a->a_lnotab);
3931 if (nbytes >= len) {
3932 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3933 len = nbytes;
3934 else if (len <= INT_MAX / 2)
3935 len *= 2;
3936 else {
3937 PyErr_NoMemory();
3938 return 0;
3939 }
3940 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3941 return 0;
3942 }
3943 lnotab = (unsigned char *)
3944 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3945 *lnotab++ = d_bytecode;
3946 *lnotab++ = 255;
3947 d_bytecode = 0;
3948 for (j = 1; j < ncodes; j++) {
3949 *lnotab++ = 0;
3950 *lnotab++ = 255;
3951 }
3952 d_lineno -= ncodes * 255;
3953 a->a_lnotab_off += ncodes * 2;
3954 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 len = PyBytes_GET_SIZE(a->a_lnotab);
3957 if (a->a_lnotab_off + 2 >= len) {
3958 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3959 return 0;
3960 }
3961 lnotab = (unsigned char *)
3962 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 a->a_lnotab_off += 2;
3965 if (d_bytecode) {
3966 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003967 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 }
3969 else { /* First line of a block; def stmt, etc. */
3970 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003971 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 }
3973 a->a_lineno = i->i_lineno;
3974 a->a_lineno_off = a->a_offset;
3975 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003976}
3977
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003978/* assemble_emit()
3979 Extend the bytecode with a new instruction.
3980 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003981*/
3982
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003983static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003984assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 int size, arg = 0, ext = 0;
3987 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3988 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 size = instrsize(i);
3991 if (i->i_hasarg) {
3992 arg = i->i_oparg;
3993 ext = arg >> 16;
3994 }
3995 if (i->i_lineno && !assemble_lnotab(a, i))
3996 return 0;
3997 if (a->a_offset + size >= len) {
3998 if (len > PY_SSIZE_T_MAX / 2)
3999 return 0;
4000 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4001 return 0;
4002 }
4003 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4004 a->a_offset += size;
4005 if (size == 6) {
4006 assert(i->i_hasarg);
4007 *code++ = (char)EXTENDED_ARG;
4008 *code++ = ext & 0xff;
4009 *code++ = ext >> 8;
4010 arg &= 0xffff;
4011 }
4012 *code++ = i->i_opcode;
4013 if (i->i_hasarg) {
4014 assert(size == 3 || size == 6);
4015 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004016 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 }
4018 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004019}
4020
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004021static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004022assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 basicblock *b;
4025 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4026 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 /* Compute the size of each block and fixup jump args.
4029 Replace block pointer with position in bytecode. */
4030 do {
4031 totsize = 0;
4032 for (i = a->a_nblocks - 1; i >= 0; i--) {
4033 b = a->a_postorder[i];
4034 bsize = blocksize(b);
4035 b->b_offset = totsize;
4036 totsize += bsize;
4037 }
4038 last_extended_arg_count = extended_arg_count;
4039 extended_arg_count = 0;
4040 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4041 bsize = b->b_offset;
4042 for (i = 0; i < b->b_iused; i++) {
4043 struct instr *instr = &b->b_instr[i];
4044 /* Relative jumps are computed relative to
4045 the instruction pointer after fetching
4046 the jump instruction.
4047 */
4048 bsize += instrsize(instr);
4049 if (instr->i_jabs)
4050 instr->i_oparg = instr->i_target->b_offset;
4051 else if (instr->i_jrel) {
4052 int delta = instr->i_target->b_offset - bsize;
4053 instr->i_oparg = delta;
4054 }
4055 else
4056 continue;
4057 if (instr->i_oparg > 0xffff)
4058 extended_arg_count++;
4059 }
4060 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 /* XXX: This is an awful hack that could hurt performance, but
4063 on the bright side it should work until we come up
4064 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 The issue is that in the first loop blocksize() is called
4067 which calls instrsize() which requires i_oparg be set
4068 appropriately. There is a bootstrap problem because
4069 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 So we loop until we stop seeing new EXTENDED_ARGs.
4072 The only EXTENDED_ARGs that could be popping up are
4073 ones in jump instructions. So this should converge
4074 fairly quickly.
4075 */
4076 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004077}
4078
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004079static PyObject *
4080dict_keys_inorder(PyObject *dict, int offset)
4081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 PyObject *tuple, *k, *v;
4083 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 tuple = PyTuple_New(size);
4086 if (tuple == NULL)
4087 return NULL;
4088 while (PyDict_Next(dict, &pos, &k, &v)) {
4089 i = PyLong_AS_LONG(v);
4090 /* The keys of the dictionary are tuples. (see compiler_add_o)
4091 The object we want is always first, though. */
4092 k = PyTuple_GET_ITEM(k, 0);
4093 Py_INCREF(k);
4094 assert((i - offset) < size);
4095 assert((i - offset) >= 0);
4096 PyTuple_SET_ITEM(tuple, i - offset, k);
4097 }
4098 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004099}
4100
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004101static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004102compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 PySTEntryObject *ste = c->u->u_ste;
4105 int flags = 0, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004107 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 if (!ste->ste_unoptimized)
4109 flags |= CO_OPTIMIZED;
4110 if (ste->ste_nested)
4111 flags |= CO_NESTED;
4112 if (ste->ste_generator)
4113 flags |= CO_GENERATOR;
4114 if (ste->ste_varargs)
4115 flags |= CO_VARARGS;
4116 if (ste->ste_varkeywords)
4117 flags |= CO_VARKEYWORDS;
4118 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 /* (Only) inherit compilerflags in PyCF_MASK */
4121 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 n = PyDict_Size(c->u->u_freevars);
4124 if (n < 0)
4125 return -1;
4126 if (n == 0) {
4127 n = PyDict_Size(c->u->u_cellvars);
4128 if (n < 0)
4129 return -1;
4130 if (n == 0) {
4131 flags |= CO_NOFREE;
4132 }
4133 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004136}
4137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138static PyCodeObject *
4139makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 PyObject *tmp;
4142 PyCodeObject *co = NULL;
4143 PyObject *consts = NULL;
4144 PyObject *names = NULL;
4145 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 PyObject *name = NULL;
4147 PyObject *freevars = NULL;
4148 PyObject *cellvars = NULL;
4149 PyObject *bytecode = NULL;
4150 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 tmp = dict_keys_inorder(c->u->u_consts, 0);
4153 if (!tmp)
4154 goto error;
4155 consts = PySequence_List(tmp); /* optimize_code requires a list */
4156 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 names = dict_keys_inorder(c->u->u_names, 0);
4159 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4160 if (!consts || !names || !varnames)
4161 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4164 if (!cellvars)
4165 goto error;
4166 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4167 if (!freevars)
4168 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 nlocals = PyDict_Size(c->u->u_varnames);
4170 flags = compute_code_flags(c);
4171 if (flags < 0)
4172 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4175 if (!bytecode)
4176 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4179 if (!tmp)
4180 goto error;
4181 Py_DECREF(consts);
4182 consts = tmp;
4183
4184 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4185 nlocals, stackdepth(c), flags,
4186 bytecode, consts, names, varnames,
4187 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004188 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 c->u->u_firstlineno,
4190 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 Py_XDECREF(consts);
4193 Py_XDECREF(names);
4194 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 Py_XDECREF(name);
4196 Py_XDECREF(freevars);
4197 Py_XDECREF(cellvars);
4198 Py_XDECREF(bytecode);
4199 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004200}
4201
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004202
4203/* For debugging purposes only */
4204#if 0
4205static void
4206dump_instr(const struct instr *i)
4207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 const char *jrel = i->i_jrel ? "jrel " : "";
4209 const char *jabs = i->i_jabs ? "jabs " : "";
4210 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 *arg = '\0';
4213 if (i->i_hasarg)
4214 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4217 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004218}
4219
4220static void
4221dump_basicblock(const basicblock *b)
4222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 const char *seen = b->b_seen ? "seen " : "";
4224 const char *b_return = b->b_return ? "return " : "";
4225 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4226 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4227 if (b->b_instr) {
4228 int i;
4229 for (i = 0; i < b->b_iused; i++) {
4230 fprintf(stderr, " [%02d] ", i);
4231 dump_instr(b->b_instr + i);
4232 }
4233 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004234}
4235#endif
4236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004237static PyCodeObject *
4238assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 basicblock *b, *entryblock;
4241 struct assembler a;
4242 int i, j, nblocks;
4243 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 /* Make sure every block that falls off the end returns None.
4246 XXX NEXT_BLOCK() isn't quite right, because if the last
4247 block ends with a jump or return b_next shouldn't set.
4248 */
4249 if (!c->u->u_curblock->b_return) {
4250 NEXT_BLOCK(c);
4251 if (addNone)
4252 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4253 ADDOP(c, RETURN_VALUE);
4254 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 nblocks = 0;
4257 entryblock = NULL;
4258 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4259 nblocks++;
4260 entryblock = b;
4261 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 /* Set firstlineno if it wasn't explicitly set. */
4264 if (!c->u->u_firstlineno) {
4265 if (entryblock && entryblock->b_instr)
4266 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4267 else
4268 c->u->u_firstlineno = 1;
4269 }
4270 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4271 goto error;
4272 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 /* Can't modify the bytecode after computing jump offsets. */
4275 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 /* Emit code in reverse postorder from dfs. */
4278 for (i = a.a_nblocks - 1; i >= 0; i--) {
4279 b = a.a_postorder[i];
4280 for (j = 0; j < b->b_iused; j++)
4281 if (!assemble_emit(&a, &b->b_instr[j]))
4282 goto error;
4283 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4286 goto error;
4287 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4288 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 assemble_free(&a);
4293 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004294}
Georg Brandl8334fd92010-12-04 10:26:46 +00004295
4296#undef PyAST_Compile
4297PyAPI_FUNC(PyCodeObject *)
4298PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4299 PyArena *arena)
4300{
4301 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4302}
4303
4304