blob: 24ff61f8a9143abbe85b5250949cfab6de2ab407 [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 */
896 case STORE_LOCALS:
897 return -1;
898 case RETURN_VALUE:
899 return -1;
900 case IMPORT_STAR:
901 return -1;
902 case YIELD_VALUE:
903 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500904 case YIELD_FROM:
905 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case POP_BLOCK:
907 return 0;
908 case POP_EXCEPT:
909 return 0; /* -3 except if bad bytecode */
910 case END_FINALLY:
911 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 case STORE_NAME:
914 return -1;
915 case DELETE_NAME:
916 return 0;
917 case UNPACK_SEQUENCE:
918 return oparg-1;
919 case UNPACK_EX:
920 return (oparg&0xFF) + (oparg>>8);
921 case FOR_ITER:
922 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 case STORE_ATTR:
925 return -2;
926 case DELETE_ATTR:
927 return -1;
928 case STORE_GLOBAL:
929 return -1;
930 case DELETE_GLOBAL:
931 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case LOAD_CONST:
933 return 1;
934 case LOAD_NAME:
935 return 1;
936 case BUILD_TUPLE:
937 case BUILD_LIST:
938 case BUILD_SET:
939 return 1-oparg;
940 case BUILD_MAP:
941 return 1;
942 case LOAD_ATTR:
943 return 0;
944 case COMPARE_OP:
945 return -1;
946 case IMPORT_NAME:
947 return -1;
948 case IMPORT_FROM:
949 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 case JUMP_FORWARD:
952 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
953 case JUMP_IF_FALSE_OR_POP: /* "" */
954 case JUMP_ABSOLUTE:
955 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case POP_JUMP_IF_FALSE:
958 case POP_JUMP_IF_TRUE:
959 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case LOAD_GLOBAL:
962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case CONTINUE_LOOP:
965 return 0;
966 case SETUP_LOOP:
967 return 0;
968 case SETUP_EXCEPT:
969 case SETUP_FINALLY:
970 return 6; /* can push 3 values for the new exception
971 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case LOAD_FAST:
974 return 1;
975 case STORE_FAST:
976 return -1;
977 case DELETE_FAST:
978 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 case RAISE_VARARGS:
981 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000982#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 case CALL_FUNCTION:
984 return -NARGS(oparg);
985 case CALL_FUNCTION_VAR:
986 case CALL_FUNCTION_KW:
987 return -NARGS(oparg)-1;
988 case CALL_FUNCTION_VAR_KW:
989 return -NARGS(oparg)-2;
990 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100991 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100993 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000994#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 case BUILD_SLICE:
996 if (oparg == 3)
997 return -2;
998 else
999 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case LOAD_CLOSURE:
1002 return 1;
1003 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001004 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return 1;
1006 case STORE_DEREF:
1007 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001008 case DELETE_DEREF:
1009 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 default:
1011 fprintf(stderr, "opcode = %d\n", opcode);
1012 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 }
1015 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016}
1017
1018/* Add an opcode with no argument.
1019 Returns 0 on failure, 1 on success.
1020*/
1021
1022static int
1023compiler_addop(struct compiler *c, int opcode)
1024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 basicblock *b;
1026 struct instr *i;
1027 int off;
1028 off = compiler_next_instr(c, c->u->u_curblock);
1029 if (off < 0)
1030 return 0;
1031 b = c->u->u_curblock;
1032 i = &b->b_instr[off];
1033 i->i_opcode = opcode;
1034 i->i_hasarg = 0;
1035 if (opcode == RETURN_VALUE)
1036 b->b_return = 1;
1037 compiler_set_lineno(c, off);
1038 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001039}
1040
1041static int
1042compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyObject *t, *v;
1045 Py_ssize_t arg;
1046 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* necessary to make sure types aren't coerced (e.g., int and long) */
1049 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1050 if (PyFloat_Check(o)) {
1051 d = PyFloat_AS_DOUBLE(o);
1052 /* all we need is to make the tuple different in either the 0.0
1053 * or -0.0 case from all others, just to avoid the "coercion".
1054 */
1055 if (d == 0.0 && copysign(1.0, d) < 0.0)
1056 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1057 else
1058 t = PyTuple_Pack(2, o, o->ob_type);
1059 }
1060 else if (PyComplex_Check(o)) {
1061 Py_complex z;
1062 int real_negzero, imag_negzero;
1063 /* For the complex case we must make complex(x, 0.)
1064 different from complex(x, -0.) and complex(0., y)
1065 different from complex(-0., y), for any x and y.
1066 All four complex zeros must be distinguished.*/
1067 z = PyComplex_AsCComplex(o);
1068 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1069 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1070 if (real_negzero && imag_negzero) {
1071 t = PyTuple_Pack(5, o, o->ob_type,
1072 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001073 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 else if (imag_negzero) {
1075 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 else if (real_negzero) {
1078 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1079 }
1080 else {
1081 t = PyTuple_Pack(2, o, o->ob_type);
1082 }
1083 }
1084 else {
1085 t = PyTuple_Pack(2, o, o->ob_type);
1086 }
1087 if (t == NULL)
1088 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 v = PyDict_GetItem(dict, t);
1091 if (!v) {
1092 if (PyErr_Occurred())
1093 return -1;
1094 arg = PyDict_Size(dict);
1095 v = PyLong_FromLong(arg);
1096 if (!v) {
1097 Py_DECREF(t);
1098 return -1;
1099 }
1100 if (PyDict_SetItem(dict, t, v) < 0) {
1101 Py_DECREF(t);
1102 Py_DECREF(v);
1103 return -1;
1104 }
1105 Py_DECREF(v);
1106 }
1107 else
1108 arg = PyLong_AsLong(v);
1109 Py_DECREF(t);
1110 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001111}
1112
1113static int
1114compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116{
1117 int arg = compiler_add_o(c, dict, o);
1118 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001119 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 return compiler_addop_i(c, opcode, arg);
1121}
1122
1123static int
1124compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126{
1127 int arg;
1128 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1129 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001130 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 arg = compiler_add_o(c, dict, mangled);
1132 Py_DECREF(mangled);
1133 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001134 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 return compiler_addop_i(c, opcode, arg);
1136}
1137
1138/* Add an opcode with an integer argument.
1139 Returns 0 on failure, 1 on success.
1140*/
1141
1142static int
1143compiler_addop_i(struct compiler *c, int opcode, int oparg)
1144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 struct instr *i;
1146 int off;
1147 off = compiler_next_instr(c, c->u->u_curblock);
1148 if (off < 0)
1149 return 0;
1150 i = &c->u->u_curblock->b_instr[off];
1151 i->i_opcode = opcode;
1152 i->i_oparg = oparg;
1153 i->i_hasarg = 1;
1154 compiler_set_lineno(c, off);
1155 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156}
1157
1158static int
1159compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 struct instr *i;
1162 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 assert(b != NULL);
1165 off = compiler_next_instr(c, c->u->u_curblock);
1166 if (off < 0)
1167 return 0;
1168 i = &c->u->u_curblock->b_instr[off];
1169 i->i_opcode = opcode;
1170 i->i_target = b;
1171 i->i_hasarg = 1;
1172 if (absolute)
1173 i->i_jabs = 1;
1174 else
1175 i->i_jrel = 1;
1176 compiler_set_lineno(c, off);
1177 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178}
1179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1181 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182 it as the current block. NEXT_BLOCK() also creates an implicit jump
1183 from the current block to the new block.
1184*/
1185
Thomas Wouters89f507f2006-12-13 04:49:30 +00001186/* The returns inside these macros make it impossible to decref objects
1187 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188*/
1189
1190
1191#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (compiler_use_new_block((C)) == NULL) \
1193 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194}
1195
1196#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (compiler_next_block((C)) == NULL) \
1198 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199}
1200
1201#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (!compiler_addop((C), (OP))) \
1203 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204}
1205
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001206#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (!compiler_addop((C), (OP))) { \
1208 compiler_exit_scope(c); \
1209 return 0; \
1210 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001211}
1212
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1215 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216}
1217
1218#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1220 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221}
1222
1223#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (!compiler_addop_i((C), (OP), (O))) \
1225 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226}
1227
1228#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (!compiler_addop_j((C), (OP), (O), 1)) \
1230 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231}
1232
1233#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (!compiler_addop_j((C), (OP), (O), 0)) \
1235 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
1238/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1239 the ASDL name to synthesize the name of the C type and the visit function.
1240*/
1241
1242#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (!compiler_visit_ ## TYPE((C), (V))) \
1244 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245}
1246
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001247#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (!compiler_visit_ ## TYPE((C), (V))) { \
1249 compiler_exit_scope(c); \
1250 return 0; \
1251 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001252}
1253
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (!compiler_visit_slice((C), (V), (CTX))) \
1256 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 int _i; \
1261 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1262 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1263 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1264 if (!compiler_visit_ ## TYPE((C), elt)) \
1265 return 0; \
1266 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001269#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 int _i; \
1271 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1272 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1273 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1274 if (!compiler_visit_ ## TYPE((C), elt)) { \
1275 compiler_exit_scope(c); \
1276 return 0; \
1277 } \
1278 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001279}
1280
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281static int
1282compiler_isdocstring(stmt_ty s)
1283{
1284 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001285 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001286 return s->v.Expr.value->kind == Str_kind;
1287}
1288
1289/* Compile a sequence of statements, checking for a docstring. */
1290
1291static int
1292compiler_body(struct compiler *c, asdl_seq *stmts)
1293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 int i = 0;
1295 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (!asdl_seq_LEN(stmts))
1298 return 1;
1299 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001300 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 /* don't generate docstrings if -OO */
1302 i = 1;
1303 VISIT(c, expr, st->v.Expr.value);
1304 if (!compiler_nameop(c, __doc__, Store))
1305 return 0;
1306 }
1307 for (; i < asdl_seq_LEN(stmts); i++)
1308 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1309 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
1312static PyCodeObject *
1313compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyCodeObject *co;
1316 int addNone = 1;
1317 static PyObject *module;
1318 if (!module) {
1319 module = PyUnicode_InternFromString("<module>");
1320 if (!module)
1321 return NULL;
1322 }
1323 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001324 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 return NULL;
1326 switch (mod->kind) {
1327 case Module_kind:
1328 if (!compiler_body(c, mod->v.Module.body)) {
1329 compiler_exit_scope(c);
1330 return 0;
1331 }
1332 break;
1333 case Interactive_kind:
1334 c->c_interactive = 1;
1335 VISIT_SEQ_IN_SCOPE(c, stmt,
1336 mod->v.Interactive.body);
1337 break;
1338 case Expression_kind:
1339 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1340 addNone = 0;
1341 break;
1342 case Suite_kind:
1343 PyErr_SetString(PyExc_SystemError,
1344 "suite should not be possible");
1345 return 0;
1346 default:
1347 PyErr_Format(PyExc_SystemError,
1348 "module kind %d should not be possible",
1349 mod->kind);
1350 return 0;
1351 }
1352 co = assemble(c, addNone);
1353 compiler_exit_scope(c);
1354 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001355}
1356
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357/* The test for LOCAL must come before the test for FREE in order to
1358 handle classes where name is both local and free. The local var is
1359 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001360*/
1361
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362static int
1363get_ref_type(struct compiler *c, PyObject *name)
1364{
Benjamin Peterson312595c2013-05-15 15:26:42 -05001365 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1366 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1367 return CELL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 int scope = PyST_GetScope(c->u->u_ste, name);
1369 if (scope == 0) {
1370 char buf[350];
1371 PyOS_snprintf(buf, sizeof(buf),
1372 "unknown scope for %.100s in %.100s(%s) in %s\n"
1373 "symbols: %s\nlocals: %s\nglobals: %s",
1374 PyBytes_AS_STRING(name),
1375 PyBytes_AS_STRING(c->u->u_name),
1376 PyObject_REPR(c->u->u_ste->ste_id),
1377 c->c_filename,
1378 PyObject_REPR(c->u->u_ste->ste_symbols),
1379 PyObject_REPR(c->u->u_varnames),
1380 PyObject_REPR(c->u->u_names)
1381 );
1382 Py_FatalError(buf);
1383 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386}
1387
1388static int
1389compiler_lookup_arg(PyObject *dict, PyObject *name)
1390{
1391 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001392 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001394 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001396 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001398 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001399 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400}
1401
1402static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001403compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001406 if (qualname == NULL)
1407 qualname = co->co_name;
1408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (free == 0) {
1410 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001411 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 ADDOP_I(c, MAKE_FUNCTION, args);
1413 return 1;
1414 }
1415 for (i = 0; i < free; ++i) {
1416 /* Bypass com_addop_varname because it will generate
1417 LOAD_DEREF but LOAD_CLOSURE is needed.
1418 */
1419 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1420 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* Special case: If a class contains a method with a
1423 free variable that has the same name as a method,
1424 the name will be considered free *and* local in the
1425 class. It should be handled by the closure, as
1426 well as by the normal name loookup logic.
1427 */
1428 reftype = get_ref_type(c, name);
1429 if (reftype == CELL)
1430 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1431 else /* (reftype == FREE) */
1432 arg = compiler_lookup_arg(c->u->u_freevars, name);
1433 if (arg == -1) {
1434 fprintf(stderr,
1435 "lookup %s in %s %d %d\n"
1436 "freevars of %s: %s\n",
1437 PyObject_REPR(name),
1438 PyBytes_AS_STRING(c->u->u_name),
1439 reftype, arg,
1440 _PyUnicode_AsString(co->co_name),
1441 PyObject_REPR(co->co_freevars));
1442 Py_FatalError("compiler_make_closure()");
1443 }
1444 ADDOP_I(c, LOAD_CLOSURE, arg);
1445 }
1446 ADDOP_I(c, BUILD_TUPLE, free);
1447 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001448 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 ADDOP_I(c, MAKE_CLOSURE, args);
1450 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451}
1452
1453static int
1454compiler_decorators(struct compiler *c, asdl_seq* decos)
1455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 if (!decos)
1459 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1462 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1463 }
1464 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465}
1466
1467static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001468compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 int i, default_count = 0;
1472 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1473 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1474 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1475 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001476 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1477 if (!mangled)
1478 return -1;
1479 ADDOP_O(c, LOAD_CONST, mangled, consts);
1480 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_visit_expr(c, default_)) {
1482 return -1;
1483 }
1484 default_count++;
1485 }
1486 }
1487 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001488}
1489
1490static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001491compiler_visit_argannotation(struct compiler *c, identifier id,
1492 expr_ty annotation, PyObject *names)
1493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (annotation) {
1495 VISIT(c, expr, annotation);
1496 if (PyList_Append(names, id))
1497 return -1;
1498 }
1499 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001500}
1501
1502static int
1503compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1504 PyObject *names)
1505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 int i, error;
1507 for (i = 0; i < asdl_seq_LEN(args); i++) {
1508 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1509 error = compiler_visit_argannotation(
1510 c,
1511 arg->arg,
1512 arg->annotation,
1513 names);
1514 if (error)
1515 return error;
1516 }
1517 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001518}
1519
1520static int
1521compiler_visit_annotations(struct compiler *c, arguments_ty args,
1522 expr_ty returns)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 /* Push arg annotations and a list of the argument names. Return the #
1525 of items pushed. The expressions are evaluated out-of-order wrt the
1526 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1529 */
1530 static identifier return_str;
1531 PyObject *names;
1532 int len;
1533 names = PyList_New(0);
1534 if (!names)
1535 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (compiler_visit_argannotations(c, args->args, names))
1538 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001539 if (args->vararg && args->vararg->annotation &&
1540 compiler_visit_argannotation(c, args->vararg->arg,
1541 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 goto error;
1543 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1544 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001545 if (args->kwarg && args->kwarg->annotation &&
1546 compiler_visit_argannotation(c, args->kwarg->arg,
1547 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (!return_str) {
1551 return_str = PyUnicode_InternFromString("return");
1552 if (!return_str)
1553 goto error;
1554 }
1555 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1556 goto error;
1557 }
1558
1559 len = PyList_GET_SIZE(names);
1560 if (len > 65534) {
1561 /* len must fit in 16 bits, and len is incremented below */
1562 PyErr_SetString(PyExc_SyntaxError,
1563 "too many annotations");
1564 goto error;
1565 }
1566 if (len) {
1567 /* convert names to a tuple and place on stack */
1568 PyObject *elt;
1569 int i;
1570 PyObject *s = PyTuple_New(len);
1571 if (!s)
1572 goto error;
1573 for (i = 0; i < len; i++) {
1574 elt = PyList_GET_ITEM(names, i);
1575 Py_INCREF(elt);
1576 PyTuple_SET_ITEM(s, i, elt);
1577 }
1578 ADDOP_O(c, LOAD_CONST, s, consts);
1579 Py_DECREF(s);
1580 len++; /* include the just-pushed tuple */
1581 }
1582 Py_DECREF(names);
1583 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001584
1585error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 Py_DECREF(names);
1587 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001588}
1589
1590static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591compiler_function(struct compiler *c, stmt_ty s)
1592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001594 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 arguments_ty args = s->v.FunctionDef.args;
1596 expr_ty returns = s->v.FunctionDef.returns;
1597 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1598 stmt_ty st;
1599 int i, n, docstring, kw_default_count = 0, arglength;
1600 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 if (!compiler_decorators(c, decos))
1605 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001606 if (args->defaults)
1607 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if (args->kwonlyargs) {
1609 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1610 args->kw_defaults);
1611 if (res < 0)
1612 return 0;
1613 kw_default_count = res;
1614 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 num_annotations = compiler_visit_annotations(c, args, returns);
1616 if (num_annotations < 0)
1617 return 0;
1618 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001619
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001620 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1621 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 s->lineno))
1623 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1626 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001627 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 first_const = st->v.Expr.value->v.Str.s;
1629 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1630 compiler_exit_scope(c);
1631 return 0;
1632 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 c->u->u_argcount = asdl_seq_LEN(args->args);
1635 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1636 n = asdl_seq_LEN(s->v.FunctionDef.body);
1637 /* if there was a docstring, we need to skip the first statement */
1638 for (i = docstring; i < n; i++) {
1639 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1640 VISIT_IN_SCOPE(c, stmt, st);
1641 }
1642 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001643 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001645 if (qualname == NULL || co == NULL) {
1646 Py_XDECREF(qualname);
1647 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001649 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 arglength = asdl_seq_LEN(args->defaults);
1652 arglength |= kw_default_count << 8;
1653 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001654 compiler_make_closure(c, co, arglength, qualname);
1655 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 /* decorators */
1659 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1660 ADDOP_I(c, CALL_FUNCTION, 1);
1661 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001664}
1665
1666static int
1667compiler_class(struct compiler *c, stmt_ty s)
1668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PyCodeObject *co;
1670 PyObject *str;
1671 int i;
1672 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (!compiler_decorators(c, decos))
1675 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 /* ultimately generate code for:
1678 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1679 where:
1680 <func> is a function/closure created from the class body;
1681 it has a single argument (__locals__) where the dict
1682 (or MutableSequence) representing the locals is passed
1683 <name> is the class name
1684 <bases> is the positional arguments and *varargs argument
1685 <keywords> is the keyword arguments and **kwds argument
1686 This borrows from compiler_call.
1687 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001690 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1691 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 return 0;
1693 /* this block represents what we do in the new scope */
1694 {
1695 /* use the class name for name mangling */
1696 Py_INCREF(s->v.ClassDef.name);
1697 Py_XDECREF(c->u->u_private);
1698 c->u->u_private = s->v.ClassDef.name;
1699 /* force it to have one mandatory argument */
1700 c->u->u_argcount = 1;
1701 /* load the first argument (__locals__) ... */
1702 ADDOP_I(c, LOAD_FAST, 0);
1703 /* ... and store it into f_locals */
1704 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1705 /* load (global) __name__ ... */
1706 str = PyUnicode_InternFromString("__name__");
1707 if (!str || !compiler_nameop(c, str, Load)) {
1708 Py_XDECREF(str);
1709 compiler_exit_scope(c);
1710 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001711 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 Py_DECREF(str);
1713 /* ... and store it as __module__ */
1714 str = PyUnicode_InternFromString("__module__");
1715 if (!str || !compiler_nameop(c, str, Store)) {
1716 Py_XDECREF(str);
1717 compiler_exit_scope(c);
1718 return 0;
1719 }
1720 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001721 /* store the __qualname__ */
1722 str = compiler_scope_qualname(c);
1723 if (!str) {
1724 compiler_exit_scope(c);
1725 return 0;
1726 }
1727 ADDOP_O(c, LOAD_CONST, str, consts);
1728 Py_DECREF(str);
1729 str = PyUnicode_InternFromString("__qualname__");
1730 if (!str || !compiler_nameop(c, str, Store)) {
1731 Py_XDECREF(str);
1732 compiler_exit_scope(c);
1733 return 0;
1734 }
1735 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* compile the body proper */
1737 if (!compiler_body(c, s->v.ClassDef.body)) {
1738 compiler_exit_scope(c);
1739 return 0;
1740 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001741 if (c->u->u_ste->ste_needs_class_closure) {
1742 /* return the (empty) __class__ cell */
1743 str = PyUnicode_InternFromString("__class__");
1744 if (str == NULL) {
1745 compiler_exit_scope(c);
1746 return 0;
1747 }
1748 i = compiler_lookup_arg(c->u->u_cellvars, str);
1749 Py_DECREF(str);
1750 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* Return the cell where to store __class__ */
1752 ADDOP_I(c, LOAD_CLOSURE, i);
1753 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001754 else {
1755 assert(PyDict_Size(c->u->u_cellvars) == 0);
1756 /* This happens when nobody references the cell. Return None. */
1757 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1760 /* create the code object */
1761 co = assemble(c, 1);
1762 }
1763 /* leave the new scope */
1764 compiler_exit_scope(c);
1765 if (co == NULL)
1766 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* 2. load the 'build_class' function */
1769 ADDOP(c, LOAD_BUILD_CLASS);
1770
1771 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001772 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 Py_DECREF(co);
1774
1775 /* 4. load class name */
1776 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1777
1778 /* 5. generate the rest of the code for the call */
1779 if (!compiler_call_helper(c, 2,
1780 s->v.ClassDef.bases,
1781 s->v.ClassDef.keywords,
1782 s->v.ClassDef.starargs,
1783 s->v.ClassDef.kwargs))
1784 return 0;
1785
1786 /* 6. apply decorators */
1787 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1788 ADDOP_I(c, CALL_FUNCTION, 1);
1789 }
1790
1791 /* 7. store into <name> */
1792 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1793 return 0;
1794 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795}
1796
1797static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001798compiler_ifexp(struct compiler *c, expr_ty e)
1799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 basicblock *end, *next;
1801
1802 assert(e->kind == IfExp_kind);
1803 end = compiler_new_block(c);
1804 if (end == NULL)
1805 return 0;
1806 next = compiler_new_block(c);
1807 if (next == NULL)
1808 return 0;
1809 VISIT(c, expr, e->v.IfExp.test);
1810 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1811 VISIT(c, expr, e->v.IfExp.body);
1812 ADDOP_JREL(c, JUMP_FORWARD, end);
1813 compiler_use_next_block(c, next);
1814 VISIT(c, expr, e->v.IfExp.orelse);
1815 compiler_use_next_block(c, end);
1816 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001817}
1818
1819static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820compiler_lambda(struct compiler *c, expr_ty e)
1821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001823 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 static identifier name;
1825 int kw_default_count = 0, arglength;
1826 arguments_ty args = e->v.Lambda.args;
1827 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (!name) {
1830 name = PyUnicode_InternFromString("<lambda>");
1831 if (!name)
1832 return 0;
1833 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001835 if (args->defaults)
1836 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (args->kwonlyargs) {
1838 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1839 args->kw_defaults);
1840 if (res < 0) return 0;
1841 kw_default_count = res;
1842 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001843 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1844 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* Make None the first constant, so the lambda can't have a
1848 docstring. */
1849 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1850 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 c->u->u_argcount = asdl_seq_LEN(args->args);
1853 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1854 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1855 if (c->u->u_ste->ste_generator) {
1856 ADDOP_IN_SCOPE(c, POP_TOP);
1857 }
1858 else {
1859 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1860 }
1861 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001862 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001864 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 arglength = asdl_seq_LEN(args->defaults);
1868 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001869 compiler_make_closure(c, co, arglength, qualname);
1870 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 Py_DECREF(co);
1872
1873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874}
1875
1876static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877compiler_if(struct compiler *c, stmt_ty s)
1878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 basicblock *end, *next;
1880 int constant;
1881 assert(s->kind == If_kind);
1882 end = compiler_new_block(c);
1883 if (end == NULL)
1884 return 0;
1885
Georg Brandl8334fd92010-12-04 10:26:46 +00001886 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* constant = 0: "if 0"
1888 * constant = 1: "if 1", "if 2", ...
1889 * constant = -1: rest */
1890 if (constant == 0) {
1891 if (s->v.If.orelse)
1892 VISIT_SEQ(c, stmt, s->v.If.orelse);
1893 } else if (constant == 1) {
1894 VISIT_SEQ(c, stmt, s->v.If.body);
1895 } else {
1896 if (s->v.If.orelse) {
1897 next = compiler_new_block(c);
1898 if (next == NULL)
1899 return 0;
1900 }
1901 else
1902 next = end;
1903 VISIT(c, expr, s->v.If.test);
1904 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1905 VISIT_SEQ(c, stmt, s->v.If.body);
1906 ADDOP_JREL(c, JUMP_FORWARD, end);
1907 if (s->v.If.orelse) {
1908 compiler_use_next_block(c, next);
1909 VISIT_SEQ(c, stmt, s->v.If.orelse);
1910 }
1911 }
1912 compiler_use_next_block(c, end);
1913 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914}
1915
1916static int
1917compiler_for(struct compiler *c, stmt_ty s)
1918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 start = compiler_new_block(c);
1922 cleanup = compiler_new_block(c);
1923 end = compiler_new_block(c);
1924 if (start == NULL || end == NULL || cleanup == NULL)
1925 return 0;
1926 ADDOP_JREL(c, SETUP_LOOP, end);
1927 if (!compiler_push_fblock(c, LOOP, start))
1928 return 0;
1929 VISIT(c, expr, s->v.For.iter);
1930 ADDOP(c, GET_ITER);
1931 compiler_use_next_block(c, start);
1932 ADDOP_JREL(c, FOR_ITER, cleanup);
1933 VISIT(c, expr, s->v.For.target);
1934 VISIT_SEQ(c, stmt, s->v.For.body);
1935 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1936 compiler_use_next_block(c, cleanup);
1937 ADDOP(c, POP_BLOCK);
1938 compiler_pop_fblock(c, LOOP, start);
1939 VISIT_SEQ(c, stmt, s->v.For.orelse);
1940 compiler_use_next_block(c, end);
1941 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942}
1943
1944static int
1945compiler_while(struct compiler *c, stmt_ty s)
1946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001948 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 if (constant == 0) {
1951 if (s->v.While.orelse)
1952 VISIT_SEQ(c, stmt, s->v.While.orelse);
1953 return 1;
1954 }
1955 loop = compiler_new_block(c);
1956 end = compiler_new_block(c);
1957 if (constant == -1) {
1958 anchor = compiler_new_block(c);
1959 if (anchor == NULL)
1960 return 0;
1961 }
1962 if (loop == NULL || end == NULL)
1963 return 0;
1964 if (s->v.While.orelse) {
1965 orelse = compiler_new_block(c);
1966 if (orelse == NULL)
1967 return 0;
1968 }
1969 else
1970 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 ADDOP_JREL(c, SETUP_LOOP, end);
1973 compiler_use_next_block(c, loop);
1974 if (!compiler_push_fblock(c, LOOP, loop))
1975 return 0;
1976 if (constant == -1) {
1977 VISIT(c, expr, s->v.While.test);
1978 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1979 }
1980 VISIT_SEQ(c, stmt, s->v.While.body);
1981 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 /* XXX should the two POP instructions be in a separate block
1984 if there is no else clause ?
1985 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (constant == -1) {
1988 compiler_use_next_block(c, anchor);
1989 ADDOP(c, POP_BLOCK);
1990 }
1991 compiler_pop_fblock(c, LOOP, loop);
1992 if (orelse != NULL) /* what if orelse is just pass? */
1993 VISIT_SEQ(c, stmt, s->v.While.orelse);
1994 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997}
1998
1999static int
2000compiler_continue(struct compiler *c)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2003 static const char IN_FINALLY_ERROR_MSG[] =
2004 "'continue' not supported inside 'finally' clause";
2005 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (!c->u->u_nfblocks)
2008 return compiler_error(c, LOOP_ERROR_MSG);
2009 i = c->u->u_nfblocks - 1;
2010 switch (c->u->u_fblock[i].fb_type) {
2011 case LOOP:
2012 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2013 break;
2014 case EXCEPT:
2015 case FINALLY_TRY:
2016 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2017 /* Prevent continue anywhere under a finally
2018 even if hidden in a sub-try or except. */
2019 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2020 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2021 }
2022 if (i == -1)
2023 return compiler_error(c, LOOP_ERROR_MSG);
2024 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2025 break;
2026 case FINALLY_END:
2027 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2028 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031}
2032
2033/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034
2035 SETUP_FINALLY L
2036 <code for body>
2037 POP_BLOCK
2038 LOAD_CONST <None>
2039 L: <code for finalbody>
2040 END_FINALLY
2041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042 The special instructions use the block stack. Each block
2043 stack entry contains the instruction that created it (here
2044 SETUP_FINALLY), the level of the value stack at the time the
2045 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 Pushes the current value stack level and the label
2049 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 Pops en entry from the block stack, and pops the value
2052 stack until its level is the same as indicated on the
2053 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 Pops a variable number of entries from the *value* stack
2056 and re-raises the exception they specify. The number of
2057 entries popped depends on the (pseudo) exception type.
2058
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 The block stack is unwound when an exception is raised:
2060 when a SETUP_FINALLY entry is found, the exception is pushed
2061 onto the value stack (and the exception condition is cleared),
2062 and the interpreter jumps to the label gotten from the block
2063 stack.
2064*/
2065
2066static int
2067compiler_try_finally(struct compiler *c, stmt_ty s)
2068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 basicblock *body, *end;
2070 body = compiler_new_block(c);
2071 end = compiler_new_block(c);
2072 if (body == NULL || end == NULL)
2073 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 ADDOP_JREL(c, SETUP_FINALLY, end);
2076 compiler_use_next_block(c, body);
2077 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2078 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002079 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2080 if (!compiler_try_except(c, s))
2081 return 0;
2082 }
2083 else {
2084 VISIT_SEQ(c, stmt, s->v.Try.body);
2085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 ADDOP(c, POP_BLOCK);
2087 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2090 compiler_use_next_block(c, end);
2091 if (!compiler_push_fblock(c, FINALLY_END, end))
2092 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002093 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 ADDOP(c, END_FINALLY);
2095 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098}
2099
2100/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002101 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 (The contents of the value stack is shown in [], with the top
2103 at the right; 'tb' is trace-back info, 'val' the exception's
2104 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105
2106 Value stack Label Instruction Argument
2107 [] SETUP_EXCEPT L1
2108 [] <code for S>
2109 [] POP_BLOCK
2110 [] JUMP_FORWARD L0
2111
2112 [tb, val, exc] L1: DUP )
2113 [tb, val, exc, exc] <evaluate E1> )
2114 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2115 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2116 [tb, val, exc] POP
2117 [tb, val] <assign to V1> (or POP if no V1)
2118 [tb] POP
2119 [] <code for S1>
2120 JUMP_FORWARD L0
2121
2122 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 .............................etc.......................
2124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2126
2127 [] L0: <next statement>
2128
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 Of course, parts are not generated if Vi or Ei is not present.
2130*/
2131static int
2132compiler_try_except(struct compiler *c, stmt_ty s)
2133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 basicblock *body, *orelse, *except, *end;
2135 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 body = compiler_new_block(c);
2138 except = compiler_new_block(c);
2139 orelse = compiler_new_block(c);
2140 end = compiler_new_block(c);
2141 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2142 return 0;
2143 ADDOP_JREL(c, SETUP_EXCEPT, except);
2144 compiler_use_next_block(c, body);
2145 if (!compiler_push_fblock(c, EXCEPT, body))
2146 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002147 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 ADDOP(c, POP_BLOCK);
2149 compiler_pop_fblock(c, EXCEPT, body);
2150 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002151 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 compiler_use_next_block(c, except);
2153 for (i = 0; i < n; i++) {
2154 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002155 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 if (!handler->v.ExceptHandler.type && i < n-1)
2157 return compiler_error(c, "default 'except:' must be last");
2158 c->u->u_lineno_set = 0;
2159 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002160 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 except = compiler_new_block(c);
2162 if (except == NULL)
2163 return 0;
2164 if (handler->v.ExceptHandler.type) {
2165 ADDOP(c, DUP_TOP);
2166 VISIT(c, expr, handler->v.ExceptHandler.type);
2167 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2168 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2169 }
2170 ADDOP(c, POP_TOP);
2171 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002172 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002173
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002174 cleanup_end = compiler_new_block(c);
2175 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002176 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002177 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002178
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002179 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2180 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002182 /*
2183 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002184 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002185 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002186 try:
2187 # body
2188 finally:
2189 name = None
2190 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002191 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002193 /* second try: */
2194 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2195 compiler_use_next_block(c, cleanup_body);
2196 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2197 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002199 /* second # body */
2200 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2201 ADDOP(c, POP_BLOCK);
2202 ADDOP(c, POP_EXCEPT);
2203 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002205 /* finally: */
2206 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2207 compiler_use_next_block(c, cleanup_end);
2208 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2209 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002211 /* name = None */
2212 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2213 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002215 /* del name */
2216 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002218 ADDOP(c, END_FINALLY);
2219 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 }
2221 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002222 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002224 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002225 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002226 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227
Guido van Rossumb940e112007-01-10 16:19:56 +00002228 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002229 ADDOP(c, POP_TOP);
2230 compiler_use_next_block(c, cleanup_body);
2231 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2232 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002234 ADDOP(c, POP_EXCEPT);
2235 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 }
2237 ADDOP_JREL(c, JUMP_FORWARD, end);
2238 compiler_use_next_block(c, except);
2239 }
2240 ADDOP(c, END_FINALLY);
2241 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002242 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 compiler_use_next_block(c, end);
2244 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245}
2246
2247static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002248compiler_try(struct compiler *c, stmt_ty s) {
2249 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2250 return compiler_try_finally(c, s);
2251 else
2252 return compiler_try_except(c, s);
2253}
2254
2255
2256static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257compiler_import_as(struct compiler *c, identifier name, identifier asname)
2258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* The IMPORT_NAME opcode was already generated. This function
2260 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 If there is a dot in name, we need to split it and emit a
2263 LOAD_ATTR for each name.
2264 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2266 PyUnicode_GET_LENGTH(name), 1);
2267 if (dot == -2)
2268 return -1;
2269 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002271 Py_ssize_t pos = dot + 1;
2272 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002274 dot = PyUnicode_FindChar(name, '.', pos,
2275 PyUnicode_GET_LENGTH(name), 1);
2276 if (dot == -2)
2277 return -1;
2278 attr = PyUnicode_Substring(name, pos,
2279 (dot != -1) ? dot :
2280 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (!attr)
2282 return -1;
2283 ADDOP_O(c, LOAD_ATTR, attr, names);
2284 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002285 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 }
2287 }
2288 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289}
2290
2291static int
2292compiler_import(struct compiler *c, stmt_ty s)
2293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* The Import node stores a module name like a.b.c as a single
2295 string. This is convenient for all cases except
2296 import a.b.c as d
2297 where we need to parse that string to extract the individual
2298 module names.
2299 XXX Perhaps change the representation to make this case simpler?
2300 */
2301 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 for (i = 0; i < n; i++) {
2304 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2305 int r;
2306 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 level = PyLong_FromLong(0);
2309 if (level == NULL)
2310 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 ADDOP_O(c, LOAD_CONST, level, consts);
2313 Py_DECREF(level);
2314 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2315 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 if (alias->asname) {
2318 r = compiler_import_as(c, alias->name, alias->asname);
2319 if (!r)
2320 return r;
2321 }
2322 else {
2323 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002324 Py_ssize_t dot = PyUnicode_FindChar(
2325 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2326 if (dot != -1)
2327 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002329 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_DECREF(tmp);
2331 }
2332 if (!r)
2333 return r;
2334 }
2335 }
2336 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337}
2338
2339static int
2340compiler_from_import(struct compiler *c, stmt_ty s)
2341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 PyObject *names = PyTuple_New(n);
2345 PyObject *level;
2346 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 if (!empty_string) {
2349 empty_string = PyUnicode_FromString("");
2350 if (!empty_string)
2351 return 0;
2352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (!names)
2355 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 level = PyLong_FromLong(s->v.ImportFrom.level);
2358 if (!level) {
2359 Py_DECREF(names);
2360 return 0;
2361 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* build up the names */
2364 for (i = 0; i < n; i++) {
2365 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2366 Py_INCREF(alias->name);
2367 PyTuple_SET_ITEM(names, i, alias->name);
2368 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2371 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2372 Py_DECREF(level);
2373 Py_DECREF(names);
2374 return compiler_error(c, "from __future__ imports must occur "
2375 "at the beginning of the file");
2376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 ADDOP_O(c, LOAD_CONST, level, consts);
2379 Py_DECREF(level);
2380 ADDOP_O(c, LOAD_CONST, names, consts);
2381 Py_DECREF(names);
2382 if (s->v.ImportFrom.module) {
2383 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2384 }
2385 else {
2386 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2387 }
2388 for (i = 0; i < n; i++) {
2389 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2390 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002392 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 assert(n == 1);
2394 ADDOP(c, IMPORT_STAR);
2395 return 1;
2396 }
2397
2398 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2399 store_name = alias->name;
2400 if (alias->asname)
2401 store_name = alias->asname;
2402
2403 if (!compiler_nameop(c, store_name, Store)) {
2404 Py_DECREF(names);
2405 return 0;
2406 }
2407 }
2408 /* remove imported module */
2409 ADDOP(c, POP_TOP);
2410 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411}
2412
2413static int
2414compiler_assert(struct compiler *c, stmt_ty s)
2415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 static PyObject *assertion_error = NULL;
2417 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002418
Georg Brandl8334fd92010-12-04 10:26:46 +00002419 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return 1;
2421 if (assertion_error == NULL) {
2422 assertion_error = PyUnicode_InternFromString("AssertionError");
2423 if (assertion_error == NULL)
2424 return 0;
2425 }
2426 if (s->v.Assert.test->kind == Tuple_kind &&
2427 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2428 const char* msg =
2429 "assertion is always true, perhaps remove parentheses?";
2430 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2431 c->u->u_lineno, NULL, NULL) == -1)
2432 return 0;
2433 }
2434 VISIT(c, expr, s->v.Assert.test);
2435 end = compiler_new_block(c);
2436 if (end == NULL)
2437 return 0;
2438 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2439 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2440 if (s->v.Assert.msg) {
2441 VISIT(c, expr, s->v.Assert.msg);
2442 ADDOP_I(c, CALL_FUNCTION, 1);
2443 }
2444 ADDOP_I(c, RAISE_VARARGS, 1);
2445 compiler_use_next_block(c, end);
2446 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447}
2448
2449static int
2450compiler_visit_stmt(struct compiler *c, stmt_ty s)
2451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* Always assign a lineno to the next instruction for a stmt. */
2455 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002456 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 switch (s->kind) {
2460 case FunctionDef_kind:
2461 return compiler_function(c, s);
2462 case ClassDef_kind:
2463 return compiler_class(c, s);
2464 case Return_kind:
2465 if (c->u->u_ste->ste_type != FunctionBlock)
2466 return compiler_error(c, "'return' outside function");
2467 if (s->v.Return.value) {
2468 VISIT(c, expr, s->v.Return.value);
2469 }
2470 else
2471 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2472 ADDOP(c, RETURN_VALUE);
2473 break;
2474 case Delete_kind:
2475 VISIT_SEQ(c, expr, s->v.Delete.targets)
2476 break;
2477 case Assign_kind:
2478 n = asdl_seq_LEN(s->v.Assign.targets);
2479 VISIT(c, expr, s->v.Assign.value);
2480 for (i = 0; i < n; i++) {
2481 if (i < n - 1)
2482 ADDOP(c, DUP_TOP);
2483 VISIT(c, expr,
2484 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2485 }
2486 break;
2487 case AugAssign_kind:
2488 return compiler_augassign(c, s);
2489 case For_kind:
2490 return compiler_for(c, s);
2491 case While_kind:
2492 return compiler_while(c, s);
2493 case If_kind:
2494 return compiler_if(c, s);
2495 case Raise_kind:
2496 n = 0;
2497 if (s->v.Raise.exc) {
2498 VISIT(c, expr, s->v.Raise.exc);
2499 n++;
2500 if (s->v.Raise.cause) {
2501 VISIT(c, expr, s->v.Raise.cause);
2502 n++;
2503 }
2504 }
2505 ADDOP_I(c, RAISE_VARARGS, n);
2506 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002507 case Try_kind:
2508 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 case Assert_kind:
2510 return compiler_assert(c, s);
2511 case Import_kind:
2512 return compiler_import(c, s);
2513 case ImportFrom_kind:
2514 return compiler_from_import(c, s);
2515 case Global_kind:
2516 case Nonlocal_kind:
2517 break;
2518 case Expr_kind:
2519 if (c->c_interactive && c->c_nestlevel <= 1) {
2520 VISIT(c, expr, s->v.Expr.value);
2521 ADDOP(c, PRINT_EXPR);
2522 }
2523 else if (s->v.Expr.value->kind != Str_kind &&
2524 s->v.Expr.value->kind != Num_kind) {
2525 VISIT(c, expr, s->v.Expr.value);
2526 ADDOP(c, POP_TOP);
2527 }
2528 break;
2529 case Pass_kind:
2530 break;
2531 case Break_kind:
2532 if (!compiler_in_loop(c))
2533 return compiler_error(c, "'break' outside loop");
2534 ADDOP(c, BREAK_LOOP);
2535 break;
2536 case Continue_kind:
2537 return compiler_continue(c);
2538 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002539 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 }
2541 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542}
2543
2544static int
2545unaryop(unaryop_ty op)
2546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 switch (op) {
2548 case Invert:
2549 return UNARY_INVERT;
2550 case Not:
2551 return UNARY_NOT;
2552 case UAdd:
2553 return UNARY_POSITIVE;
2554 case USub:
2555 return UNARY_NEGATIVE;
2556 default:
2557 PyErr_Format(PyExc_SystemError,
2558 "unary op %d should not be possible", op);
2559 return 0;
2560 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561}
2562
2563static int
2564binop(struct compiler *c, operator_ty op)
2565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 switch (op) {
2567 case Add:
2568 return BINARY_ADD;
2569 case Sub:
2570 return BINARY_SUBTRACT;
2571 case Mult:
2572 return BINARY_MULTIPLY;
2573 case Div:
2574 return BINARY_TRUE_DIVIDE;
2575 case Mod:
2576 return BINARY_MODULO;
2577 case Pow:
2578 return BINARY_POWER;
2579 case LShift:
2580 return BINARY_LSHIFT;
2581 case RShift:
2582 return BINARY_RSHIFT;
2583 case BitOr:
2584 return BINARY_OR;
2585 case BitXor:
2586 return BINARY_XOR;
2587 case BitAnd:
2588 return BINARY_AND;
2589 case FloorDiv:
2590 return BINARY_FLOOR_DIVIDE;
2591 default:
2592 PyErr_Format(PyExc_SystemError,
2593 "binary op %d should not be possible", op);
2594 return 0;
2595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596}
2597
2598static int
2599cmpop(cmpop_ty op)
2600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 switch (op) {
2602 case Eq:
2603 return PyCmp_EQ;
2604 case NotEq:
2605 return PyCmp_NE;
2606 case Lt:
2607 return PyCmp_LT;
2608 case LtE:
2609 return PyCmp_LE;
2610 case Gt:
2611 return PyCmp_GT;
2612 case GtE:
2613 return PyCmp_GE;
2614 case Is:
2615 return PyCmp_IS;
2616 case IsNot:
2617 return PyCmp_IS_NOT;
2618 case In:
2619 return PyCmp_IN;
2620 case NotIn:
2621 return PyCmp_NOT_IN;
2622 default:
2623 return PyCmp_BAD;
2624 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625}
2626
2627static int
2628inplace_binop(struct compiler *c, operator_ty op)
2629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 switch (op) {
2631 case Add:
2632 return INPLACE_ADD;
2633 case Sub:
2634 return INPLACE_SUBTRACT;
2635 case Mult:
2636 return INPLACE_MULTIPLY;
2637 case Div:
2638 return INPLACE_TRUE_DIVIDE;
2639 case Mod:
2640 return INPLACE_MODULO;
2641 case Pow:
2642 return INPLACE_POWER;
2643 case LShift:
2644 return INPLACE_LSHIFT;
2645 case RShift:
2646 return INPLACE_RSHIFT;
2647 case BitOr:
2648 return INPLACE_OR;
2649 case BitXor:
2650 return INPLACE_XOR;
2651 case BitAnd:
2652 return INPLACE_AND;
2653 case FloorDiv:
2654 return INPLACE_FLOOR_DIVIDE;
2655 default:
2656 PyErr_Format(PyExc_SystemError,
2657 "inplace binary op %d should not be possible", op);
2658 return 0;
2659 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660}
2661
2662static int
2663compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 int op, scope, arg;
2666 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 PyObject *dict = c->u->u_names;
2669 PyObject *mangled;
2670 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 mangled = _Py_Mangle(c->u->u_private, name);
2673 if (!mangled)
2674 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002675
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002676 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2677 PyUnicode_CompareWithASCIIString(name, "True") &&
2678 PyUnicode_CompareWithASCIIString(name, "False"));
2679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 op = 0;
2681 optype = OP_NAME;
2682 scope = PyST_GetScope(c->u->u_ste, mangled);
2683 switch (scope) {
2684 case FREE:
2685 dict = c->u->u_freevars;
2686 optype = OP_DEREF;
2687 break;
2688 case CELL:
2689 dict = c->u->u_cellvars;
2690 optype = OP_DEREF;
2691 break;
2692 case LOCAL:
2693 if (c->u->u_ste->ste_type == FunctionBlock)
2694 optype = OP_FAST;
2695 break;
2696 case GLOBAL_IMPLICIT:
2697 if (c->u->u_ste->ste_type == FunctionBlock &&
2698 !c->u->u_ste->ste_unoptimized)
2699 optype = OP_GLOBAL;
2700 break;
2701 case GLOBAL_EXPLICIT:
2702 optype = OP_GLOBAL;
2703 break;
2704 default:
2705 /* scope can be 0 */
2706 break;
2707 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002710 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 switch (optype) {
2713 case OP_DEREF:
2714 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002715 case Load:
2716 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2717 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 case Store: op = STORE_DEREF; break;
2719 case AugLoad:
2720 case AugStore:
2721 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002722 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 case Param:
2724 default:
2725 PyErr_SetString(PyExc_SystemError,
2726 "param invalid for deref variable");
2727 return 0;
2728 }
2729 break;
2730 case OP_FAST:
2731 switch (ctx) {
2732 case Load: op = LOAD_FAST; break;
2733 case Store: op = STORE_FAST; break;
2734 case Del: op = DELETE_FAST; break;
2735 case AugLoad:
2736 case AugStore:
2737 break;
2738 case Param:
2739 default:
2740 PyErr_SetString(PyExc_SystemError,
2741 "param invalid for local variable");
2742 return 0;
2743 }
2744 ADDOP_O(c, op, mangled, varnames);
2745 Py_DECREF(mangled);
2746 return 1;
2747 case OP_GLOBAL:
2748 switch (ctx) {
2749 case Load: op = LOAD_GLOBAL; break;
2750 case Store: op = STORE_GLOBAL; break;
2751 case Del: op = DELETE_GLOBAL; break;
2752 case AugLoad:
2753 case AugStore:
2754 break;
2755 case Param:
2756 default:
2757 PyErr_SetString(PyExc_SystemError,
2758 "param invalid for global variable");
2759 return 0;
2760 }
2761 break;
2762 case OP_NAME:
2763 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002764 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 case Store: op = STORE_NAME; break;
2766 case Del: op = DELETE_NAME; break;
2767 case AugLoad:
2768 case AugStore:
2769 break;
2770 case Param:
2771 default:
2772 PyErr_SetString(PyExc_SystemError,
2773 "param invalid for name variable");
2774 return 0;
2775 }
2776 break;
2777 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 assert(op);
2780 arg = compiler_add_o(c, dict, mangled);
2781 Py_DECREF(mangled);
2782 if (arg < 0)
2783 return 0;
2784 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785}
2786
2787static int
2788compiler_boolop(struct compiler *c, expr_ty e)
2789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 basicblock *end;
2791 int jumpi, i, n;
2792 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 assert(e->kind == BoolOp_kind);
2795 if (e->v.BoolOp.op == And)
2796 jumpi = JUMP_IF_FALSE_OR_POP;
2797 else
2798 jumpi = JUMP_IF_TRUE_OR_POP;
2799 end = compiler_new_block(c);
2800 if (end == NULL)
2801 return 0;
2802 s = e->v.BoolOp.values;
2803 n = asdl_seq_LEN(s) - 1;
2804 assert(n >= 0);
2805 for (i = 0; i < n; ++i) {
2806 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2807 ADDOP_JABS(c, jumpi, end);
2808 }
2809 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2810 compiler_use_next_block(c, end);
2811 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002812}
2813
2814static int
2815compiler_list(struct compiler *c, expr_ty e)
2816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 int n = asdl_seq_LEN(e->v.List.elts);
2818 if (e->v.List.ctx == Store) {
2819 int i, seen_star = 0;
2820 for (i = 0; i < n; i++) {
2821 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2822 if (elt->kind == Starred_kind && !seen_star) {
2823 if ((i >= (1 << 8)) ||
2824 (n-i-1 >= (INT_MAX >> 8)))
2825 return compiler_error(c,
2826 "too many expressions in "
2827 "star-unpacking assignment");
2828 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2829 seen_star = 1;
2830 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2831 } else if (elt->kind == Starred_kind) {
2832 return compiler_error(c,
2833 "two starred expressions in assignment");
2834 }
2835 }
2836 if (!seen_star) {
2837 ADDOP_I(c, UNPACK_SEQUENCE, n);
2838 }
2839 }
2840 VISIT_SEQ(c, expr, e->v.List.elts);
2841 if (e->v.List.ctx == Load) {
2842 ADDOP_I(c, BUILD_LIST, n);
2843 }
2844 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845}
2846
2847static int
2848compiler_tuple(struct compiler *c, expr_ty e)
2849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 int n = asdl_seq_LEN(e->v.Tuple.elts);
2851 if (e->v.Tuple.ctx == Store) {
2852 int i, seen_star = 0;
2853 for (i = 0; i < n; i++) {
2854 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2855 if (elt->kind == Starred_kind && !seen_star) {
2856 if ((i >= (1 << 8)) ||
2857 (n-i-1 >= (INT_MAX >> 8)))
2858 return compiler_error(c,
2859 "too many expressions in "
2860 "star-unpacking assignment");
2861 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2862 seen_star = 1;
2863 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2864 } else if (elt->kind == Starred_kind) {
2865 return compiler_error(c,
2866 "two starred expressions in assignment");
2867 }
2868 }
2869 if (!seen_star) {
2870 ADDOP_I(c, UNPACK_SEQUENCE, n);
2871 }
2872 }
2873 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2874 if (e->v.Tuple.ctx == Load) {
2875 ADDOP_I(c, BUILD_TUPLE, n);
2876 }
2877 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878}
2879
2880static int
2881compiler_compare(struct compiler *c, expr_ty e)
2882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 int i, n;
2884 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2887 VISIT(c, expr, e->v.Compare.left);
2888 n = asdl_seq_LEN(e->v.Compare.ops);
2889 assert(n > 0);
2890 if (n > 1) {
2891 cleanup = compiler_new_block(c);
2892 if (cleanup == NULL)
2893 return 0;
2894 VISIT(c, expr,
2895 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2896 }
2897 for (i = 1; i < n; i++) {
2898 ADDOP(c, DUP_TOP);
2899 ADDOP(c, ROT_THREE);
2900 ADDOP_I(c, COMPARE_OP,
2901 cmpop((cmpop_ty)(asdl_seq_GET(
2902 e->v.Compare.ops, i - 1))));
2903 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2904 NEXT_BLOCK(c);
2905 if (i < (n - 1))
2906 VISIT(c, expr,
2907 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2908 }
2909 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2910 ADDOP_I(c, COMPARE_OP,
2911 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2912 if (n > 1) {
2913 basicblock *end = compiler_new_block(c);
2914 if (end == NULL)
2915 return 0;
2916 ADDOP_JREL(c, JUMP_FORWARD, end);
2917 compiler_use_next_block(c, cleanup);
2918 ADDOP(c, ROT_TWO);
2919 ADDOP(c, POP_TOP);
2920 compiler_use_next_block(c, end);
2921 }
2922 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923}
2924
2925static int
2926compiler_call(struct compiler *c, expr_ty e)
2927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 VISIT(c, expr, e->v.Call.func);
2929 return compiler_call_helper(c, 0,
2930 e->v.Call.args,
2931 e->v.Call.keywords,
2932 e->v.Call.starargs,
2933 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002934}
2935
2936/* shared code between compiler_call and compiler_class */
2937static int
2938compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 int n, /* Args already pushed */
2940 asdl_seq *args,
2941 asdl_seq *keywords,
2942 expr_ty starargs,
2943 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 n += asdl_seq_LEN(args);
2948 VISIT_SEQ(c, expr, args);
2949 if (keywords) {
2950 VISIT_SEQ(c, keyword, keywords);
2951 n |= asdl_seq_LEN(keywords) << 8;
2952 }
2953 if (starargs) {
2954 VISIT(c, expr, starargs);
2955 code |= 1;
2956 }
2957 if (kwargs) {
2958 VISIT(c, expr, kwargs);
2959 code |= 2;
2960 }
2961 switch (code) {
2962 case 0:
2963 ADDOP_I(c, CALL_FUNCTION, n);
2964 break;
2965 case 1:
2966 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2967 break;
2968 case 2:
2969 ADDOP_I(c, CALL_FUNCTION_KW, n);
2970 break;
2971 case 3:
2972 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2973 break;
2974 }
2975 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976}
2977
Nick Coghlan650f0d02007-04-15 12:05:43 +00002978
2979/* List and set comprehensions and generator expressions work by creating a
2980 nested function to perform the actual iteration. This means that the
2981 iteration variables don't leak into the current scope.
2982 The defined function is called immediately following its definition, with the
2983 result of that call being the result of the expression.
2984 The LC/SC version returns the populated container, while the GE version is
2985 flagged in symtable.c as a generator, so it returns the generator object
2986 when the function is called.
2987 This code *knows* that the loop cannot contain break, continue, or return,
2988 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2989
2990 Possible cleanups:
2991 - iterate over the generator sequence instead of using recursion
2992*/
2993
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995compiler_comprehension_generator(struct compiler *c,
2996 asdl_seq *generators, int gen_index,
2997 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 /* generate code for the iterator, then each of the ifs,
3000 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 comprehension_ty gen;
3003 basicblock *start, *anchor, *skip, *if_cleanup;
3004 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 start = compiler_new_block(c);
3007 skip = compiler_new_block(c);
3008 if_cleanup = compiler_new_block(c);
3009 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3012 anchor == NULL)
3013 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 if (gen_index == 0) {
3018 /* Receive outermost iter as an implicit argument */
3019 c->u->u_argcount = 1;
3020 ADDOP_I(c, LOAD_FAST, 0);
3021 }
3022 else {
3023 /* Sub-iter - calculate on the fly */
3024 VISIT(c, expr, gen->iter);
3025 ADDOP(c, GET_ITER);
3026 }
3027 compiler_use_next_block(c, start);
3028 ADDOP_JREL(c, FOR_ITER, anchor);
3029 NEXT_BLOCK(c);
3030 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 /* XXX this needs to be cleaned up...a lot! */
3033 n = asdl_seq_LEN(gen->ifs);
3034 for (i = 0; i < n; i++) {
3035 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3036 VISIT(c, expr, e);
3037 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3038 NEXT_BLOCK(c);
3039 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 if (++gen_index < asdl_seq_LEN(generators))
3042 if (!compiler_comprehension_generator(c,
3043 generators, gen_index,
3044 elt, val, type))
3045 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 /* only append after the last for generator */
3048 if (gen_index >= asdl_seq_LEN(generators)) {
3049 /* comprehension specific code */
3050 switch (type) {
3051 case COMP_GENEXP:
3052 VISIT(c, expr, elt);
3053 ADDOP(c, YIELD_VALUE);
3054 ADDOP(c, POP_TOP);
3055 break;
3056 case COMP_LISTCOMP:
3057 VISIT(c, expr, elt);
3058 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3059 break;
3060 case COMP_SETCOMP:
3061 VISIT(c, expr, elt);
3062 ADDOP_I(c, SET_ADD, gen_index + 1);
3063 break;
3064 case COMP_DICTCOMP:
3065 /* With 'd[k] = v', v is evaluated before k, so we do
3066 the same. */
3067 VISIT(c, expr, val);
3068 VISIT(c, expr, elt);
3069 ADDOP_I(c, MAP_ADD, gen_index + 1);
3070 break;
3071 default:
3072 return 0;
3073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 compiler_use_next_block(c, skip);
3076 }
3077 compiler_use_next_block(c, if_cleanup);
3078 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3079 compiler_use_next_block(c, anchor);
3080
3081 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082}
3083
3084static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003085compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 PyCodeObject *co = NULL;
3089 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003090 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 outermost_iter = ((comprehension_ty)
3093 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003094
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003095 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3096 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 if (type != COMP_GENEXP) {
3100 int op;
3101 switch (type) {
3102 case COMP_LISTCOMP:
3103 op = BUILD_LIST;
3104 break;
3105 case COMP_SETCOMP:
3106 op = BUILD_SET;
3107 break;
3108 case COMP_DICTCOMP:
3109 op = BUILD_MAP;
3110 break;
3111 default:
3112 PyErr_Format(PyExc_SystemError,
3113 "unknown comprehension type %d", type);
3114 goto error_in_scope;
3115 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 ADDOP_I(c, op, 0);
3118 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 if (!compiler_comprehension_generator(c, generators, 0, elt,
3121 val, type))
3122 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 if (type != COMP_GENEXP) {
3125 ADDOP(c, RETURN_VALUE);
3126 }
3127
3128 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003129 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003131 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 goto error;
3133
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003134 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003136 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 Py_DECREF(co);
3138
3139 VISIT(c, expr, outermost_iter);
3140 ADDOP(c, GET_ITER);
3141 ADDOP_I(c, CALL_FUNCTION, 1);
3142 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003143error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003145error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003146 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 Py_XDECREF(co);
3148 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003149}
3150
3151static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152compiler_genexp(struct compiler *c, expr_ty e)
3153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 static identifier name;
3155 if (!name) {
3156 name = PyUnicode_FromString("<genexpr>");
3157 if (!name)
3158 return 0;
3159 }
3160 assert(e->kind == GeneratorExp_kind);
3161 return compiler_comprehension(c, e, COMP_GENEXP, name,
3162 e->v.GeneratorExp.generators,
3163 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164}
3165
3166static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003167compiler_listcomp(struct compiler *c, expr_ty e)
3168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 static identifier name;
3170 if (!name) {
3171 name = PyUnicode_FromString("<listcomp>");
3172 if (!name)
3173 return 0;
3174 }
3175 assert(e->kind == ListComp_kind);
3176 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3177 e->v.ListComp.generators,
3178 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003179}
3180
3181static int
3182compiler_setcomp(struct compiler *c, expr_ty e)
3183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 static identifier name;
3185 if (!name) {
3186 name = PyUnicode_FromString("<setcomp>");
3187 if (!name)
3188 return 0;
3189 }
3190 assert(e->kind == SetComp_kind);
3191 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3192 e->v.SetComp.generators,
3193 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003194}
3195
3196
3197static int
3198compiler_dictcomp(struct compiler *c, expr_ty e)
3199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 static identifier name;
3201 if (!name) {
3202 name = PyUnicode_FromString("<dictcomp>");
3203 if (!name)
3204 return 0;
3205 }
3206 assert(e->kind == DictComp_kind);
3207 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3208 e->v.DictComp.generators,
3209 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003210}
3211
3212
3213static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214compiler_visit_keyword(struct compiler *c, keyword_ty k)
3215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3217 VISIT(c, expr, k->value);
3218 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219}
3220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 whether they are true or false.
3223
3224 Return values: 1 for true, 0 for false, -1 for non-constant.
3225 */
3226
3227static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003228expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 char *id;
3231 switch (e->kind) {
3232 case Ellipsis_kind:
3233 return 1;
3234 case Num_kind:
3235 return PyObject_IsTrue(e->v.Num.n);
3236 case Str_kind:
3237 return PyObject_IsTrue(e->v.Str.s);
3238 case Name_kind:
3239 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003240 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003241 if (id && strcmp(id, "__debug__") == 0)
3242 return !c->c_optimize;
3243 return -1;
3244 case NameConstant_kind: {
3245 PyObject *o = e->v.NameConstant.value;
3246 if (o == Py_None)
3247 return 0;
3248 else if (o == Py_True)
3249 return 1;
3250 else if (o == Py_False)
3251 return 0;
3252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 default:
3254 return -1;
3255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256}
3257
Guido van Rossumc2e20742006-02-27 22:32:47 +00003258/*
3259 Implements the with statement from PEP 343.
3260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003262
3263 with EXPR as VAR:
3264 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265
Guido van Rossumc2e20742006-02-27 22:32:47 +00003266 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267
Thomas Wouters477c8d52006-05-27 19:21:47 +00003268 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003269 exit = context.__exit__ # not calling it
3270 value = context.__enter__()
3271 try:
3272 VAR = value # if VAR present in the syntax
3273 BLOCK
3274 finally:
3275 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003277 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003279 exit(*exc)
3280 */
3281static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003282compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003283{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003284 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003285 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003286
3287 assert(s->kind == With_kind);
3288
Guido van Rossumc2e20742006-02-27 22:32:47 +00003289 block = compiler_new_block(c);
3290 finally = compiler_new_block(c);
3291 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003292 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003293
Thomas Wouters477c8d52006-05-27 19:21:47 +00003294 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003295 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003296 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003297
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003298 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003299 compiler_use_next_block(c, block);
3300 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003301 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003302 }
3303
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003304 if (item->optional_vars) {
3305 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003306 }
3307 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003309 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003310 }
3311
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003312 pos++;
3313 if (pos == asdl_seq_LEN(s->v.With.items))
3314 /* BLOCK code */
3315 VISIT_SEQ(c, stmt, s->v.With.body)
3316 else if (!compiler_with(c, s, pos))
3317 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003318
3319 /* End of try block; start the finally block */
3320 ADDOP(c, POP_BLOCK);
3321 compiler_pop_fblock(c, FINALLY_TRY, block);
3322
3323 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3324 compiler_use_next_block(c, finally);
3325 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003326 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003327
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003328 /* Finally block starts; context.__exit__ is on the stack under
3329 the exception or return information. Just issue our magic
3330 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003331 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003332
3333 /* Finally block ends. */
3334 ADDOP(c, END_FINALLY);
3335 compiler_pop_fblock(c, FINALLY_END, finally);
3336 return 1;
3337}
3338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339static int
3340compiler_visit_expr(struct compiler *c, expr_ty e)
3341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 /* If expr e has a different line number than the last expr/stmt,
3345 set a new line number for the next instruction.
3346 */
3347 if (e->lineno > c->u->u_lineno) {
3348 c->u->u_lineno = e->lineno;
3349 c->u->u_lineno_set = 0;
3350 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003351 /* Updating the column offset is always harmless. */
3352 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 switch (e->kind) {
3354 case BoolOp_kind:
3355 return compiler_boolop(c, e);
3356 case BinOp_kind:
3357 VISIT(c, expr, e->v.BinOp.left);
3358 VISIT(c, expr, e->v.BinOp.right);
3359 ADDOP(c, binop(c, e->v.BinOp.op));
3360 break;
3361 case UnaryOp_kind:
3362 VISIT(c, expr, e->v.UnaryOp.operand);
3363 ADDOP(c, unaryop(e->v.UnaryOp.op));
3364 break;
3365 case Lambda_kind:
3366 return compiler_lambda(c, e);
3367 case IfExp_kind:
3368 return compiler_ifexp(c, e);
3369 case Dict_kind:
3370 n = asdl_seq_LEN(e->v.Dict.values);
3371 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3372 for (i = 0; i < n; i++) {
3373 VISIT(c, expr,
3374 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3375 VISIT(c, expr,
3376 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3377 ADDOP(c, STORE_MAP);
3378 }
3379 break;
3380 case Set_kind:
3381 n = asdl_seq_LEN(e->v.Set.elts);
3382 VISIT_SEQ(c, expr, e->v.Set.elts);
3383 ADDOP_I(c, BUILD_SET, n);
3384 break;
3385 case GeneratorExp_kind:
3386 return compiler_genexp(c, e);
3387 case ListComp_kind:
3388 return compiler_listcomp(c, e);
3389 case SetComp_kind:
3390 return compiler_setcomp(c, e);
3391 case DictComp_kind:
3392 return compiler_dictcomp(c, e);
3393 case Yield_kind:
3394 if (c->u->u_ste->ste_type != FunctionBlock)
3395 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003396 if (e->v.Yield.value) {
3397 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 }
3399 else {
3400 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3401 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003402 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003404 case YieldFrom_kind:
3405 if (c->u->u_ste->ste_type != FunctionBlock)
3406 return compiler_error(c, "'yield' outside function");
3407 VISIT(c, expr, e->v.YieldFrom.value);
3408 ADDOP(c, GET_ITER);
3409 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3410 ADDOP(c, YIELD_FROM);
3411 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 case Compare_kind:
3413 return compiler_compare(c, e);
3414 case Call_kind:
3415 return compiler_call(c, e);
3416 case Num_kind:
3417 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3418 break;
3419 case Str_kind:
3420 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3421 break;
3422 case Bytes_kind:
3423 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3424 break;
3425 case Ellipsis_kind:
3426 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3427 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003428 case NameConstant_kind:
3429 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3430 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 /* The following exprs can be assignment targets. */
3432 case Attribute_kind:
3433 if (e->v.Attribute.ctx != AugStore)
3434 VISIT(c, expr, e->v.Attribute.value);
3435 switch (e->v.Attribute.ctx) {
3436 case AugLoad:
3437 ADDOP(c, DUP_TOP);
3438 /* Fall through to load */
3439 case Load:
3440 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3441 break;
3442 case AugStore:
3443 ADDOP(c, ROT_TWO);
3444 /* Fall through to save */
3445 case Store:
3446 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3447 break;
3448 case Del:
3449 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3450 break;
3451 case Param:
3452 default:
3453 PyErr_SetString(PyExc_SystemError,
3454 "param invalid in attribute expression");
3455 return 0;
3456 }
3457 break;
3458 case Subscript_kind:
3459 switch (e->v.Subscript.ctx) {
3460 case AugLoad:
3461 VISIT(c, expr, e->v.Subscript.value);
3462 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3463 break;
3464 case Load:
3465 VISIT(c, expr, e->v.Subscript.value);
3466 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3467 break;
3468 case AugStore:
3469 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3470 break;
3471 case Store:
3472 VISIT(c, expr, e->v.Subscript.value);
3473 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3474 break;
3475 case Del:
3476 VISIT(c, expr, e->v.Subscript.value);
3477 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3478 break;
3479 case Param:
3480 default:
3481 PyErr_SetString(PyExc_SystemError,
3482 "param invalid in subscript expression");
3483 return 0;
3484 }
3485 break;
3486 case Starred_kind:
3487 switch (e->v.Starred.ctx) {
3488 case Store:
3489 /* In all legitimate cases, the Starred node was already replaced
3490 * by compiler_list/compiler_tuple. XXX: is that okay? */
3491 return compiler_error(c,
3492 "starred assignment target must be in a list or tuple");
3493 default:
3494 return compiler_error(c,
3495 "can use starred expression only as assignment target");
3496 }
3497 break;
3498 case Name_kind:
3499 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3500 /* child nodes of List and Tuple will have expr_context set */
3501 case List_kind:
3502 return compiler_list(c, e);
3503 case Tuple_kind:
3504 return compiler_tuple(c, e);
3505 }
3506 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507}
3508
3509static int
3510compiler_augassign(struct compiler *c, stmt_ty s)
3511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 expr_ty e = s->v.AugAssign.target;
3513 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 switch (e->kind) {
3518 case Attribute_kind:
3519 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3520 AugLoad, e->lineno, e->col_offset, c->c_arena);
3521 if (auge == NULL)
3522 return 0;
3523 VISIT(c, expr, auge);
3524 VISIT(c, expr, s->v.AugAssign.value);
3525 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3526 auge->v.Attribute.ctx = AugStore;
3527 VISIT(c, expr, auge);
3528 break;
3529 case Subscript_kind:
3530 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3531 AugLoad, e->lineno, e->col_offset, c->c_arena);
3532 if (auge == NULL)
3533 return 0;
3534 VISIT(c, expr, auge);
3535 VISIT(c, expr, s->v.AugAssign.value);
3536 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3537 auge->v.Subscript.ctx = AugStore;
3538 VISIT(c, expr, auge);
3539 break;
3540 case Name_kind:
3541 if (!compiler_nameop(c, e->v.Name.id, Load))
3542 return 0;
3543 VISIT(c, expr, s->v.AugAssign.value);
3544 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3545 return compiler_nameop(c, e->v.Name.id, Store);
3546 default:
3547 PyErr_Format(PyExc_SystemError,
3548 "invalid node type (%d) for augmented assignment",
3549 e->kind);
3550 return 0;
3551 }
3552 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553}
3554
3555static int
3556compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 struct fblockinfo *f;
3559 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3560 PyErr_SetString(PyExc_SystemError,
3561 "too many statically nested blocks");
3562 return 0;
3563 }
3564 f = &c->u->u_fblock[c->u->u_nfblocks++];
3565 f->fb_type = t;
3566 f->fb_block = b;
3567 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568}
3569
3570static void
3571compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 struct compiler_unit *u = c->u;
3574 assert(u->u_nfblocks > 0);
3575 u->u_nfblocks--;
3576 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3577 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578}
3579
Thomas Wouters89f507f2006-12-13 04:49:30 +00003580static int
3581compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 int i;
3583 struct compiler_unit *u = c->u;
3584 for (i = 0; i < u->u_nfblocks; ++i) {
3585 if (u->u_fblock[i].fb_type == LOOP)
3586 return 1;
3587 }
3588 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003589}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590/* Raises a SyntaxError and returns 0.
3591 If something goes wrong, a different exception may be raised.
3592*/
3593
3594static int
3595compiler_error(struct compiler *c, const char *errstr)
3596{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003597 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3601 if (!loc) {
3602 Py_INCREF(Py_None);
3603 loc = Py_None;
3604 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003605 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003606 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 if (!u)
3608 goto exit;
3609 v = Py_BuildValue("(zO)", errstr, u);
3610 if (!v)
3611 goto exit;
3612 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 Py_DECREF(loc);
3615 Py_XDECREF(u);
3616 Py_XDECREF(v);
3617 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618}
3619
3620static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621compiler_handle_subscr(struct compiler *c, const char *kind,
3622 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 /* XXX this code is duplicated */
3627 switch (ctx) {
3628 case AugLoad: /* fall through to Load */
3629 case Load: op = BINARY_SUBSCR; break;
3630 case AugStore:/* fall through to Store */
3631 case Store: op = STORE_SUBSCR; break;
3632 case Del: op = DELETE_SUBSCR; break;
3633 case Param:
3634 PyErr_Format(PyExc_SystemError,
3635 "invalid %s kind %d in subscript\n",
3636 kind, ctx);
3637 return 0;
3638 }
3639 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003640 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 }
3642 else if (ctx == AugStore) {
3643 ADDOP(c, ROT_THREE);
3644 }
3645 ADDOP(c, op);
3646 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647}
3648
3649static int
3650compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 int n = 2;
3653 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 /* only handles the cases where BUILD_SLICE is emitted */
3656 if (s->v.Slice.lower) {
3657 VISIT(c, expr, s->v.Slice.lower);
3658 }
3659 else {
3660 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3661 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 if (s->v.Slice.upper) {
3664 VISIT(c, expr, s->v.Slice.upper);
3665 }
3666 else {
3667 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3668 }
3669
3670 if (s->v.Slice.step) {
3671 n++;
3672 VISIT(c, expr, s->v.Slice.step);
3673 }
3674 ADDOP_I(c, BUILD_SLICE, n);
3675 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676}
3677
3678static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3680 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 switch (s->kind) {
3683 case Slice_kind:
3684 return compiler_slice(c, s, ctx);
3685 case Index_kind:
3686 VISIT(c, expr, s->v.Index.value);
3687 break;
3688 case ExtSlice_kind:
3689 default:
3690 PyErr_SetString(PyExc_SystemError,
3691 "extended slice invalid in nested slice");
3692 return 0;
3693 }
3694 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695}
3696
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003697static int
3698compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 char * kindname = NULL;
3701 switch (s->kind) {
3702 case Index_kind:
3703 kindname = "index";
3704 if (ctx != AugStore) {
3705 VISIT(c, expr, s->v.Index.value);
3706 }
3707 break;
3708 case Slice_kind:
3709 kindname = "slice";
3710 if (ctx != AugStore) {
3711 if (!compiler_slice(c, s, ctx))
3712 return 0;
3713 }
3714 break;
3715 case ExtSlice_kind:
3716 kindname = "extended slice";
3717 if (ctx != AugStore) {
3718 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3719 for (i = 0; i < n; i++) {
3720 slice_ty sub = (slice_ty)asdl_seq_GET(
3721 s->v.ExtSlice.dims, i);
3722 if (!compiler_visit_nested_slice(c, sub, ctx))
3723 return 0;
3724 }
3725 ADDOP_I(c, BUILD_TUPLE, n);
3726 }
3727 break;
3728 default:
3729 PyErr_Format(PyExc_SystemError,
3730 "invalid subscript kind %d", s->kind);
3731 return 0;
3732 }
3733 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734}
3735
Thomas Wouters89f507f2006-12-13 04:49:30 +00003736/* End of the compiler section, beginning of the assembler section */
3737
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738/* do depth-first search of basic block graph, starting with block.
3739 post records the block indices in post-order.
3740
3741 XXX must handle implicit jumps from one block to next
3742*/
3743
Thomas Wouters89f507f2006-12-13 04:49:30 +00003744struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 PyObject *a_bytecode; /* string containing bytecode */
3746 int a_offset; /* offset into bytecode */
3747 int a_nblocks; /* number of reachable blocks */
3748 basicblock **a_postorder; /* list of blocks in dfs postorder */
3749 PyObject *a_lnotab; /* string containing lnotab */
3750 int a_lnotab_off; /* offset into lnotab */
3751 int a_lineno; /* last lineno of emitted instruction */
3752 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003753};
3754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755static void
3756dfs(struct compiler *c, basicblock *b, struct assembler *a)
3757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 int i;
3759 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 if (b->b_seen)
3762 return;
3763 b->b_seen = 1;
3764 if (b->b_next != NULL)
3765 dfs(c, b->b_next, a);
3766 for (i = 0; i < b->b_iused; i++) {
3767 instr = &b->b_instr[i];
3768 if (instr->i_jrel || instr->i_jabs)
3769 dfs(c, instr->i_target, a);
3770 }
3771 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772}
3773
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003774static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 int i, target_depth;
3778 struct instr *instr;
3779 if (b->b_seen || b->b_startdepth >= depth)
3780 return maxdepth;
3781 b->b_seen = 1;
3782 b->b_startdepth = depth;
3783 for (i = 0; i < b->b_iused; i++) {
3784 instr = &b->b_instr[i];
3785 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3786 if (depth > maxdepth)
3787 maxdepth = depth;
3788 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3789 if (instr->i_jrel || instr->i_jabs) {
3790 target_depth = depth;
3791 if (instr->i_opcode == FOR_ITER) {
3792 target_depth = depth-2;
3793 } else if (instr->i_opcode == SETUP_FINALLY ||
3794 instr->i_opcode == SETUP_EXCEPT) {
3795 target_depth = depth+3;
3796 if (target_depth > maxdepth)
3797 maxdepth = target_depth;
3798 }
3799 maxdepth = stackdepth_walk(c, instr->i_target,
3800 target_depth, maxdepth);
3801 if (instr->i_opcode == JUMP_ABSOLUTE ||
3802 instr->i_opcode == JUMP_FORWARD) {
3803 goto out; /* remaining code is dead */
3804 }
3805 }
3806 }
3807 if (b->b_next)
3808 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 b->b_seen = 0;
3811 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812}
3813
3814/* Find the flow path that needs the largest stack. We assume that
3815 * cycles in the flow graph have no net effect on the stack depth.
3816 */
3817static int
3818stackdepth(struct compiler *c)
3819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 basicblock *b, *entryblock;
3821 entryblock = NULL;
3822 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3823 b->b_seen = 0;
3824 b->b_startdepth = INT_MIN;
3825 entryblock = b;
3826 }
3827 if (!entryblock)
3828 return 0;
3829 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830}
3831
3832static int
3833assemble_init(struct assembler *a, int nblocks, int firstlineno)
3834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 memset(a, 0, sizeof(struct assembler));
3836 a->a_lineno = firstlineno;
3837 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3838 if (!a->a_bytecode)
3839 return 0;
3840 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3841 if (!a->a_lnotab)
3842 return 0;
3843 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3844 PyErr_NoMemory();
3845 return 0;
3846 }
3847 a->a_postorder = (basicblock **)PyObject_Malloc(
3848 sizeof(basicblock *) * nblocks);
3849 if (!a->a_postorder) {
3850 PyErr_NoMemory();
3851 return 0;
3852 }
3853 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854}
3855
3856static void
3857assemble_free(struct assembler *a)
3858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 Py_XDECREF(a->a_bytecode);
3860 Py_XDECREF(a->a_lnotab);
3861 if (a->a_postorder)
3862 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863}
3864
3865/* Return the size of a basic block in bytes. */
3866
3867static int
3868instrsize(struct instr *instr)
3869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 if (!instr->i_hasarg)
3871 return 1; /* 1 byte for the opcode*/
3872 if (instr->i_oparg > 0xffff)
3873 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3874 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875}
3876
3877static int
3878blocksize(basicblock *b)
3879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 int i;
3881 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 for (i = 0; i < b->b_iused; i++)
3884 size += instrsize(&b->b_instr[i]);
3885 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886}
3887
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003888/* Appends a pair to the end of the line number table, a_lnotab, representing
3889 the instruction's bytecode offset and line number. See
3890 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003891
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003892static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 int d_bytecode, d_lineno;
3896 int len;
3897 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 d_bytecode = a->a_offset - a->a_lineno_off;
3900 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 assert(d_bytecode >= 0);
3903 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 if(d_bytecode == 0 && d_lineno == 0)
3906 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 if (d_bytecode > 255) {
3909 int j, nbytes, ncodes = d_bytecode / 255;
3910 nbytes = a->a_lnotab_off + 2 * ncodes;
3911 len = PyBytes_GET_SIZE(a->a_lnotab);
3912 if (nbytes >= len) {
3913 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3914 len = nbytes;
3915 else if (len <= INT_MAX / 2)
3916 len *= 2;
3917 else {
3918 PyErr_NoMemory();
3919 return 0;
3920 }
3921 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3922 return 0;
3923 }
3924 lnotab = (unsigned char *)
3925 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3926 for (j = 0; j < ncodes; j++) {
3927 *lnotab++ = 255;
3928 *lnotab++ = 0;
3929 }
3930 d_bytecode -= ncodes * 255;
3931 a->a_lnotab_off += ncodes * 2;
3932 }
3933 assert(d_bytecode <= 255);
3934 if (d_lineno > 255) {
3935 int j, nbytes, ncodes = d_lineno / 255;
3936 nbytes = a->a_lnotab_off + 2 * ncodes;
3937 len = PyBytes_GET_SIZE(a->a_lnotab);
3938 if (nbytes >= len) {
3939 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3940 len = nbytes;
3941 else if (len <= INT_MAX / 2)
3942 len *= 2;
3943 else {
3944 PyErr_NoMemory();
3945 return 0;
3946 }
3947 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3948 return 0;
3949 }
3950 lnotab = (unsigned char *)
3951 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3952 *lnotab++ = d_bytecode;
3953 *lnotab++ = 255;
3954 d_bytecode = 0;
3955 for (j = 1; j < ncodes; j++) {
3956 *lnotab++ = 0;
3957 *lnotab++ = 255;
3958 }
3959 d_lineno -= ncodes * 255;
3960 a->a_lnotab_off += ncodes * 2;
3961 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 len = PyBytes_GET_SIZE(a->a_lnotab);
3964 if (a->a_lnotab_off + 2 >= len) {
3965 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3966 return 0;
3967 }
3968 lnotab = (unsigned char *)
3969 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 a->a_lnotab_off += 2;
3972 if (d_bytecode) {
3973 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003974 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 }
3976 else { /* First line of a block; def stmt, etc. */
3977 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003978 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 }
3980 a->a_lineno = i->i_lineno;
3981 a->a_lineno_off = a->a_offset;
3982 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003983}
3984
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003985/* assemble_emit()
3986 Extend the bytecode with a new instruction.
3987 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003988*/
3989
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003990static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 int size, arg = 0, ext = 0;
3994 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3995 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 size = instrsize(i);
3998 if (i->i_hasarg) {
3999 arg = i->i_oparg;
4000 ext = arg >> 16;
4001 }
4002 if (i->i_lineno && !assemble_lnotab(a, i))
4003 return 0;
4004 if (a->a_offset + size >= len) {
4005 if (len > PY_SSIZE_T_MAX / 2)
4006 return 0;
4007 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4008 return 0;
4009 }
4010 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4011 a->a_offset += size;
4012 if (size == 6) {
4013 assert(i->i_hasarg);
4014 *code++ = (char)EXTENDED_ARG;
4015 *code++ = ext & 0xff;
4016 *code++ = ext >> 8;
4017 arg &= 0xffff;
4018 }
4019 *code++ = i->i_opcode;
4020 if (i->i_hasarg) {
4021 assert(size == 3 || size == 6);
4022 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004023 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 }
4025 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004026}
4027
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004028static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004029assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 basicblock *b;
4032 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4033 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 /* Compute the size of each block and fixup jump args.
4036 Replace block pointer with position in bytecode. */
4037 do {
4038 totsize = 0;
4039 for (i = a->a_nblocks - 1; i >= 0; i--) {
4040 b = a->a_postorder[i];
4041 bsize = blocksize(b);
4042 b->b_offset = totsize;
4043 totsize += bsize;
4044 }
4045 last_extended_arg_count = extended_arg_count;
4046 extended_arg_count = 0;
4047 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4048 bsize = b->b_offset;
4049 for (i = 0; i < b->b_iused; i++) {
4050 struct instr *instr = &b->b_instr[i];
4051 /* Relative jumps are computed relative to
4052 the instruction pointer after fetching
4053 the jump instruction.
4054 */
4055 bsize += instrsize(instr);
4056 if (instr->i_jabs)
4057 instr->i_oparg = instr->i_target->b_offset;
4058 else if (instr->i_jrel) {
4059 int delta = instr->i_target->b_offset - bsize;
4060 instr->i_oparg = delta;
4061 }
4062 else
4063 continue;
4064 if (instr->i_oparg > 0xffff)
4065 extended_arg_count++;
4066 }
4067 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 /* XXX: This is an awful hack that could hurt performance, but
4070 on the bright side it should work until we come up
4071 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 The issue is that in the first loop blocksize() is called
4074 which calls instrsize() which requires i_oparg be set
4075 appropriately. There is a bootstrap problem because
4076 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 So we loop until we stop seeing new EXTENDED_ARGs.
4079 The only EXTENDED_ARGs that could be popping up are
4080 ones in jump instructions. So this should converge
4081 fairly quickly.
4082 */
4083 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004084}
4085
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004086static PyObject *
4087dict_keys_inorder(PyObject *dict, int offset)
4088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 PyObject *tuple, *k, *v;
4090 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 tuple = PyTuple_New(size);
4093 if (tuple == NULL)
4094 return NULL;
4095 while (PyDict_Next(dict, &pos, &k, &v)) {
4096 i = PyLong_AS_LONG(v);
4097 /* The keys of the dictionary are tuples. (see compiler_add_o)
4098 The object we want is always first, though. */
4099 k = PyTuple_GET_ITEM(k, 0);
4100 Py_INCREF(k);
4101 assert((i - offset) < size);
4102 assert((i - offset) >= 0);
4103 PyTuple_SET_ITEM(tuple, i - offset, k);
4104 }
4105 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004106}
4107
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004108static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 PySTEntryObject *ste = c->u->u_ste;
4112 int flags = 0, n;
4113 if (ste->ste_type != ModuleBlock)
4114 flags |= CO_NEWLOCALS;
4115 if (ste->ste_type == FunctionBlock) {
4116 if (!ste->ste_unoptimized)
4117 flags |= CO_OPTIMIZED;
4118 if (ste->ste_nested)
4119 flags |= CO_NESTED;
4120 if (ste->ste_generator)
4121 flags |= CO_GENERATOR;
4122 if (ste->ste_varargs)
4123 flags |= CO_VARARGS;
4124 if (ste->ste_varkeywords)
4125 flags |= CO_VARKEYWORDS;
4126 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 /* (Only) inherit compilerflags in PyCF_MASK */
4129 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 n = PyDict_Size(c->u->u_freevars);
4132 if (n < 0)
4133 return -1;
4134 if (n == 0) {
4135 n = PyDict_Size(c->u->u_cellvars);
4136 if (n < 0)
4137 return -1;
4138 if (n == 0) {
4139 flags |= CO_NOFREE;
4140 }
4141 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004144}
4145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146static PyCodeObject *
4147makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 PyObject *tmp;
4150 PyCodeObject *co = NULL;
4151 PyObject *consts = NULL;
4152 PyObject *names = NULL;
4153 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 PyObject *name = NULL;
4155 PyObject *freevars = NULL;
4156 PyObject *cellvars = NULL;
4157 PyObject *bytecode = NULL;
4158 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 tmp = dict_keys_inorder(c->u->u_consts, 0);
4161 if (!tmp)
4162 goto error;
4163 consts = PySequence_List(tmp); /* optimize_code requires a list */
4164 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 names = dict_keys_inorder(c->u->u_names, 0);
4167 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4168 if (!consts || !names || !varnames)
4169 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4172 if (!cellvars)
4173 goto error;
4174 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4175 if (!freevars)
4176 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 nlocals = PyDict_Size(c->u->u_varnames);
4178 flags = compute_code_flags(c);
4179 if (flags < 0)
4180 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4183 if (!bytecode)
4184 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4187 if (!tmp)
4188 goto error;
4189 Py_DECREF(consts);
4190 consts = tmp;
4191
4192 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4193 nlocals, stackdepth(c), flags,
4194 bytecode, consts, names, varnames,
4195 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004196 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 c->u->u_firstlineno,
4198 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 Py_XDECREF(consts);
4201 Py_XDECREF(names);
4202 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 Py_XDECREF(name);
4204 Py_XDECREF(freevars);
4205 Py_XDECREF(cellvars);
4206 Py_XDECREF(bytecode);
4207 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004208}
4209
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004210
4211/* For debugging purposes only */
4212#if 0
4213static void
4214dump_instr(const struct instr *i)
4215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 const char *jrel = i->i_jrel ? "jrel " : "";
4217 const char *jabs = i->i_jabs ? "jabs " : "";
4218 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 *arg = '\0';
4221 if (i->i_hasarg)
4222 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4225 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004226}
4227
4228static void
4229dump_basicblock(const basicblock *b)
4230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 const char *seen = b->b_seen ? "seen " : "";
4232 const char *b_return = b->b_return ? "return " : "";
4233 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4234 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4235 if (b->b_instr) {
4236 int i;
4237 for (i = 0; i < b->b_iused; i++) {
4238 fprintf(stderr, " [%02d] ", i);
4239 dump_instr(b->b_instr + i);
4240 }
4241 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004242}
4243#endif
4244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245static PyCodeObject *
4246assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 basicblock *b, *entryblock;
4249 struct assembler a;
4250 int i, j, nblocks;
4251 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 /* Make sure every block that falls off the end returns None.
4254 XXX NEXT_BLOCK() isn't quite right, because if the last
4255 block ends with a jump or return b_next shouldn't set.
4256 */
4257 if (!c->u->u_curblock->b_return) {
4258 NEXT_BLOCK(c);
4259 if (addNone)
4260 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4261 ADDOP(c, RETURN_VALUE);
4262 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 nblocks = 0;
4265 entryblock = NULL;
4266 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4267 nblocks++;
4268 entryblock = b;
4269 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 /* Set firstlineno if it wasn't explicitly set. */
4272 if (!c->u->u_firstlineno) {
4273 if (entryblock && entryblock->b_instr)
4274 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4275 else
4276 c->u->u_firstlineno = 1;
4277 }
4278 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4279 goto error;
4280 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 /* Can't modify the bytecode after computing jump offsets. */
4283 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 /* Emit code in reverse postorder from dfs. */
4286 for (i = a.a_nblocks - 1; i >= 0; i--) {
4287 b = a.a_postorder[i];
4288 for (j = 0; j < b->b_iused; j++)
4289 if (!assemble_emit(&a, &b->b_instr[j]))
4290 goto error;
4291 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4294 goto error;
4295 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4296 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004299 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004300 assemble_free(&a);
4301 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004302}
Georg Brandl8334fd92010-12-04 10:26:46 +00004303
4304#undef PyAST_Compile
4305PyAPI_FUNC(PyCodeObject *)
4306PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4307 PyArena *arena)
4308{
4309 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4310}
4311
4312