blob: d11e3abeaa4ca2fc9f1b743039ea03bdc2a72926 [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);
Victor Stinner6b64a682013-07-11 22:50:45 +02002319 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002320 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002321 if (tmp == NULL)
2322 return 0;
2323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002325 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 Py_DECREF(tmp);
2327 }
2328 if (!r)
2329 return r;
2330 }
2331 }
2332 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333}
2334
2335static int
2336compiler_from_import(struct compiler *c, stmt_ty s)
2337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 PyObject *names = PyTuple_New(n);
2341 PyObject *level;
2342 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (!empty_string) {
2345 empty_string = PyUnicode_FromString("");
2346 if (!empty_string)
2347 return 0;
2348 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (!names)
2351 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 level = PyLong_FromLong(s->v.ImportFrom.level);
2354 if (!level) {
2355 Py_DECREF(names);
2356 return 0;
2357 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* build up the names */
2360 for (i = 0; i < n; i++) {
2361 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2362 Py_INCREF(alias->name);
2363 PyTuple_SET_ITEM(names, i, alias->name);
2364 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2367 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2368 Py_DECREF(level);
2369 Py_DECREF(names);
2370 return compiler_error(c, "from __future__ imports must occur "
2371 "at the beginning of the file");
2372 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 ADDOP_O(c, LOAD_CONST, level, consts);
2375 Py_DECREF(level);
2376 ADDOP_O(c, LOAD_CONST, names, consts);
2377 Py_DECREF(names);
2378 if (s->v.ImportFrom.module) {
2379 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2380 }
2381 else {
2382 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2383 }
2384 for (i = 0; i < n; i++) {
2385 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2386 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 assert(n == 1);
2390 ADDOP(c, IMPORT_STAR);
2391 return 1;
2392 }
2393
2394 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2395 store_name = alias->name;
2396 if (alias->asname)
2397 store_name = alias->asname;
2398
2399 if (!compiler_nameop(c, store_name, Store)) {
2400 Py_DECREF(names);
2401 return 0;
2402 }
2403 }
2404 /* remove imported module */
2405 ADDOP(c, POP_TOP);
2406 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407}
2408
2409static int
2410compiler_assert(struct compiler *c, stmt_ty s)
2411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 static PyObject *assertion_error = NULL;
2413 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002414
Georg Brandl8334fd92010-12-04 10:26:46 +00002415 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 return 1;
2417 if (assertion_error == NULL) {
2418 assertion_error = PyUnicode_InternFromString("AssertionError");
2419 if (assertion_error == NULL)
2420 return 0;
2421 }
2422 if (s->v.Assert.test->kind == Tuple_kind &&
2423 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2424 const char* msg =
2425 "assertion is always true, perhaps remove parentheses?";
2426 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2427 c->u->u_lineno, NULL, NULL) == -1)
2428 return 0;
2429 }
2430 VISIT(c, expr, s->v.Assert.test);
2431 end = compiler_new_block(c);
2432 if (end == NULL)
2433 return 0;
2434 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2435 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2436 if (s->v.Assert.msg) {
2437 VISIT(c, expr, s->v.Assert.msg);
2438 ADDOP_I(c, CALL_FUNCTION, 1);
2439 }
2440 ADDOP_I(c, RAISE_VARARGS, 1);
2441 compiler_use_next_block(c, end);
2442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443}
2444
2445static int
2446compiler_visit_stmt(struct compiler *c, stmt_ty s)
2447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* Always assign a lineno to the next instruction for a stmt. */
2451 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002452 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 switch (s->kind) {
2456 case FunctionDef_kind:
2457 return compiler_function(c, s);
2458 case ClassDef_kind:
2459 return compiler_class(c, s);
2460 case Return_kind:
2461 if (c->u->u_ste->ste_type != FunctionBlock)
2462 return compiler_error(c, "'return' outside function");
2463 if (s->v.Return.value) {
2464 VISIT(c, expr, s->v.Return.value);
2465 }
2466 else
2467 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2468 ADDOP(c, RETURN_VALUE);
2469 break;
2470 case Delete_kind:
2471 VISIT_SEQ(c, expr, s->v.Delete.targets)
2472 break;
2473 case Assign_kind:
2474 n = asdl_seq_LEN(s->v.Assign.targets);
2475 VISIT(c, expr, s->v.Assign.value);
2476 for (i = 0; i < n; i++) {
2477 if (i < n - 1)
2478 ADDOP(c, DUP_TOP);
2479 VISIT(c, expr,
2480 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2481 }
2482 break;
2483 case AugAssign_kind:
2484 return compiler_augassign(c, s);
2485 case For_kind:
2486 return compiler_for(c, s);
2487 case While_kind:
2488 return compiler_while(c, s);
2489 case If_kind:
2490 return compiler_if(c, s);
2491 case Raise_kind:
2492 n = 0;
2493 if (s->v.Raise.exc) {
2494 VISIT(c, expr, s->v.Raise.exc);
2495 n++;
2496 if (s->v.Raise.cause) {
2497 VISIT(c, expr, s->v.Raise.cause);
2498 n++;
2499 }
2500 }
2501 ADDOP_I(c, RAISE_VARARGS, n);
2502 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002503 case Try_kind:
2504 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 case Assert_kind:
2506 return compiler_assert(c, s);
2507 case Import_kind:
2508 return compiler_import(c, s);
2509 case ImportFrom_kind:
2510 return compiler_from_import(c, s);
2511 case Global_kind:
2512 case Nonlocal_kind:
2513 break;
2514 case Expr_kind:
2515 if (c->c_interactive && c->c_nestlevel <= 1) {
2516 VISIT(c, expr, s->v.Expr.value);
2517 ADDOP(c, PRINT_EXPR);
2518 }
2519 else if (s->v.Expr.value->kind != Str_kind &&
2520 s->v.Expr.value->kind != Num_kind) {
2521 VISIT(c, expr, s->v.Expr.value);
2522 ADDOP(c, POP_TOP);
2523 }
2524 break;
2525 case Pass_kind:
2526 break;
2527 case Break_kind:
2528 if (!compiler_in_loop(c))
2529 return compiler_error(c, "'break' outside loop");
2530 ADDOP(c, BREAK_LOOP);
2531 break;
2532 case Continue_kind:
2533 return compiler_continue(c);
2534 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002535 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 }
2537 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538}
2539
2540static int
2541unaryop(unaryop_ty op)
2542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 switch (op) {
2544 case Invert:
2545 return UNARY_INVERT;
2546 case Not:
2547 return UNARY_NOT;
2548 case UAdd:
2549 return UNARY_POSITIVE;
2550 case USub:
2551 return UNARY_NEGATIVE;
2552 default:
2553 PyErr_Format(PyExc_SystemError,
2554 "unary op %d should not be possible", op);
2555 return 0;
2556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557}
2558
2559static int
2560binop(struct compiler *c, operator_ty op)
2561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 switch (op) {
2563 case Add:
2564 return BINARY_ADD;
2565 case Sub:
2566 return BINARY_SUBTRACT;
2567 case Mult:
2568 return BINARY_MULTIPLY;
2569 case Div:
2570 return BINARY_TRUE_DIVIDE;
2571 case Mod:
2572 return BINARY_MODULO;
2573 case Pow:
2574 return BINARY_POWER;
2575 case LShift:
2576 return BINARY_LSHIFT;
2577 case RShift:
2578 return BINARY_RSHIFT;
2579 case BitOr:
2580 return BINARY_OR;
2581 case BitXor:
2582 return BINARY_XOR;
2583 case BitAnd:
2584 return BINARY_AND;
2585 case FloorDiv:
2586 return BINARY_FLOOR_DIVIDE;
2587 default:
2588 PyErr_Format(PyExc_SystemError,
2589 "binary op %d should not be possible", op);
2590 return 0;
2591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592}
2593
2594static int
2595cmpop(cmpop_ty op)
2596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 switch (op) {
2598 case Eq:
2599 return PyCmp_EQ;
2600 case NotEq:
2601 return PyCmp_NE;
2602 case Lt:
2603 return PyCmp_LT;
2604 case LtE:
2605 return PyCmp_LE;
2606 case Gt:
2607 return PyCmp_GT;
2608 case GtE:
2609 return PyCmp_GE;
2610 case Is:
2611 return PyCmp_IS;
2612 case IsNot:
2613 return PyCmp_IS_NOT;
2614 case In:
2615 return PyCmp_IN;
2616 case NotIn:
2617 return PyCmp_NOT_IN;
2618 default:
2619 return PyCmp_BAD;
2620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621}
2622
2623static int
2624inplace_binop(struct compiler *c, operator_ty op)
2625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 switch (op) {
2627 case Add:
2628 return INPLACE_ADD;
2629 case Sub:
2630 return INPLACE_SUBTRACT;
2631 case Mult:
2632 return INPLACE_MULTIPLY;
2633 case Div:
2634 return INPLACE_TRUE_DIVIDE;
2635 case Mod:
2636 return INPLACE_MODULO;
2637 case Pow:
2638 return INPLACE_POWER;
2639 case LShift:
2640 return INPLACE_LSHIFT;
2641 case RShift:
2642 return INPLACE_RSHIFT;
2643 case BitOr:
2644 return INPLACE_OR;
2645 case BitXor:
2646 return INPLACE_XOR;
2647 case BitAnd:
2648 return INPLACE_AND;
2649 case FloorDiv:
2650 return INPLACE_FLOOR_DIVIDE;
2651 default:
2652 PyErr_Format(PyExc_SystemError,
2653 "inplace binary op %d should not be possible", op);
2654 return 0;
2655 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656}
2657
2658static int
2659compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 int op, scope, arg;
2662 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 PyObject *dict = c->u->u_names;
2665 PyObject *mangled;
2666 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 mangled = _Py_Mangle(c->u->u_private, name);
2669 if (!mangled)
2670 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002671
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002672 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2673 PyUnicode_CompareWithASCIIString(name, "True") &&
2674 PyUnicode_CompareWithASCIIString(name, "False"));
2675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 op = 0;
2677 optype = OP_NAME;
2678 scope = PyST_GetScope(c->u->u_ste, mangled);
2679 switch (scope) {
2680 case FREE:
2681 dict = c->u->u_freevars;
2682 optype = OP_DEREF;
2683 break;
2684 case CELL:
2685 dict = c->u->u_cellvars;
2686 optype = OP_DEREF;
2687 break;
2688 case LOCAL:
2689 if (c->u->u_ste->ste_type == FunctionBlock)
2690 optype = OP_FAST;
2691 break;
2692 case GLOBAL_IMPLICIT:
2693 if (c->u->u_ste->ste_type == FunctionBlock &&
2694 !c->u->u_ste->ste_unoptimized)
2695 optype = OP_GLOBAL;
2696 break;
2697 case GLOBAL_EXPLICIT:
2698 optype = OP_GLOBAL;
2699 break;
2700 default:
2701 /* scope can be 0 */
2702 break;
2703 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 switch (optype) {
2709 case OP_DEREF:
2710 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002711 case Load:
2712 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2713 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 case Store: op = STORE_DEREF; break;
2715 case AugLoad:
2716 case AugStore:
2717 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002718 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 case Param:
2720 default:
2721 PyErr_SetString(PyExc_SystemError,
2722 "param invalid for deref variable");
2723 return 0;
2724 }
2725 break;
2726 case OP_FAST:
2727 switch (ctx) {
2728 case Load: op = LOAD_FAST; break;
2729 case Store: op = STORE_FAST; break;
2730 case Del: op = DELETE_FAST; break;
2731 case AugLoad:
2732 case AugStore:
2733 break;
2734 case Param:
2735 default:
2736 PyErr_SetString(PyExc_SystemError,
2737 "param invalid for local variable");
2738 return 0;
2739 }
2740 ADDOP_O(c, op, mangled, varnames);
2741 Py_DECREF(mangled);
2742 return 1;
2743 case OP_GLOBAL:
2744 switch (ctx) {
2745 case Load: op = LOAD_GLOBAL; break;
2746 case Store: op = STORE_GLOBAL; break;
2747 case Del: op = DELETE_GLOBAL; break;
2748 case AugLoad:
2749 case AugStore:
2750 break;
2751 case Param:
2752 default:
2753 PyErr_SetString(PyExc_SystemError,
2754 "param invalid for global variable");
2755 return 0;
2756 }
2757 break;
2758 case OP_NAME:
2759 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002760 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 case Store: op = STORE_NAME; break;
2762 case Del: op = DELETE_NAME; break;
2763 case AugLoad:
2764 case AugStore:
2765 break;
2766 case Param:
2767 default:
2768 PyErr_SetString(PyExc_SystemError,
2769 "param invalid for name variable");
2770 return 0;
2771 }
2772 break;
2773 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 assert(op);
2776 arg = compiler_add_o(c, dict, mangled);
2777 Py_DECREF(mangled);
2778 if (arg < 0)
2779 return 0;
2780 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002781}
2782
2783static int
2784compiler_boolop(struct compiler *c, expr_ty e)
2785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 basicblock *end;
2787 int jumpi, i, n;
2788 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 assert(e->kind == BoolOp_kind);
2791 if (e->v.BoolOp.op == And)
2792 jumpi = JUMP_IF_FALSE_OR_POP;
2793 else
2794 jumpi = JUMP_IF_TRUE_OR_POP;
2795 end = compiler_new_block(c);
2796 if (end == NULL)
2797 return 0;
2798 s = e->v.BoolOp.values;
2799 n = asdl_seq_LEN(s) - 1;
2800 assert(n >= 0);
2801 for (i = 0; i < n; ++i) {
2802 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2803 ADDOP_JABS(c, jumpi, end);
2804 }
2805 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2806 compiler_use_next_block(c, end);
2807 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002808}
2809
2810static int
2811compiler_list(struct compiler *c, expr_ty e)
2812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 int n = asdl_seq_LEN(e->v.List.elts);
2814 if (e->v.List.ctx == Store) {
2815 int i, seen_star = 0;
2816 for (i = 0; i < n; i++) {
2817 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2818 if (elt->kind == Starred_kind && !seen_star) {
2819 if ((i >= (1 << 8)) ||
2820 (n-i-1 >= (INT_MAX >> 8)))
2821 return compiler_error(c,
2822 "too many expressions in "
2823 "star-unpacking assignment");
2824 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2825 seen_star = 1;
2826 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2827 } else if (elt->kind == Starred_kind) {
2828 return compiler_error(c,
2829 "two starred expressions in assignment");
2830 }
2831 }
2832 if (!seen_star) {
2833 ADDOP_I(c, UNPACK_SEQUENCE, n);
2834 }
2835 }
2836 VISIT_SEQ(c, expr, e->v.List.elts);
2837 if (e->v.List.ctx == Load) {
2838 ADDOP_I(c, BUILD_LIST, n);
2839 }
2840 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841}
2842
2843static int
2844compiler_tuple(struct compiler *c, expr_ty e)
2845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 int n = asdl_seq_LEN(e->v.Tuple.elts);
2847 if (e->v.Tuple.ctx == Store) {
2848 int i, seen_star = 0;
2849 for (i = 0; i < n; i++) {
2850 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2851 if (elt->kind == Starred_kind && !seen_star) {
2852 if ((i >= (1 << 8)) ||
2853 (n-i-1 >= (INT_MAX >> 8)))
2854 return compiler_error(c,
2855 "too many expressions in "
2856 "star-unpacking assignment");
2857 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2858 seen_star = 1;
2859 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2860 } else if (elt->kind == Starred_kind) {
2861 return compiler_error(c,
2862 "two starred expressions in assignment");
2863 }
2864 }
2865 if (!seen_star) {
2866 ADDOP_I(c, UNPACK_SEQUENCE, n);
2867 }
2868 }
2869 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2870 if (e->v.Tuple.ctx == Load) {
2871 ADDOP_I(c, BUILD_TUPLE, n);
2872 }
2873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874}
2875
2876static int
2877compiler_compare(struct compiler *c, expr_ty e)
2878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 int i, n;
2880 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2883 VISIT(c, expr, e->v.Compare.left);
2884 n = asdl_seq_LEN(e->v.Compare.ops);
2885 assert(n > 0);
2886 if (n > 1) {
2887 cleanup = compiler_new_block(c);
2888 if (cleanup == NULL)
2889 return 0;
2890 VISIT(c, expr,
2891 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2892 }
2893 for (i = 1; i < n; i++) {
2894 ADDOP(c, DUP_TOP);
2895 ADDOP(c, ROT_THREE);
2896 ADDOP_I(c, COMPARE_OP,
2897 cmpop((cmpop_ty)(asdl_seq_GET(
2898 e->v.Compare.ops, i - 1))));
2899 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2900 NEXT_BLOCK(c);
2901 if (i < (n - 1))
2902 VISIT(c, expr,
2903 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2904 }
2905 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2906 ADDOP_I(c, COMPARE_OP,
2907 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2908 if (n > 1) {
2909 basicblock *end = compiler_new_block(c);
2910 if (end == NULL)
2911 return 0;
2912 ADDOP_JREL(c, JUMP_FORWARD, end);
2913 compiler_use_next_block(c, cleanup);
2914 ADDOP(c, ROT_TWO);
2915 ADDOP(c, POP_TOP);
2916 compiler_use_next_block(c, end);
2917 }
2918 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919}
2920
2921static int
2922compiler_call(struct compiler *c, expr_ty e)
2923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 VISIT(c, expr, e->v.Call.func);
2925 return compiler_call_helper(c, 0,
2926 e->v.Call.args,
2927 e->v.Call.keywords,
2928 e->v.Call.starargs,
2929 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002930}
2931
2932/* shared code between compiler_call and compiler_class */
2933static int
2934compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 int n, /* Args already pushed */
2936 asdl_seq *args,
2937 asdl_seq *keywords,
2938 expr_ty starargs,
2939 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 n += asdl_seq_LEN(args);
2944 VISIT_SEQ(c, expr, args);
2945 if (keywords) {
2946 VISIT_SEQ(c, keyword, keywords);
2947 n |= asdl_seq_LEN(keywords) << 8;
2948 }
2949 if (starargs) {
2950 VISIT(c, expr, starargs);
2951 code |= 1;
2952 }
2953 if (kwargs) {
2954 VISIT(c, expr, kwargs);
2955 code |= 2;
2956 }
2957 switch (code) {
2958 case 0:
2959 ADDOP_I(c, CALL_FUNCTION, n);
2960 break;
2961 case 1:
2962 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2963 break;
2964 case 2:
2965 ADDOP_I(c, CALL_FUNCTION_KW, n);
2966 break;
2967 case 3:
2968 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2969 break;
2970 }
2971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972}
2973
Nick Coghlan650f0d02007-04-15 12:05:43 +00002974
2975/* List and set comprehensions and generator expressions work by creating a
2976 nested function to perform the actual iteration. This means that the
2977 iteration variables don't leak into the current scope.
2978 The defined function is called immediately following its definition, with the
2979 result of that call being the result of the expression.
2980 The LC/SC version returns the populated container, while the GE version is
2981 flagged in symtable.c as a generator, so it returns the generator object
2982 when the function is called.
2983 This code *knows* that the loop cannot contain break, continue, or return,
2984 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2985
2986 Possible cleanups:
2987 - iterate over the generator sequence instead of using recursion
2988*/
2989
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991compiler_comprehension_generator(struct compiler *c,
2992 asdl_seq *generators, int gen_index,
2993 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 /* generate code for the iterator, then each of the ifs,
2996 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 comprehension_ty gen;
2999 basicblock *start, *anchor, *skip, *if_cleanup;
3000 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 start = compiler_new_block(c);
3003 skip = compiler_new_block(c);
3004 if_cleanup = compiler_new_block(c);
3005 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3008 anchor == NULL)
3009 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 if (gen_index == 0) {
3014 /* Receive outermost iter as an implicit argument */
3015 c->u->u_argcount = 1;
3016 ADDOP_I(c, LOAD_FAST, 0);
3017 }
3018 else {
3019 /* Sub-iter - calculate on the fly */
3020 VISIT(c, expr, gen->iter);
3021 ADDOP(c, GET_ITER);
3022 }
3023 compiler_use_next_block(c, start);
3024 ADDOP_JREL(c, FOR_ITER, anchor);
3025 NEXT_BLOCK(c);
3026 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 /* XXX this needs to be cleaned up...a lot! */
3029 n = asdl_seq_LEN(gen->ifs);
3030 for (i = 0; i < n; i++) {
3031 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3032 VISIT(c, expr, e);
3033 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3034 NEXT_BLOCK(c);
3035 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 if (++gen_index < asdl_seq_LEN(generators))
3038 if (!compiler_comprehension_generator(c,
3039 generators, gen_index,
3040 elt, val, type))
3041 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 /* only append after the last for generator */
3044 if (gen_index >= asdl_seq_LEN(generators)) {
3045 /* comprehension specific code */
3046 switch (type) {
3047 case COMP_GENEXP:
3048 VISIT(c, expr, elt);
3049 ADDOP(c, YIELD_VALUE);
3050 ADDOP(c, POP_TOP);
3051 break;
3052 case COMP_LISTCOMP:
3053 VISIT(c, expr, elt);
3054 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3055 break;
3056 case COMP_SETCOMP:
3057 VISIT(c, expr, elt);
3058 ADDOP_I(c, SET_ADD, gen_index + 1);
3059 break;
3060 case COMP_DICTCOMP:
3061 /* With 'd[k] = v', v is evaluated before k, so we do
3062 the same. */
3063 VISIT(c, expr, val);
3064 VISIT(c, expr, elt);
3065 ADDOP_I(c, MAP_ADD, gen_index + 1);
3066 break;
3067 default:
3068 return 0;
3069 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 compiler_use_next_block(c, skip);
3072 }
3073 compiler_use_next_block(c, if_cleanup);
3074 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3075 compiler_use_next_block(c, anchor);
3076
3077 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078}
3079
3080static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003081compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 PyCodeObject *co = NULL;
3085 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003086 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 outermost_iter = ((comprehension_ty)
3089 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003090
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003091 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3092 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 if (type != COMP_GENEXP) {
3096 int op;
3097 switch (type) {
3098 case COMP_LISTCOMP:
3099 op = BUILD_LIST;
3100 break;
3101 case COMP_SETCOMP:
3102 op = BUILD_SET;
3103 break;
3104 case COMP_DICTCOMP:
3105 op = BUILD_MAP;
3106 break;
3107 default:
3108 PyErr_Format(PyExc_SystemError,
3109 "unknown comprehension type %d", type);
3110 goto error_in_scope;
3111 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 ADDOP_I(c, op, 0);
3114 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 if (!compiler_comprehension_generator(c, generators, 0, elt,
3117 val, type))
3118 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 if (type != COMP_GENEXP) {
3121 ADDOP(c, RETURN_VALUE);
3122 }
3123
3124 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003125 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003127 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 goto error;
3129
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003130 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003132 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 Py_DECREF(co);
3134
3135 VISIT(c, expr, outermost_iter);
3136 ADDOP(c, GET_ITER);
3137 ADDOP_I(c, CALL_FUNCTION, 1);
3138 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003139error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003141error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003142 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 Py_XDECREF(co);
3144 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003145}
3146
3147static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148compiler_genexp(struct compiler *c, expr_ty e)
3149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 static identifier name;
3151 if (!name) {
3152 name = PyUnicode_FromString("<genexpr>");
3153 if (!name)
3154 return 0;
3155 }
3156 assert(e->kind == GeneratorExp_kind);
3157 return compiler_comprehension(c, e, COMP_GENEXP, name,
3158 e->v.GeneratorExp.generators,
3159 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160}
3161
3162static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003163compiler_listcomp(struct compiler *c, expr_ty e)
3164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 static identifier name;
3166 if (!name) {
3167 name = PyUnicode_FromString("<listcomp>");
3168 if (!name)
3169 return 0;
3170 }
3171 assert(e->kind == ListComp_kind);
3172 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3173 e->v.ListComp.generators,
3174 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003175}
3176
3177static int
3178compiler_setcomp(struct compiler *c, expr_ty e)
3179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 static identifier name;
3181 if (!name) {
3182 name = PyUnicode_FromString("<setcomp>");
3183 if (!name)
3184 return 0;
3185 }
3186 assert(e->kind == SetComp_kind);
3187 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3188 e->v.SetComp.generators,
3189 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003190}
3191
3192
3193static int
3194compiler_dictcomp(struct compiler *c, expr_ty e)
3195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 static identifier name;
3197 if (!name) {
3198 name = PyUnicode_FromString("<dictcomp>");
3199 if (!name)
3200 return 0;
3201 }
3202 assert(e->kind == DictComp_kind);
3203 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3204 e->v.DictComp.generators,
3205 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003206}
3207
3208
3209static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210compiler_visit_keyword(struct compiler *c, keyword_ty k)
3211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3213 VISIT(c, expr, k->value);
3214 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003215}
3216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 whether they are true or false.
3219
3220 Return values: 1 for true, 0 for false, -1 for non-constant.
3221 */
3222
3223static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003224expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 char *id;
3227 switch (e->kind) {
3228 case Ellipsis_kind:
3229 return 1;
3230 case Num_kind:
3231 return PyObject_IsTrue(e->v.Num.n);
3232 case Str_kind:
3233 return PyObject_IsTrue(e->v.Str.s);
3234 case Name_kind:
3235 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003236 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003237 if (id && strcmp(id, "__debug__") == 0)
3238 return !c->c_optimize;
3239 return -1;
3240 case NameConstant_kind: {
3241 PyObject *o = e->v.NameConstant.value;
3242 if (o == Py_None)
3243 return 0;
3244 else if (o == Py_True)
3245 return 1;
3246 else if (o == Py_False)
3247 return 0;
3248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 default:
3250 return -1;
3251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252}
3253
Guido van Rossumc2e20742006-02-27 22:32:47 +00003254/*
3255 Implements the with statement from PEP 343.
3256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003258
3259 with EXPR as VAR:
3260 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261
Guido van Rossumc2e20742006-02-27 22:32:47 +00003262 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263
Thomas Wouters477c8d52006-05-27 19:21:47 +00003264 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003265 exit = context.__exit__ # not calling it
3266 value = context.__enter__()
3267 try:
3268 VAR = value # if VAR present in the syntax
3269 BLOCK
3270 finally:
3271 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003273 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003275 exit(*exc)
3276 */
3277static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003278compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003279{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003280 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003281 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003282
3283 assert(s->kind == With_kind);
3284
Guido van Rossumc2e20742006-02-27 22:32:47 +00003285 block = compiler_new_block(c);
3286 finally = compiler_new_block(c);
3287 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003288 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003289
Thomas Wouters477c8d52006-05-27 19:21:47 +00003290 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003291 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003292 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003293
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003294 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003295 compiler_use_next_block(c, block);
3296 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003297 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003298 }
3299
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003300 if (item->optional_vars) {
3301 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003302 }
3303 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003305 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003306 }
3307
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003308 pos++;
3309 if (pos == asdl_seq_LEN(s->v.With.items))
3310 /* BLOCK code */
3311 VISIT_SEQ(c, stmt, s->v.With.body)
3312 else if (!compiler_with(c, s, pos))
3313 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003314
3315 /* End of try block; start the finally block */
3316 ADDOP(c, POP_BLOCK);
3317 compiler_pop_fblock(c, FINALLY_TRY, block);
3318
3319 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3320 compiler_use_next_block(c, finally);
3321 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003322 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003323
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003324 /* Finally block starts; context.__exit__ is on the stack under
3325 the exception or return information. Just issue our magic
3326 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003327 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003328
3329 /* Finally block ends. */
3330 ADDOP(c, END_FINALLY);
3331 compiler_pop_fblock(c, FINALLY_END, finally);
3332 return 1;
3333}
3334
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335static int
3336compiler_visit_expr(struct compiler *c, expr_ty e)
3337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 /* If expr e has a different line number than the last expr/stmt,
3341 set a new line number for the next instruction.
3342 */
3343 if (e->lineno > c->u->u_lineno) {
3344 c->u->u_lineno = e->lineno;
3345 c->u->u_lineno_set = 0;
3346 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003347 /* Updating the column offset is always harmless. */
3348 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 switch (e->kind) {
3350 case BoolOp_kind:
3351 return compiler_boolop(c, e);
3352 case BinOp_kind:
3353 VISIT(c, expr, e->v.BinOp.left);
3354 VISIT(c, expr, e->v.BinOp.right);
3355 ADDOP(c, binop(c, e->v.BinOp.op));
3356 break;
3357 case UnaryOp_kind:
3358 VISIT(c, expr, e->v.UnaryOp.operand);
3359 ADDOP(c, unaryop(e->v.UnaryOp.op));
3360 break;
3361 case Lambda_kind:
3362 return compiler_lambda(c, e);
3363 case IfExp_kind:
3364 return compiler_ifexp(c, e);
3365 case Dict_kind:
3366 n = asdl_seq_LEN(e->v.Dict.values);
3367 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3368 for (i = 0; i < n; i++) {
3369 VISIT(c, expr,
3370 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3371 VISIT(c, expr,
3372 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3373 ADDOP(c, STORE_MAP);
3374 }
3375 break;
3376 case Set_kind:
3377 n = asdl_seq_LEN(e->v.Set.elts);
3378 VISIT_SEQ(c, expr, e->v.Set.elts);
3379 ADDOP_I(c, BUILD_SET, n);
3380 break;
3381 case GeneratorExp_kind:
3382 return compiler_genexp(c, e);
3383 case ListComp_kind:
3384 return compiler_listcomp(c, e);
3385 case SetComp_kind:
3386 return compiler_setcomp(c, e);
3387 case DictComp_kind:
3388 return compiler_dictcomp(c, e);
3389 case Yield_kind:
3390 if (c->u->u_ste->ste_type != FunctionBlock)
3391 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003392 if (e->v.Yield.value) {
3393 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 }
3395 else {
3396 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3397 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003398 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003400 case YieldFrom_kind:
3401 if (c->u->u_ste->ste_type != FunctionBlock)
3402 return compiler_error(c, "'yield' outside function");
3403 VISIT(c, expr, e->v.YieldFrom.value);
3404 ADDOP(c, GET_ITER);
3405 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3406 ADDOP(c, YIELD_FROM);
3407 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 case Compare_kind:
3409 return compiler_compare(c, e);
3410 case Call_kind:
3411 return compiler_call(c, e);
3412 case Num_kind:
3413 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3414 break;
3415 case Str_kind:
3416 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3417 break;
3418 case Bytes_kind:
3419 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3420 break;
3421 case Ellipsis_kind:
3422 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3423 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003424 case NameConstant_kind:
3425 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3426 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 /* The following exprs can be assignment targets. */
3428 case Attribute_kind:
3429 if (e->v.Attribute.ctx != AugStore)
3430 VISIT(c, expr, e->v.Attribute.value);
3431 switch (e->v.Attribute.ctx) {
3432 case AugLoad:
3433 ADDOP(c, DUP_TOP);
3434 /* Fall through to load */
3435 case Load:
3436 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3437 break;
3438 case AugStore:
3439 ADDOP(c, ROT_TWO);
3440 /* Fall through to save */
3441 case Store:
3442 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3443 break;
3444 case Del:
3445 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3446 break;
3447 case Param:
3448 default:
3449 PyErr_SetString(PyExc_SystemError,
3450 "param invalid in attribute expression");
3451 return 0;
3452 }
3453 break;
3454 case Subscript_kind:
3455 switch (e->v.Subscript.ctx) {
3456 case AugLoad:
3457 VISIT(c, expr, e->v.Subscript.value);
3458 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3459 break;
3460 case Load:
3461 VISIT(c, expr, e->v.Subscript.value);
3462 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3463 break;
3464 case AugStore:
3465 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3466 break;
3467 case Store:
3468 VISIT(c, expr, e->v.Subscript.value);
3469 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3470 break;
3471 case Del:
3472 VISIT(c, expr, e->v.Subscript.value);
3473 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3474 break;
3475 case Param:
3476 default:
3477 PyErr_SetString(PyExc_SystemError,
3478 "param invalid in subscript expression");
3479 return 0;
3480 }
3481 break;
3482 case Starred_kind:
3483 switch (e->v.Starred.ctx) {
3484 case Store:
3485 /* In all legitimate cases, the Starred node was already replaced
3486 * by compiler_list/compiler_tuple. XXX: is that okay? */
3487 return compiler_error(c,
3488 "starred assignment target must be in a list or tuple");
3489 default:
3490 return compiler_error(c,
3491 "can use starred expression only as assignment target");
3492 }
3493 break;
3494 case Name_kind:
3495 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3496 /* child nodes of List and Tuple will have expr_context set */
3497 case List_kind:
3498 return compiler_list(c, e);
3499 case Tuple_kind:
3500 return compiler_tuple(c, e);
3501 }
3502 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503}
3504
3505static int
3506compiler_augassign(struct compiler *c, stmt_ty s)
3507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 expr_ty e = s->v.AugAssign.target;
3509 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 switch (e->kind) {
3514 case Attribute_kind:
3515 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3516 AugLoad, e->lineno, e->col_offset, c->c_arena);
3517 if (auge == NULL)
3518 return 0;
3519 VISIT(c, expr, auge);
3520 VISIT(c, expr, s->v.AugAssign.value);
3521 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3522 auge->v.Attribute.ctx = AugStore;
3523 VISIT(c, expr, auge);
3524 break;
3525 case Subscript_kind:
3526 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3527 AugLoad, e->lineno, e->col_offset, c->c_arena);
3528 if (auge == NULL)
3529 return 0;
3530 VISIT(c, expr, auge);
3531 VISIT(c, expr, s->v.AugAssign.value);
3532 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3533 auge->v.Subscript.ctx = AugStore;
3534 VISIT(c, expr, auge);
3535 break;
3536 case Name_kind:
3537 if (!compiler_nameop(c, e->v.Name.id, Load))
3538 return 0;
3539 VISIT(c, expr, s->v.AugAssign.value);
3540 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3541 return compiler_nameop(c, e->v.Name.id, Store);
3542 default:
3543 PyErr_Format(PyExc_SystemError,
3544 "invalid node type (%d) for augmented assignment",
3545 e->kind);
3546 return 0;
3547 }
3548 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549}
3550
3551static int
3552compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 struct fblockinfo *f;
3555 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3556 PyErr_SetString(PyExc_SystemError,
3557 "too many statically nested blocks");
3558 return 0;
3559 }
3560 f = &c->u->u_fblock[c->u->u_nfblocks++];
3561 f->fb_type = t;
3562 f->fb_block = b;
3563 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564}
3565
3566static void
3567compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 struct compiler_unit *u = c->u;
3570 assert(u->u_nfblocks > 0);
3571 u->u_nfblocks--;
3572 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3573 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574}
3575
Thomas Wouters89f507f2006-12-13 04:49:30 +00003576static int
3577compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 int i;
3579 struct compiler_unit *u = c->u;
3580 for (i = 0; i < u->u_nfblocks; ++i) {
3581 if (u->u_fblock[i].fb_type == LOOP)
3582 return 1;
3583 }
3584 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003585}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586/* Raises a SyntaxError and returns 0.
3587 If something goes wrong, a different exception may be raised.
3588*/
3589
3590static int
3591compiler_error(struct compiler *c, const char *errstr)
3592{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003593 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3597 if (!loc) {
3598 Py_INCREF(Py_None);
3599 loc = Py_None;
3600 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003601 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003602 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 if (!u)
3604 goto exit;
3605 v = Py_BuildValue("(zO)", errstr, u);
3606 if (!v)
3607 goto exit;
3608 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 Py_DECREF(loc);
3611 Py_XDECREF(u);
3612 Py_XDECREF(v);
3613 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614}
3615
3616static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617compiler_handle_subscr(struct compiler *c, const char *kind,
3618 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 /* XXX this code is duplicated */
3623 switch (ctx) {
3624 case AugLoad: /* fall through to Load */
3625 case Load: op = BINARY_SUBSCR; break;
3626 case AugStore:/* fall through to Store */
3627 case Store: op = STORE_SUBSCR; break;
3628 case Del: op = DELETE_SUBSCR; break;
3629 case Param:
3630 PyErr_Format(PyExc_SystemError,
3631 "invalid %s kind %d in subscript\n",
3632 kind, ctx);
3633 return 0;
3634 }
3635 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003636 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 }
3638 else if (ctx == AugStore) {
3639 ADDOP(c, ROT_THREE);
3640 }
3641 ADDOP(c, op);
3642 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643}
3644
3645static int
3646compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 int n = 2;
3649 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 /* only handles the cases where BUILD_SLICE is emitted */
3652 if (s->v.Slice.lower) {
3653 VISIT(c, expr, s->v.Slice.lower);
3654 }
3655 else {
3656 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3657 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 if (s->v.Slice.upper) {
3660 VISIT(c, expr, s->v.Slice.upper);
3661 }
3662 else {
3663 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3664 }
3665
3666 if (s->v.Slice.step) {
3667 n++;
3668 VISIT(c, expr, s->v.Slice.step);
3669 }
3670 ADDOP_I(c, BUILD_SLICE, n);
3671 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672}
3673
3674static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3676 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 switch (s->kind) {
3679 case Slice_kind:
3680 return compiler_slice(c, s, ctx);
3681 case Index_kind:
3682 VISIT(c, expr, s->v.Index.value);
3683 break;
3684 case ExtSlice_kind:
3685 default:
3686 PyErr_SetString(PyExc_SystemError,
3687 "extended slice invalid in nested slice");
3688 return 0;
3689 }
3690 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003691}
3692
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003693static int
3694compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 char * kindname = NULL;
3697 switch (s->kind) {
3698 case Index_kind:
3699 kindname = "index";
3700 if (ctx != AugStore) {
3701 VISIT(c, expr, s->v.Index.value);
3702 }
3703 break;
3704 case Slice_kind:
3705 kindname = "slice";
3706 if (ctx != AugStore) {
3707 if (!compiler_slice(c, s, ctx))
3708 return 0;
3709 }
3710 break;
3711 case ExtSlice_kind:
3712 kindname = "extended slice";
3713 if (ctx != AugStore) {
3714 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3715 for (i = 0; i < n; i++) {
3716 slice_ty sub = (slice_ty)asdl_seq_GET(
3717 s->v.ExtSlice.dims, i);
3718 if (!compiler_visit_nested_slice(c, sub, ctx))
3719 return 0;
3720 }
3721 ADDOP_I(c, BUILD_TUPLE, n);
3722 }
3723 break;
3724 default:
3725 PyErr_Format(PyExc_SystemError,
3726 "invalid subscript kind %d", s->kind);
3727 return 0;
3728 }
3729 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003730}
3731
Thomas Wouters89f507f2006-12-13 04:49:30 +00003732/* End of the compiler section, beginning of the assembler section */
3733
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734/* do depth-first search of basic block graph, starting with block.
3735 post records the block indices in post-order.
3736
3737 XXX must handle implicit jumps from one block to next
3738*/
3739
Thomas Wouters89f507f2006-12-13 04:49:30 +00003740struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 PyObject *a_bytecode; /* string containing bytecode */
3742 int a_offset; /* offset into bytecode */
3743 int a_nblocks; /* number of reachable blocks */
3744 basicblock **a_postorder; /* list of blocks in dfs postorder */
3745 PyObject *a_lnotab; /* string containing lnotab */
3746 int a_lnotab_off; /* offset into lnotab */
3747 int a_lineno; /* last lineno of emitted instruction */
3748 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003749};
3750
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751static void
3752dfs(struct compiler *c, basicblock *b, struct assembler *a)
3753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 int i;
3755 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 if (b->b_seen)
3758 return;
3759 b->b_seen = 1;
3760 if (b->b_next != NULL)
3761 dfs(c, b->b_next, a);
3762 for (i = 0; i < b->b_iused; i++) {
3763 instr = &b->b_instr[i];
3764 if (instr->i_jrel || instr->i_jabs)
3765 dfs(c, instr->i_target, a);
3766 }
3767 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768}
3769
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003770static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 int i, target_depth;
3774 struct instr *instr;
3775 if (b->b_seen || b->b_startdepth >= depth)
3776 return maxdepth;
3777 b->b_seen = 1;
3778 b->b_startdepth = depth;
3779 for (i = 0; i < b->b_iused; i++) {
3780 instr = &b->b_instr[i];
3781 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3782 if (depth > maxdepth)
3783 maxdepth = depth;
3784 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3785 if (instr->i_jrel || instr->i_jabs) {
3786 target_depth = depth;
3787 if (instr->i_opcode == FOR_ITER) {
3788 target_depth = depth-2;
3789 } else if (instr->i_opcode == SETUP_FINALLY ||
3790 instr->i_opcode == SETUP_EXCEPT) {
3791 target_depth = depth+3;
3792 if (target_depth > maxdepth)
3793 maxdepth = target_depth;
3794 }
3795 maxdepth = stackdepth_walk(c, instr->i_target,
3796 target_depth, maxdepth);
3797 if (instr->i_opcode == JUMP_ABSOLUTE ||
3798 instr->i_opcode == JUMP_FORWARD) {
3799 goto out; /* remaining code is dead */
3800 }
3801 }
3802 }
3803 if (b->b_next)
3804 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 b->b_seen = 0;
3807 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808}
3809
3810/* Find the flow path that needs the largest stack. We assume that
3811 * cycles in the flow graph have no net effect on the stack depth.
3812 */
3813static int
3814stackdepth(struct compiler *c)
3815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 basicblock *b, *entryblock;
3817 entryblock = NULL;
3818 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3819 b->b_seen = 0;
3820 b->b_startdepth = INT_MIN;
3821 entryblock = b;
3822 }
3823 if (!entryblock)
3824 return 0;
3825 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826}
3827
3828static int
3829assemble_init(struct assembler *a, int nblocks, int firstlineno)
3830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 memset(a, 0, sizeof(struct assembler));
3832 a->a_lineno = firstlineno;
3833 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3834 if (!a->a_bytecode)
3835 return 0;
3836 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3837 if (!a->a_lnotab)
3838 return 0;
3839 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3840 PyErr_NoMemory();
3841 return 0;
3842 }
3843 a->a_postorder = (basicblock **)PyObject_Malloc(
3844 sizeof(basicblock *) * nblocks);
3845 if (!a->a_postorder) {
3846 PyErr_NoMemory();
3847 return 0;
3848 }
3849 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850}
3851
3852static void
3853assemble_free(struct assembler *a)
3854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 Py_XDECREF(a->a_bytecode);
3856 Py_XDECREF(a->a_lnotab);
3857 if (a->a_postorder)
3858 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859}
3860
3861/* Return the size of a basic block in bytes. */
3862
3863static int
3864instrsize(struct instr *instr)
3865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 if (!instr->i_hasarg)
3867 return 1; /* 1 byte for the opcode*/
3868 if (instr->i_oparg > 0xffff)
3869 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3870 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871}
3872
3873static int
3874blocksize(basicblock *b)
3875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 int i;
3877 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 for (i = 0; i < b->b_iused; i++)
3880 size += instrsize(&b->b_instr[i]);
3881 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882}
3883
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003884/* Appends a pair to the end of the line number table, a_lnotab, representing
3885 the instruction's bytecode offset and line number. See
3886 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003887
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003888static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 int d_bytecode, d_lineno;
3892 int len;
3893 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 d_bytecode = a->a_offset - a->a_lineno_off;
3896 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 assert(d_bytecode >= 0);
3899 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 if(d_bytecode == 0 && d_lineno == 0)
3902 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 if (d_bytecode > 255) {
3905 int j, nbytes, ncodes = d_bytecode / 255;
3906 nbytes = a->a_lnotab_off + 2 * ncodes;
3907 len = PyBytes_GET_SIZE(a->a_lnotab);
3908 if (nbytes >= len) {
3909 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3910 len = nbytes;
3911 else if (len <= INT_MAX / 2)
3912 len *= 2;
3913 else {
3914 PyErr_NoMemory();
3915 return 0;
3916 }
3917 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3918 return 0;
3919 }
3920 lnotab = (unsigned char *)
3921 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3922 for (j = 0; j < ncodes; j++) {
3923 *lnotab++ = 255;
3924 *lnotab++ = 0;
3925 }
3926 d_bytecode -= ncodes * 255;
3927 a->a_lnotab_off += ncodes * 2;
3928 }
3929 assert(d_bytecode <= 255);
3930 if (d_lineno > 255) {
3931 int j, nbytes, ncodes = d_lineno / 255;
3932 nbytes = a->a_lnotab_off + 2 * ncodes;
3933 len = PyBytes_GET_SIZE(a->a_lnotab);
3934 if (nbytes >= len) {
3935 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3936 len = nbytes;
3937 else if (len <= INT_MAX / 2)
3938 len *= 2;
3939 else {
3940 PyErr_NoMemory();
3941 return 0;
3942 }
3943 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3944 return 0;
3945 }
3946 lnotab = (unsigned char *)
3947 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3948 *lnotab++ = d_bytecode;
3949 *lnotab++ = 255;
3950 d_bytecode = 0;
3951 for (j = 1; j < ncodes; j++) {
3952 *lnotab++ = 0;
3953 *lnotab++ = 255;
3954 }
3955 d_lineno -= ncodes * 255;
3956 a->a_lnotab_off += ncodes * 2;
3957 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 len = PyBytes_GET_SIZE(a->a_lnotab);
3960 if (a->a_lnotab_off + 2 >= len) {
3961 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3962 return 0;
3963 }
3964 lnotab = (unsigned char *)
3965 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 a->a_lnotab_off += 2;
3968 if (d_bytecode) {
3969 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003970 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 }
3972 else { /* First line of a block; def stmt, etc. */
3973 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003974 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 }
3976 a->a_lineno = i->i_lineno;
3977 a->a_lineno_off = a->a_offset;
3978 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003979}
3980
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003981/* assemble_emit()
3982 Extend the bytecode with a new instruction.
3983 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003984*/
3985
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003986static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003987assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 int size, arg = 0, ext = 0;
3990 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3991 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 size = instrsize(i);
3994 if (i->i_hasarg) {
3995 arg = i->i_oparg;
3996 ext = arg >> 16;
3997 }
3998 if (i->i_lineno && !assemble_lnotab(a, i))
3999 return 0;
4000 if (a->a_offset + size >= len) {
4001 if (len > PY_SSIZE_T_MAX / 2)
4002 return 0;
4003 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4004 return 0;
4005 }
4006 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4007 a->a_offset += size;
4008 if (size == 6) {
4009 assert(i->i_hasarg);
4010 *code++ = (char)EXTENDED_ARG;
4011 *code++ = ext & 0xff;
4012 *code++ = ext >> 8;
4013 arg &= 0xffff;
4014 }
4015 *code++ = i->i_opcode;
4016 if (i->i_hasarg) {
4017 assert(size == 3 || size == 6);
4018 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004019 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 }
4021 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004022}
4023
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004024static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 basicblock *b;
4028 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4029 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 /* Compute the size of each block and fixup jump args.
4032 Replace block pointer with position in bytecode. */
4033 do {
4034 totsize = 0;
4035 for (i = a->a_nblocks - 1; i >= 0; i--) {
4036 b = a->a_postorder[i];
4037 bsize = blocksize(b);
4038 b->b_offset = totsize;
4039 totsize += bsize;
4040 }
4041 last_extended_arg_count = extended_arg_count;
4042 extended_arg_count = 0;
4043 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4044 bsize = b->b_offset;
4045 for (i = 0; i < b->b_iused; i++) {
4046 struct instr *instr = &b->b_instr[i];
4047 /* Relative jumps are computed relative to
4048 the instruction pointer after fetching
4049 the jump instruction.
4050 */
4051 bsize += instrsize(instr);
4052 if (instr->i_jabs)
4053 instr->i_oparg = instr->i_target->b_offset;
4054 else if (instr->i_jrel) {
4055 int delta = instr->i_target->b_offset - bsize;
4056 instr->i_oparg = delta;
4057 }
4058 else
4059 continue;
4060 if (instr->i_oparg > 0xffff)
4061 extended_arg_count++;
4062 }
4063 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 /* XXX: This is an awful hack that could hurt performance, but
4066 on the bright side it should work until we come up
4067 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 The issue is that in the first loop blocksize() is called
4070 which calls instrsize() which requires i_oparg be set
4071 appropriately. There is a bootstrap problem because
4072 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 So we loop until we stop seeing new EXTENDED_ARGs.
4075 The only EXTENDED_ARGs that could be popping up are
4076 ones in jump instructions. So this should converge
4077 fairly quickly.
4078 */
4079 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004080}
4081
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004082static PyObject *
4083dict_keys_inorder(PyObject *dict, int offset)
4084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 PyObject *tuple, *k, *v;
4086 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 tuple = PyTuple_New(size);
4089 if (tuple == NULL)
4090 return NULL;
4091 while (PyDict_Next(dict, &pos, &k, &v)) {
4092 i = PyLong_AS_LONG(v);
4093 /* The keys of the dictionary are tuples. (see compiler_add_o)
4094 The object we want is always first, though. */
4095 k = PyTuple_GET_ITEM(k, 0);
4096 Py_INCREF(k);
4097 assert((i - offset) < size);
4098 assert((i - offset) >= 0);
4099 PyTuple_SET_ITEM(tuple, i - offset, k);
4100 }
4101 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004102}
4103
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004104static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 PySTEntryObject *ste = c->u->u_ste;
4108 int flags = 0, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004110 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 if (!ste->ste_unoptimized)
4112 flags |= CO_OPTIMIZED;
4113 if (ste->ste_nested)
4114 flags |= CO_NESTED;
4115 if (ste->ste_generator)
4116 flags |= CO_GENERATOR;
4117 if (ste->ste_varargs)
4118 flags |= CO_VARARGS;
4119 if (ste->ste_varkeywords)
4120 flags |= CO_VARKEYWORDS;
4121 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* (Only) inherit compilerflags in PyCF_MASK */
4124 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 n = PyDict_Size(c->u->u_freevars);
4127 if (n < 0)
4128 return -1;
4129 if (n == 0) {
4130 n = PyDict_Size(c->u->u_cellvars);
4131 if (n < 0)
4132 return -1;
4133 if (n == 0) {
4134 flags |= CO_NOFREE;
4135 }
4136 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004139}
4140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141static PyCodeObject *
4142makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 PyObject *tmp;
4145 PyCodeObject *co = NULL;
4146 PyObject *consts = NULL;
4147 PyObject *names = NULL;
4148 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 PyObject *name = NULL;
4150 PyObject *freevars = NULL;
4151 PyObject *cellvars = NULL;
4152 PyObject *bytecode = NULL;
4153 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 tmp = dict_keys_inorder(c->u->u_consts, 0);
4156 if (!tmp)
4157 goto error;
4158 consts = PySequence_List(tmp); /* optimize_code requires a list */
4159 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 names = dict_keys_inorder(c->u->u_names, 0);
4162 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4163 if (!consts || !names || !varnames)
4164 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4167 if (!cellvars)
4168 goto error;
4169 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4170 if (!freevars)
4171 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 nlocals = PyDict_Size(c->u->u_varnames);
4173 flags = compute_code_flags(c);
4174 if (flags < 0)
4175 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4178 if (!bytecode)
4179 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4182 if (!tmp)
4183 goto error;
4184 Py_DECREF(consts);
4185 consts = tmp;
4186
4187 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4188 nlocals, stackdepth(c), flags,
4189 bytecode, consts, names, varnames,
4190 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004191 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 c->u->u_firstlineno,
4193 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 Py_XDECREF(consts);
4196 Py_XDECREF(names);
4197 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 Py_XDECREF(name);
4199 Py_XDECREF(freevars);
4200 Py_XDECREF(cellvars);
4201 Py_XDECREF(bytecode);
4202 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004203}
4204
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004205
4206/* For debugging purposes only */
4207#if 0
4208static void
4209dump_instr(const struct instr *i)
4210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 const char *jrel = i->i_jrel ? "jrel " : "";
4212 const char *jabs = i->i_jabs ? "jabs " : "";
4213 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 *arg = '\0';
4216 if (i->i_hasarg)
4217 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4220 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004221}
4222
4223static void
4224dump_basicblock(const basicblock *b)
4225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 const char *seen = b->b_seen ? "seen " : "";
4227 const char *b_return = b->b_return ? "return " : "";
4228 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4229 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4230 if (b->b_instr) {
4231 int i;
4232 for (i = 0; i < b->b_iused; i++) {
4233 fprintf(stderr, " [%02d] ", i);
4234 dump_instr(b->b_instr + i);
4235 }
4236 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004237}
4238#endif
4239
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240static PyCodeObject *
4241assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 basicblock *b, *entryblock;
4244 struct assembler a;
4245 int i, j, nblocks;
4246 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 /* Make sure every block that falls off the end returns None.
4249 XXX NEXT_BLOCK() isn't quite right, because if the last
4250 block ends with a jump or return b_next shouldn't set.
4251 */
4252 if (!c->u->u_curblock->b_return) {
4253 NEXT_BLOCK(c);
4254 if (addNone)
4255 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4256 ADDOP(c, RETURN_VALUE);
4257 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 nblocks = 0;
4260 entryblock = NULL;
4261 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4262 nblocks++;
4263 entryblock = b;
4264 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 /* Set firstlineno if it wasn't explicitly set. */
4267 if (!c->u->u_firstlineno) {
4268 if (entryblock && entryblock->b_instr)
4269 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4270 else
4271 c->u->u_firstlineno = 1;
4272 }
4273 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4274 goto error;
4275 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 /* Can't modify the bytecode after computing jump offsets. */
4278 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 /* Emit code in reverse postorder from dfs. */
4281 for (i = a.a_nblocks - 1; i >= 0; i--) {
4282 b = a.a_postorder[i];
4283 for (j = 0; j < b->b_iused; j++)
4284 if (!assemble_emit(&a, &b->b_instr[j]))
4285 goto error;
4286 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4289 goto error;
4290 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4291 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004294 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 assemble_free(&a);
4296 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004297}
Georg Brandl8334fd92010-12-04 10:26:46 +00004298
4299#undef PyAST_Compile
4300PyAPI_FUNC(PyCodeObject *)
4301PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4302 PyArena *arena)
4303{
4304 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4305}
4306
4307