blob: 0a8f58e692d81a1b6801a46cedb8fc787102f938 [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 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
540 PyDict_Size(u->u_cellvars));
541 if (!u->u_freevars) {
542 compiler_unit_free(u);
543 return 0;
544 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u->u_blocks = NULL;
547 u->u_nfblocks = 0;
548 u->u_firstlineno = lineno;
549 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000550 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 u->u_lineno_set = 0;
552 u->u_consts = PyDict_New();
553 if (!u->u_consts) {
554 compiler_unit_free(u);
555 return 0;
556 }
557 u->u_names = PyDict_New();
558 if (!u->u_names) {
559 compiler_unit_free(u);
560 return 0;
561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 /* Push the old compiler_unit on the stack. */
566 if (c->u) {
567 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
568 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
569 Py_XDECREF(capsule);
570 compiler_unit_free(u);
571 return 0;
572 }
573 Py_DECREF(capsule);
574 u->u_private = c->u->u_private;
575 Py_XINCREF(u->u_private);
576 }
577 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 c->c_nestlevel++;
580 if (compiler_use_new_block(c) == NULL)
581 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000584}
585
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000586static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587compiler_exit_scope(struct compiler *c)
588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 int n;
590 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 c->c_nestlevel--;
593 compiler_unit_free(c->u);
594 /* Restore c->u to the parent unit. */
595 n = PyList_GET_SIZE(c->c_stack) - 1;
596 if (n >= 0) {
597 capsule = PyList_GET_ITEM(c->c_stack, n);
598 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
599 assert(c->u);
600 /* we are deleting from a list so this really shouldn't fail */
601 if (PySequence_DelItem(c->c_stack, n) < 0)
602 Py_FatalError("compiler_exit_scope()");
603 compiler_unit_check(c->u);
604 }
605 else
606 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608}
609
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100610static PyObject *
611compiler_scope_qualname(struct compiler *c)
612{
613 Py_ssize_t stack_size, i;
614 _Py_static_string(dot, ".");
615 _Py_static_string(locals, "<locals>");
616 struct compiler_unit *u;
617 PyObject *capsule, *name, *seq, *dot_str, *locals_str;
618
619 u = c->u;
620 if (u->u_qualname != NULL) {
621 Py_INCREF(u->u_qualname);
622 return u->u_qualname;
623 }
624
625 seq = PyList_New(0);
626 if (seq == NULL)
627 return NULL;
628
629 stack_size = PyList_GET_SIZE(c->c_stack);
630 for (i = 0; i < stack_size; i++) {
631 capsule = PyList_GET_ITEM(c->c_stack, i);
632 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
633 assert(u);
634 if (u->u_scope_type == COMPILER_SCOPE_MODULE)
635 continue;
636 if (PyList_Append(seq, u->u_name))
637 goto _error;
638 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION) {
639 locals_str = _PyUnicode_FromId(&locals);
640 if (locals_str == NULL)
641 goto _error;
642 if (PyList_Append(seq, locals_str))
643 goto _error;
644 }
645 }
646 u = c->u;
647 if (PyList_Append(seq, u->u_name))
648 goto _error;
649 dot_str = _PyUnicode_FromId(&dot);
650 if (dot_str == NULL)
651 goto _error;
652 name = PyUnicode_Join(dot_str, seq);
653 Py_DECREF(seq);
654 u->u_qualname = name;
655 Py_XINCREF(name);
656 return name;
657
658_error:
659 Py_XDECREF(seq);
660 return NULL;
661}
662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663/* Allocate a new block and return a pointer to it.
664 Returns NULL on error.
665*/
666
667static basicblock *
668compiler_new_block(struct compiler *c)
669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 basicblock *b;
671 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 u = c->u;
674 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
675 if (b == NULL) {
676 PyErr_NoMemory();
677 return NULL;
678 }
679 memset((void *)b, 0, sizeof(basicblock));
680 /* Extend the singly linked list of blocks with new block. */
681 b->b_list = u->u_blocks;
682 u->u_blocks = b;
683 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684}
685
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686static basicblock *
687compiler_use_new_block(struct compiler *c)
688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 basicblock *block = compiler_new_block(c);
690 if (block == NULL)
691 return NULL;
692 c->u->u_curblock = block;
693 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694}
695
696static basicblock *
697compiler_next_block(struct compiler *c)
698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 basicblock *block = compiler_new_block(c);
700 if (block == NULL)
701 return NULL;
702 c->u->u_curblock->b_next = block;
703 c->u->u_curblock = block;
704 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705}
706
707static basicblock *
708compiler_use_next_block(struct compiler *c, basicblock *block)
709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 assert(block != NULL);
711 c->u->u_curblock->b_next = block;
712 c->u->u_curblock = block;
713 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714}
715
716/* Returns the offset of the next instruction in the current block's
717 b_instr array. Resizes the b_instr as necessary.
718 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000719*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000720
721static int
722compiler_next_instr(struct compiler *c, basicblock *b)
723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 assert(b != NULL);
725 if (b->b_instr == NULL) {
726 b->b_instr = (struct instr *)PyObject_Malloc(
727 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
728 if (b->b_instr == NULL) {
729 PyErr_NoMemory();
730 return -1;
731 }
732 b->b_ialloc = DEFAULT_BLOCK_SIZE;
733 memset((char *)b->b_instr, 0,
734 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
735 }
736 else if (b->b_iused == b->b_ialloc) {
737 struct instr *tmp;
738 size_t oldsize, newsize;
739 oldsize = b->b_ialloc * sizeof(struct instr);
740 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (oldsize > (PY_SIZE_MAX >> 1)) {
743 PyErr_NoMemory();
744 return -1;
745 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (newsize == 0) {
748 PyErr_NoMemory();
749 return -1;
750 }
751 b->b_ialloc <<= 1;
752 tmp = (struct instr *)PyObject_Realloc(
753 (void *)b->b_instr, newsize);
754 if (tmp == NULL) {
755 PyErr_NoMemory();
756 return -1;
757 }
758 b->b_instr = tmp;
759 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
760 }
761 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762}
763
Christian Heimes2202f872008-02-06 14:31:34 +0000764/* Set the i_lineno member of the instruction at offset off if the
765 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000766 already been set. If it has been set, the call has no effect.
767
Christian Heimes2202f872008-02-06 14:31:34 +0000768 The line number is reset in the following cases:
769 - when entering a new scope
770 - on each statement
771 - on each expression that start a new line
772 - before the "except" clause
773 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000774*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000775
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776static void
777compiler_set_lineno(struct compiler *c, int off)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 basicblock *b;
780 if (c->u->u_lineno_set)
781 return;
782 c->u->u_lineno_set = 1;
783 b = c->u->u_curblock;
784 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785}
786
787static int
788opcode_stack_effect(int opcode, int oparg)
789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 switch (opcode) {
791 case POP_TOP:
792 return -1;
793 case ROT_TWO:
794 case ROT_THREE:
795 return 0;
796 case DUP_TOP:
797 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000798 case DUP_TOP_TWO:
799 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 case UNARY_POSITIVE:
802 case UNARY_NEGATIVE:
803 case UNARY_NOT:
804 case UNARY_INVERT:
805 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 case SET_ADD:
808 case LIST_APPEND:
809 return -1;
810 case MAP_ADD:
811 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 case BINARY_POWER:
814 case BINARY_MULTIPLY:
815 case BINARY_MODULO:
816 case BINARY_ADD:
817 case BINARY_SUBTRACT:
818 case BINARY_SUBSCR:
819 case BINARY_FLOOR_DIVIDE:
820 case BINARY_TRUE_DIVIDE:
821 return -1;
822 case INPLACE_FLOOR_DIVIDE:
823 case INPLACE_TRUE_DIVIDE:
824 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 case INPLACE_ADD:
827 case INPLACE_SUBTRACT:
828 case INPLACE_MULTIPLY:
829 case INPLACE_MODULO:
830 return -1;
831 case STORE_SUBSCR:
832 return -3;
833 case STORE_MAP:
834 return -2;
835 case DELETE_SUBSCR:
836 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 case BINARY_LSHIFT:
839 case BINARY_RSHIFT:
840 case BINARY_AND:
841 case BINARY_XOR:
842 case BINARY_OR:
843 return -1;
844 case INPLACE_POWER:
845 return -1;
846 case GET_ITER:
847 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 case PRINT_EXPR:
850 return -1;
851 case LOAD_BUILD_CLASS:
852 return 1;
853 case INPLACE_LSHIFT:
854 case INPLACE_RSHIFT:
855 case INPLACE_AND:
856 case INPLACE_XOR:
857 case INPLACE_OR:
858 return -1;
859 case BREAK_LOOP:
860 return 0;
861 case SETUP_WITH:
862 return 7;
863 case WITH_CLEANUP:
864 return -1; /* XXX Sometimes more */
865 case STORE_LOCALS:
866 return -1;
867 case RETURN_VALUE:
868 return -1;
869 case IMPORT_STAR:
870 return -1;
871 case YIELD_VALUE:
872 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500873 case YIELD_FROM:
874 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 case POP_BLOCK:
876 return 0;
877 case POP_EXCEPT:
878 return 0; /* -3 except if bad bytecode */
879 case END_FINALLY:
880 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case STORE_NAME:
883 return -1;
884 case DELETE_NAME:
885 return 0;
886 case UNPACK_SEQUENCE:
887 return oparg-1;
888 case UNPACK_EX:
889 return (oparg&0xFF) + (oparg>>8);
890 case FOR_ITER:
891 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 case STORE_ATTR:
894 return -2;
895 case DELETE_ATTR:
896 return -1;
897 case STORE_GLOBAL:
898 return -1;
899 case DELETE_GLOBAL:
900 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case LOAD_CONST:
902 return 1;
903 case LOAD_NAME:
904 return 1;
905 case BUILD_TUPLE:
906 case BUILD_LIST:
907 case BUILD_SET:
908 return 1-oparg;
909 case BUILD_MAP:
910 return 1;
911 case LOAD_ATTR:
912 return 0;
913 case COMPARE_OP:
914 return -1;
915 case IMPORT_NAME:
916 return -1;
917 case IMPORT_FROM:
918 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case JUMP_FORWARD:
921 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
922 case JUMP_IF_FALSE_OR_POP: /* "" */
923 case JUMP_ABSOLUTE:
924 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 case POP_JUMP_IF_FALSE:
927 case POP_JUMP_IF_TRUE:
928 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 case LOAD_GLOBAL:
931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case CONTINUE_LOOP:
934 return 0;
935 case SETUP_LOOP:
936 return 0;
937 case SETUP_EXCEPT:
938 case SETUP_FINALLY:
939 return 6; /* can push 3 values for the new exception
940 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case LOAD_FAST:
943 return 1;
944 case STORE_FAST:
945 return -1;
946 case DELETE_FAST:
947 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case RAISE_VARARGS:
950 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000951#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 case CALL_FUNCTION:
953 return -NARGS(oparg);
954 case CALL_FUNCTION_VAR:
955 case CALL_FUNCTION_KW:
956 return -NARGS(oparg)-1;
957 case CALL_FUNCTION_VAR_KW:
958 return -NARGS(oparg)-2;
959 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100960 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100962 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000963#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case BUILD_SLICE:
965 if (oparg == 3)
966 return -2;
967 else
968 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case LOAD_CLOSURE:
971 return 1;
972 case LOAD_DEREF:
973 return 1;
974 case STORE_DEREF:
975 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000976 case DELETE_DEREF:
977 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 default:
979 fprintf(stderr, "opcode = %d\n", opcode);
980 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 }
983 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000984}
985
986/* Add an opcode with no argument.
987 Returns 0 on failure, 1 on success.
988*/
989
990static int
991compiler_addop(struct compiler *c, int opcode)
992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 basicblock *b;
994 struct instr *i;
995 int off;
996 off = compiler_next_instr(c, c->u->u_curblock);
997 if (off < 0)
998 return 0;
999 b = c->u->u_curblock;
1000 i = &b->b_instr[off];
1001 i->i_opcode = opcode;
1002 i->i_hasarg = 0;
1003 if (opcode == RETURN_VALUE)
1004 b->b_return = 1;
1005 compiler_set_lineno(c, off);
1006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007}
1008
1009static int
1010compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyObject *t, *v;
1013 Py_ssize_t arg;
1014 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* necessary to make sure types aren't coerced (e.g., int and long) */
1017 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1018 if (PyFloat_Check(o)) {
1019 d = PyFloat_AS_DOUBLE(o);
1020 /* all we need is to make the tuple different in either the 0.0
1021 * or -0.0 case from all others, just to avoid the "coercion".
1022 */
1023 if (d == 0.0 && copysign(1.0, d) < 0.0)
1024 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1025 else
1026 t = PyTuple_Pack(2, o, o->ob_type);
1027 }
1028 else if (PyComplex_Check(o)) {
1029 Py_complex z;
1030 int real_negzero, imag_negzero;
1031 /* For the complex case we must make complex(x, 0.)
1032 different from complex(x, -0.) and complex(0., y)
1033 different from complex(-0., y), for any x and y.
1034 All four complex zeros must be distinguished.*/
1035 z = PyComplex_AsCComplex(o);
1036 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1037 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1038 if (real_negzero && imag_negzero) {
1039 t = PyTuple_Pack(5, o, o->ob_type,
1040 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 else if (imag_negzero) {
1043 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001044 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 else if (real_negzero) {
1046 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1047 }
1048 else {
1049 t = PyTuple_Pack(2, o, o->ob_type);
1050 }
1051 }
1052 else {
1053 t = PyTuple_Pack(2, o, o->ob_type);
1054 }
1055 if (t == NULL)
1056 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 v = PyDict_GetItem(dict, t);
1059 if (!v) {
1060 if (PyErr_Occurred())
1061 return -1;
1062 arg = PyDict_Size(dict);
1063 v = PyLong_FromLong(arg);
1064 if (!v) {
1065 Py_DECREF(t);
1066 return -1;
1067 }
1068 if (PyDict_SetItem(dict, t, v) < 0) {
1069 Py_DECREF(t);
1070 Py_DECREF(v);
1071 return -1;
1072 }
1073 Py_DECREF(v);
1074 }
1075 else
1076 arg = PyLong_AsLong(v);
1077 Py_DECREF(t);
1078 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079}
1080
1081static int
1082compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001084{
1085 int arg = compiler_add_o(c, dict, o);
1086 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088 return compiler_addop_i(c, opcode, arg);
1089}
1090
1091static int
1092compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001094{
1095 int arg;
1096 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1097 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001098 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099 arg = compiler_add_o(c, dict, mangled);
1100 Py_DECREF(mangled);
1101 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001102 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103 return compiler_addop_i(c, opcode, arg);
1104}
1105
1106/* Add an opcode with an integer argument.
1107 Returns 0 on failure, 1 on success.
1108*/
1109
1110static int
1111compiler_addop_i(struct compiler *c, int opcode, int oparg)
1112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 struct instr *i;
1114 int off;
1115 off = compiler_next_instr(c, c->u->u_curblock);
1116 if (off < 0)
1117 return 0;
1118 i = &c->u->u_curblock->b_instr[off];
1119 i->i_opcode = opcode;
1120 i->i_oparg = oparg;
1121 i->i_hasarg = 1;
1122 compiler_set_lineno(c, off);
1123 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124}
1125
1126static int
1127compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 struct instr *i;
1130 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 assert(b != NULL);
1133 off = compiler_next_instr(c, c->u->u_curblock);
1134 if (off < 0)
1135 return 0;
1136 i = &c->u->u_curblock->b_instr[off];
1137 i->i_opcode = opcode;
1138 i->i_target = b;
1139 i->i_hasarg = 1;
1140 if (absolute)
1141 i->i_jabs = 1;
1142 else
1143 i->i_jrel = 1;
1144 compiler_set_lineno(c, off);
1145 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146}
1147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1149 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 it as the current block. NEXT_BLOCK() also creates an implicit jump
1151 from the current block to the new block.
1152*/
1153
Thomas Wouters89f507f2006-12-13 04:49:30 +00001154/* The returns inside these macros make it impossible to decref objects
1155 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156*/
1157
1158
1159#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (compiler_use_new_block((C)) == NULL) \
1161 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162}
1163
1164#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (compiler_next_block((C)) == NULL) \
1166 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167}
1168
1169#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (!compiler_addop((C), (OP))) \
1171 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172}
1173
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001174#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (!compiler_addop((C), (OP))) { \
1176 compiler_exit_scope(c); \
1177 return 0; \
1178 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001179}
1180
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1183 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184}
1185
1186#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1188 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189}
1190
1191#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (!compiler_addop_i((C), (OP), (O))) \
1193 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194}
1195
1196#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (!compiler_addop_j((C), (OP), (O), 1)) \
1198 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199}
1200
1201#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (!compiler_addop_j((C), (OP), (O), 0)) \
1203 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204}
1205
1206/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1207 the ASDL name to synthesize the name of the C type and the visit function.
1208*/
1209
1210#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (!compiler_visit_ ## TYPE((C), (V))) \
1212 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213}
1214
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001215#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (!compiler_visit_ ## TYPE((C), (V))) { \
1217 compiler_exit_scope(c); \
1218 return 0; \
1219 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001220}
1221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (!compiler_visit_slice((C), (V), (CTX))) \
1224 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
1227#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 int _i; \
1229 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1230 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1231 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1232 if (!compiler_visit_ ## TYPE((C), elt)) \
1233 return 0; \
1234 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001237#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 int _i; \
1239 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1240 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1241 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1242 if (!compiler_visit_ ## TYPE((C), elt)) { \
1243 compiler_exit_scope(c); \
1244 return 0; \
1245 } \
1246 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001247}
1248
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249static int
1250compiler_isdocstring(stmt_ty s)
1251{
1252 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001253 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254 return s->v.Expr.value->kind == Str_kind;
1255}
1256
1257/* Compile a sequence of statements, checking for a docstring. */
1258
1259static int
1260compiler_body(struct compiler *c, asdl_seq *stmts)
1261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 int i = 0;
1263 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!asdl_seq_LEN(stmts))
1266 return 1;
1267 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001268 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* don't generate docstrings if -OO */
1270 i = 1;
1271 VISIT(c, expr, st->v.Expr.value);
1272 if (!compiler_nameop(c, __doc__, Store))
1273 return 0;
1274 }
1275 for (; i < asdl_seq_LEN(stmts); i++)
1276 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1277 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278}
1279
1280static PyCodeObject *
1281compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 PyCodeObject *co;
1284 int addNone = 1;
1285 static PyObject *module;
1286 if (!module) {
1287 module = PyUnicode_InternFromString("<module>");
1288 if (!module)
1289 return NULL;
1290 }
1291 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001292 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return NULL;
1294 switch (mod->kind) {
1295 case Module_kind:
1296 if (!compiler_body(c, mod->v.Module.body)) {
1297 compiler_exit_scope(c);
1298 return 0;
1299 }
1300 break;
1301 case Interactive_kind:
1302 c->c_interactive = 1;
1303 VISIT_SEQ_IN_SCOPE(c, stmt,
1304 mod->v.Interactive.body);
1305 break;
1306 case Expression_kind:
1307 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1308 addNone = 0;
1309 break;
1310 case Suite_kind:
1311 PyErr_SetString(PyExc_SystemError,
1312 "suite should not be possible");
1313 return 0;
1314 default:
1315 PyErr_Format(PyExc_SystemError,
1316 "module kind %d should not be possible",
1317 mod->kind);
1318 return 0;
1319 }
1320 co = assemble(c, addNone);
1321 compiler_exit_scope(c);
1322 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001323}
1324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325/* The test for LOCAL must come before the test for FREE in order to
1326 handle classes where name is both local and free. The local var is
1327 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001328*/
1329
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330static int
1331get_ref_type(struct compiler *c, PyObject *name)
1332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 int scope = PyST_GetScope(c->u->u_ste, name);
1334 if (scope == 0) {
1335 char buf[350];
1336 PyOS_snprintf(buf, sizeof(buf),
1337 "unknown scope for %.100s in %.100s(%s) in %s\n"
1338 "symbols: %s\nlocals: %s\nglobals: %s",
1339 PyBytes_AS_STRING(name),
1340 PyBytes_AS_STRING(c->u->u_name),
1341 PyObject_REPR(c->u->u_ste->ste_id),
1342 c->c_filename,
1343 PyObject_REPR(c->u->u_ste->ste_symbols),
1344 PyObject_REPR(c->u->u_varnames),
1345 PyObject_REPR(c->u->u_names)
1346 );
1347 Py_FatalError(buf);
1348 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351}
1352
1353static int
1354compiler_lookup_arg(PyObject *dict, PyObject *name)
1355{
1356 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001359 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001361 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001363 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001364 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365}
1366
1367static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001368compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001371 if (qualname == NULL)
1372 qualname = co->co_name;
1373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (free == 0) {
1375 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001376 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 ADDOP_I(c, MAKE_FUNCTION, args);
1378 return 1;
1379 }
1380 for (i = 0; i < free; ++i) {
1381 /* Bypass com_addop_varname because it will generate
1382 LOAD_DEREF but LOAD_CLOSURE is needed.
1383 */
1384 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1385 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 /* Special case: If a class contains a method with a
1388 free variable that has the same name as a method,
1389 the name will be considered free *and* local in the
1390 class. It should be handled by the closure, as
1391 well as by the normal name loookup logic.
1392 */
1393 reftype = get_ref_type(c, name);
1394 if (reftype == CELL)
1395 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1396 else /* (reftype == FREE) */
1397 arg = compiler_lookup_arg(c->u->u_freevars, name);
1398 if (arg == -1) {
1399 fprintf(stderr,
1400 "lookup %s in %s %d %d\n"
1401 "freevars of %s: %s\n",
1402 PyObject_REPR(name),
1403 PyBytes_AS_STRING(c->u->u_name),
1404 reftype, arg,
1405 _PyUnicode_AsString(co->co_name),
1406 PyObject_REPR(co->co_freevars));
1407 Py_FatalError("compiler_make_closure()");
1408 }
1409 ADDOP_I(c, LOAD_CLOSURE, arg);
1410 }
1411 ADDOP_I(c, BUILD_TUPLE, free);
1412 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001413 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 ADDOP_I(c, MAKE_CLOSURE, args);
1415 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416}
1417
1418static int
1419compiler_decorators(struct compiler *c, asdl_seq* decos)
1420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (!decos)
1424 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1427 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1428 }
1429 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430}
1431
1432static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001433compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 int i, default_count = 0;
1437 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1438 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1439 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1440 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001441 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1442 if (!mangled)
1443 return -1;
1444 ADDOP_O(c, LOAD_CONST, mangled, consts);
1445 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!compiler_visit_expr(c, default_)) {
1447 return -1;
1448 }
1449 default_count++;
1450 }
1451 }
1452 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001453}
1454
1455static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001456compiler_visit_argannotation(struct compiler *c, identifier id,
1457 expr_ty annotation, PyObject *names)
1458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (annotation) {
1460 VISIT(c, expr, annotation);
1461 if (PyList_Append(names, id))
1462 return -1;
1463 }
1464 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001465}
1466
1467static int
1468compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1469 PyObject *names)
1470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 int i, error;
1472 for (i = 0; i < asdl_seq_LEN(args); i++) {
1473 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1474 error = compiler_visit_argannotation(
1475 c,
1476 arg->arg,
1477 arg->annotation,
1478 names);
1479 if (error)
1480 return error;
1481 }
1482 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001483}
1484
1485static int
1486compiler_visit_annotations(struct compiler *c, arguments_ty args,
1487 expr_ty returns)
1488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 /* Push arg annotations and a list of the argument names. Return the #
1490 of items pushed. The expressions are evaluated out-of-order wrt the
1491 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1494 */
1495 static identifier return_str;
1496 PyObject *names;
1497 int len;
1498 names = PyList_New(0);
1499 if (!names)
1500 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (compiler_visit_argannotations(c, args->args, names))
1503 goto error;
1504 if (args->varargannotation &&
1505 compiler_visit_argannotation(c, args->vararg,
1506 args->varargannotation, names))
1507 goto error;
1508 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1509 goto error;
1510 if (args->kwargannotation &&
1511 compiler_visit_argannotation(c, args->kwarg,
1512 args->kwargannotation, names))
1513 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (!return_str) {
1516 return_str = PyUnicode_InternFromString("return");
1517 if (!return_str)
1518 goto error;
1519 }
1520 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1521 goto error;
1522 }
1523
1524 len = PyList_GET_SIZE(names);
1525 if (len > 65534) {
1526 /* len must fit in 16 bits, and len is incremented below */
1527 PyErr_SetString(PyExc_SyntaxError,
1528 "too many annotations");
1529 goto error;
1530 }
1531 if (len) {
1532 /* convert names to a tuple and place on stack */
1533 PyObject *elt;
1534 int i;
1535 PyObject *s = PyTuple_New(len);
1536 if (!s)
1537 goto error;
1538 for (i = 0; i < len; i++) {
1539 elt = PyList_GET_ITEM(names, i);
1540 Py_INCREF(elt);
1541 PyTuple_SET_ITEM(s, i, elt);
1542 }
1543 ADDOP_O(c, LOAD_CONST, s, consts);
1544 Py_DECREF(s);
1545 len++; /* include the just-pushed tuple */
1546 }
1547 Py_DECREF(names);
1548 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001549
1550error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 Py_DECREF(names);
1552 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001553}
1554
1555static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001556compiler_function(struct compiler *c, stmt_ty s)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001559 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 arguments_ty args = s->v.FunctionDef.args;
1561 expr_ty returns = s->v.FunctionDef.returns;
1562 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1563 stmt_ty st;
1564 int i, n, docstring, kw_default_count = 0, arglength;
1565 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (!compiler_decorators(c, decos))
1570 return 0;
1571 if (args->kwonlyargs) {
1572 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1573 args->kw_defaults);
1574 if (res < 0)
1575 return 0;
1576 kw_default_count = res;
1577 }
1578 if (args->defaults)
1579 VISIT_SEQ(c, expr, args->defaults);
1580 num_annotations = compiler_visit_annotations(c, args, returns);
1581 if (num_annotations < 0)
1582 return 0;
1583 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001584
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001585 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1586 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 s->lineno))
1588 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1591 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001592 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 first_const = st->v.Expr.value->v.Str.s;
1594 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1595 compiler_exit_scope(c);
1596 return 0;
1597 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 c->u->u_argcount = asdl_seq_LEN(args->args);
1600 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1601 n = asdl_seq_LEN(s->v.FunctionDef.body);
1602 /* if there was a docstring, we need to skip the first statement */
1603 for (i = docstring; i < n; i++) {
1604 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1605 VISIT_IN_SCOPE(c, stmt, st);
1606 }
1607 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001608 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001610 if (qualname == NULL || co == NULL) {
1611 Py_XDECREF(qualname);
1612 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 arglength = asdl_seq_LEN(args->defaults);
1617 arglength |= kw_default_count << 8;
1618 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001619 compiler_make_closure(c, co, arglength, qualname);
1620 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 /* decorators */
1624 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1625 ADDOP_I(c, CALL_FUNCTION, 1);
1626 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001629}
1630
1631static int
1632compiler_class(struct compiler *c, stmt_ty s)
1633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 PyCodeObject *co;
1635 PyObject *str;
1636 int i;
1637 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (!compiler_decorators(c, decos))
1640 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* ultimately generate code for:
1643 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1644 where:
1645 <func> is a function/closure created from the class body;
1646 it has a single argument (__locals__) where the dict
1647 (or MutableSequence) representing the locals is passed
1648 <name> is the class name
1649 <bases> is the positional arguments and *varargs argument
1650 <keywords> is the keyword arguments and **kwds argument
1651 This borrows from compiler_call.
1652 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001655 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1656 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 return 0;
1658 /* this block represents what we do in the new scope */
1659 {
1660 /* use the class name for name mangling */
1661 Py_INCREF(s->v.ClassDef.name);
1662 Py_XDECREF(c->u->u_private);
1663 c->u->u_private = s->v.ClassDef.name;
1664 /* force it to have one mandatory argument */
1665 c->u->u_argcount = 1;
1666 /* load the first argument (__locals__) ... */
1667 ADDOP_I(c, LOAD_FAST, 0);
1668 /* ... and store it into f_locals */
1669 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1670 /* load (global) __name__ ... */
1671 str = PyUnicode_InternFromString("__name__");
1672 if (!str || !compiler_nameop(c, str, Load)) {
1673 Py_XDECREF(str);
1674 compiler_exit_scope(c);
1675 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001676 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 Py_DECREF(str);
1678 /* ... and store it as __module__ */
1679 str = PyUnicode_InternFromString("__module__");
1680 if (!str || !compiler_nameop(c, str, Store)) {
1681 Py_XDECREF(str);
1682 compiler_exit_scope(c);
1683 return 0;
1684 }
1685 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001686 /* store the __qualname__ */
1687 str = compiler_scope_qualname(c);
1688 if (!str) {
1689 compiler_exit_scope(c);
1690 return 0;
1691 }
1692 ADDOP_O(c, LOAD_CONST, str, consts);
1693 Py_DECREF(str);
1694 str = PyUnicode_InternFromString("__qualname__");
1695 if (!str || !compiler_nameop(c, str, Store)) {
1696 Py_XDECREF(str);
1697 compiler_exit_scope(c);
1698 return 0;
1699 }
1700 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* compile the body proper */
1702 if (!compiler_body(c, s->v.ClassDef.body)) {
1703 compiler_exit_scope(c);
1704 return 0;
1705 }
1706 /* return the (empty) __class__ cell */
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001707 str = PyUnicode_InternFromString("__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (str == NULL) {
1709 compiler_exit_scope(c);
1710 return 0;
1711 }
1712 i = compiler_lookup_arg(c->u->u_cellvars, str);
1713 Py_DECREF(str);
1714 if (i == -1) {
1715 /* This happens when nobody references the cell */
1716 PyErr_Clear();
1717 /* Return None */
1718 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1719 }
1720 else {
1721 /* Return the cell where to store __class__ */
1722 ADDOP_I(c, LOAD_CLOSURE, i);
1723 }
1724 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1725 /* create the code object */
1726 co = assemble(c, 1);
1727 }
1728 /* leave the new scope */
1729 compiler_exit_scope(c);
1730 if (co == NULL)
1731 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* 2. load the 'build_class' function */
1734 ADDOP(c, LOAD_BUILD_CLASS);
1735
1736 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001737 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 Py_DECREF(co);
1739
1740 /* 4. load class name */
1741 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1742
1743 /* 5. generate the rest of the code for the call */
1744 if (!compiler_call_helper(c, 2,
1745 s->v.ClassDef.bases,
1746 s->v.ClassDef.keywords,
1747 s->v.ClassDef.starargs,
1748 s->v.ClassDef.kwargs))
1749 return 0;
1750
1751 /* 6. apply decorators */
1752 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1753 ADDOP_I(c, CALL_FUNCTION, 1);
1754 }
1755
1756 /* 7. store into <name> */
1757 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1758 return 0;
1759 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760}
1761
1762static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001763compiler_ifexp(struct compiler *c, expr_ty e)
1764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 basicblock *end, *next;
1766
1767 assert(e->kind == IfExp_kind);
1768 end = compiler_new_block(c);
1769 if (end == NULL)
1770 return 0;
1771 next = compiler_new_block(c);
1772 if (next == NULL)
1773 return 0;
1774 VISIT(c, expr, e->v.IfExp.test);
1775 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1776 VISIT(c, expr, e->v.IfExp.body);
1777 ADDOP_JREL(c, JUMP_FORWARD, end);
1778 compiler_use_next_block(c, next);
1779 VISIT(c, expr, e->v.IfExp.orelse);
1780 compiler_use_next_block(c, end);
1781 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001782}
1783
1784static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785compiler_lambda(struct compiler *c, expr_ty e)
1786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001788 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 static identifier name;
1790 int kw_default_count = 0, arglength;
1791 arguments_ty args = e->v.Lambda.args;
1792 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 if (!name) {
1795 name = PyUnicode_InternFromString("<lambda>");
1796 if (!name)
1797 return 0;
1798 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (args->kwonlyargs) {
1801 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1802 args->kw_defaults);
1803 if (res < 0) return 0;
1804 kw_default_count = res;
1805 }
1806 if (args->defaults)
1807 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001808 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1809 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* Make None the first constant, so the lambda can't have a
1813 docstring. */
1814 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1815 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 c->u->u_argcount = asdl_seq_LEN(args->args);
1818 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1819 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1820 if (c->u->u_ste->ste_generator) {
1821 ADDOP_IN_SCOPE(c, POP_TOP);
1822 }
1823 else {
1824 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1825 }
1826 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001827 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001829 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 arglength = asdl_seq_LEN(args->defaults);
1833 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001834 compiler_make_closure(c, co, arglength, qualname);
1835 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 Py_DECREF(co);
1837
1838 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001839}
1840
1841static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842compiler_if(struct compiler *c, stmt_ty s)
1843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 basicblock *end, *next;
1845 int constant;
1846 assert(s->kind == If_kind);
1847 end = compiler_new_block(c);
1848 if (end == NULL)
1849 return 0;
1850
Georg Brandl8334fd92010-12-04 10:26:46 +00001851 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 /* constant = 0: "if 0"
1853 * constant = 1: "if 1", "if 2", ...
1854 * constant = -1: rest */
1855 if (constant == 0) {
1856 if (s->v.If.orelse)
1857 VISIT_SEQ(c, stmt, s->v.If.orelse);
1858 } else if (constant == 1) {
1859 VISIT_SEQ(c, stmt, s->v.If.body);
1860 } else {
1861 if (s->v.If.orelse) {
1862 next = compiler_new_block(c);
1863 if (next == NULL)
1864 return 0;
1865 }
1866 else
1867 next = end;
1868 VISIT(c, expr, s->v.If.test);
1869 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1870 VISIT_SEQ(c, stmt, s->v.If.body);
1871 ADDOP_JREL(c, JUMP_FORWARD, end);
1872 if (s->v.If.orelse) {
1873 compiler_use_next_block(c, next);
1874 VISIT_SEQ(c, stmt, s->v.If.orelse);
1875 }
1876 }
1877 compiler_use_next_block(c, end);
1878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879}
1880
1881static int
1882compiler_for(struct compiler *c, stmt_ty s)
1883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 start = compiler_new_block(c);
1887 cleanup = compiler_new_block(c);
1888 end = compiler_new_block(c);
1889 if (start == NULL || end == NULL || cleanup == NULL)
1890 return 0;
1891 ADDOP_JREL(c, SETUP_LOOP, end);
1892 if (!compiler_push_fblock(c, LOOP, start))
1893 return 0;
1894 VISIT(c, expr, s->v.For.iter);
1895 ADDOP(c, GET_ITER);
1896 compiler_use_next_block(c, start);
1897 ADDOP_JREL(c, FOR_ITER, cleanup);
1898 VISIT(c, expr, s->v.For.target);
1899 VISIT_SEQ(c, stmt, s->v.For.body);
1900 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1901 compiler_use_next_block(c, cleanup);
1902 ADDOP(c, POP_BLOCK);
1903 compiler_pop_fblock(c, LOOP, start);
1904 VISIT_SEQ(c, stmt, s->v.For.orelse);
1905 compiler_use_next_block(c, end);
1906 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907}
1908
1909static int
1910compiler_while(struct compiler *c, stmt_ty s)
1911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001913 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 if (constant == 0) {
1916 if (s->v.While.orelse)
1917 VISIT_SEQ(c, stmt, s->v.While.orelse);
1918 return 1;
1919 }
1920 loop = compiler_new_block(c);
1921 end = compiler_new_block(c);
1922 if (constant == -1) {
1923 anchor = compiler_new_block(c);
1924 if (anchor == NULL)
1925 return 0;
1926 }
1927 if (loop == NULL || end == NULL)
1928 return 0;
1929 if (s->v.While.orelse) {
1930 orelse = compiler_new_block(c);
1931 if (orelse == NULL)
1932 return 0;
1933 }
1934 else
1935 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 ADDOP_JREL(c, SETUP_LOOP, end);
1938 compiler_use_next_block(c, loop);
1939 if (!compiler_push_fblock(c, LOOP, loop))
1940 return 0;
1941 if (constant == -1) {
1942 VISIT(c, expr, s->v.While.test);
1943 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1944 }
1945 VISIT_SEQ(c, stmt, s->v.While.body);
1946 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 /* XXX should the two POP instructions be in a separate block
1949 if there is no else clause ?
1950 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 if (constant == -1) {
1953 compiler_use_next_block(c, anchor);
1954 ADDOP(c, POP_BLOCK);
1955 }
1956 compiler_pop_fblock(c, LOOP, loop);
1957 if (orelse != NULL) /* what if orelse is just pass? */
1958 VISIT_SEQ(c, stmt, s->v.While.orelse);
1959 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
1964static int
1965compiler_continue(struct compiler *c)
1966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1968 static const char IN_FINALLY_ERROR_MSG[] =
1969 "'continue' not supported inside 'finally' clause";
1970 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 if (!c->u->u_nfblocks)
1973 return compiler_error(c, LOOP_ERROR_MSG);
1974 i = c->u->u_nfblocks - 1;
1975 switch (c->u->u_fblock[i].fb_type) {
1976 case LOOP:
1977 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1978 break;
1979 case EXCEPT:
1980 case FINALLY_TRY:
1981 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1982 /* Prevent continue anywhere under a finally
1983 even if hidden in a sub-try or except. */
1984 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1985 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1986 }
1987 if (i == -1)
1988 return compiler_error(c, LOOP_ERROR_MSG);
1989 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1990 break;
1991 case FINALLY_END:
1992 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1993 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996}
1997
1998/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999
2000 SETUP_FINALLY L
2001 <code for body>
2002 POP_BLOCK
2003 LOAD_CONST <None>
2004 L: <code for finalbody>
2005 END_FINALLY
2006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 The special instructions use the block stack. Each block
2008 stack entry contains the instruction that created it (here
2009 SETUP_FINALLY), the level of the value stack at the time the
2010 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 Pushes the current value stack level and the label
2014 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 Pops en entry from the block stack, and pops the value
2017 stack until its level is the same as indicated on the
2018 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 Pops a variable number of entries from the *value* stack
2021 and re-raises the exception they specify. The number of
2022 entries popped depends on the (pseudo) exception type.
2023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 The block stack is unwound when an exception is raised:
2025 when a SETUP_FINALLY entry is found, the exception is pushed
2026 onto the value stack (and the exception condition is cleared),
2027 and the interpreter jumps to the label gotten from the block
2028 stack.
2029*/
2030
2031static int
2032compiler_try_finally(struct compiler *c, stmt_ty s)
2033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 basicblock *body, *end;
2035 body = compiler_new_block(c);
2036 end = compiler_new_block(c);
2037 if (body == NULL || end == NULL)
2038 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 ADDOP_JREL(c, SETUP_FINALLY, end);
2041 compiler_use_next_block(c, body);
2042 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2043 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002044 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2045 if (!compiler_try_except(c, s))
2046 return 0;
2047 }
2048 else {
2049 VISIT_SEQ(c, stmt, s->v.Try.body);
2050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 ADDOP(c, POP_BLOCK);
2052 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2055 compiler_use_next_block(c, end);
2056 if (!compiler_push_fblock(c, FINALLY_END, end))
2057 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002058 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 ADDOP(c, END_FINALLY);
2060 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063}
2064
2065/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002066 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 (The contents of the value stack is shown in [], with the top
2068 at the right; 'tb' is trace-back info, 'val' the exception's
2069 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070
2071 Value stack Label Instruction Argument
2072 [] SETUP_EXCEPT L1
2073 [] <code for S>
2074 [] POP_BLOCK
2075 [] JUMP_FORWARD L0
2076
2077 [tb, val, exc] L1: DUP )
2078 [tb, val, exc, exc] <evaluate E1> )
2079 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2080 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2081 [tb, val, exc] POP
2082 [tb, val] <assign to V1> (or POP if no V1)
2083 [tb] POP
2084 [] <code for S1>
2085 JUMP_FORWARD L0
2086
2087 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 .............................etc.......................
2089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2091
2092 [] L0: <next statement>
2093
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 Of course, parts are not generated if Vi or Ei is not present.
2095*/
2096static int
2097compiler_try_except(struct compiler *c, stmt_ty s)
2098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 basicblock *body, *orelse, *except, *end;
2100 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 body = compiler_new_block(c);
2103 except = compiler_new_block(c);
2104 orelse = compiler_new_block(c);
2105 end = compiler_new_block(c);
2106 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2107 return 0;
2108 ADDOP_JREL(c, SETUP_EXCEPT, except);
2109 compiler_use_next_block(c, body);
2110 if (!compiler_push_fblock(c, EXCEPT, body))
2111 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002112 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 ADDOP(c, POP_BLOCK);
2114 compiler_pop_fblock(c, EXCEPT, body);
2115 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002116 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 compiler_use_next_block(c, except);
2118 for (i = 0; i < n; i++) {
2119 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002120 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (!handler->v.ExceptHandler.type && i < n-1)
2122 return compiler_error(c, "default 'except:' must be last");
2123 c->u->u_lineno_set = 0;
2124 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002125 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 except = compiler_new_block(c);
2127 if (except == NULL)
2128 return 0;
2129 if (handler->v.ExceptHandler.type) {
2130 ADDOP(c, DUP_TOP);
2131 VISIT(c, expr, handler->v.ExceptHandler.type);
2132 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2133 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2134 }
2135 ADDOP(c, POP_TOP);
2136 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002137 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002138
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002139 cleanup_end = compiler_new_block(c);
2140 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002141 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002142 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002143
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002144 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2145 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002147 /*
2148 try:
2149 # body
2150 except type as name:
2151 try:
2152 # body
2153 finally:
2154 name = None
2155 del name
2156 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002158 /* second try: */
2159 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2160 compiler_use_next_block(c, cleanup_body);
2161 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2162 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002164 /* second # body */
2165 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2166 ADDOP(c, POP_BLOCK);
2167 ADDOP(c, POP_EXCEPT);
2168 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002170 /* finally: */
2171 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2172 compiler_use_next_block(c, cleanup_end);
2173 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2174 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002176 /* name = None */
2177 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2178 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002180 /* del name */
2181 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002183 ADDOP(c, END_FINALLY);
2184 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 }
2186 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002187 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002189 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002190 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002191 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192
Guido van Rossumb940e112007-01-10 16:19:56 +00002193 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002194 ADDOP(c, POP_TOP);
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 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002199 ADDOP(c, POP_EXCEPT);
2200 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 }
2202 ADDOP_JREL(c, JUMP_FORWARD, end);
2203 compiler_use_next_block(c, except);
2204 }
2205 ADDOP(c, END_FINALLY);
2206 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002207 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 compiler_use_next_block(c, end);
2209 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210}
2211
2212static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002213compiler_try(struct compiler *c, stmt_ty s) {
2214 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2215 return compiler_try_finally(c, s);
2216 else
2217 return compiler_try_except(c, s);
2218}
2219
2220
2221static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222compiler_import_as(struct compiler *c, identifier name, identifier asname)
2223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* The IMPORT_NAME opcode was already generated. This function
2225 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 If there is a dot in name, we need to split it and emit a
2228 LOAD_ATTR for each name.
2229 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002230 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2231 PyUnicode_GET_LENGTH(name), 1);
2232 if (dot == -2)
2233 return -1;
2234 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 Py_ssize_t pos = dot + 1;
2237 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002239 dot = PyUnicode_FindChar(name, '.', pos,
2240 PyUnicode_GET_LENGTH(name), 1);
2241 if (dot == -2)
2242 return -1;
2243 attr = PyUnicode_Substring(name, pos,
2244 (dot != -1) ? dot :
2245 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 if (!attr)
2247 return -1;
2248 ADDOP_O(c, LOAD_ATTR, attr, names);
2249 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002250 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 }
2252 }
2253 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254}
2255
2256static int
2257compiler_import(struct compiler *c, stmt_ty s)
2258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* The Import node stores a module name like a.b.c as a single
2260 string. This is convenient for all cases except
2261 import a.b.c as d
2262 where we need to parse that string to extract the individual
2263 module names.
2264 XXX Perhaps change the representation to make this case simpler?
2265 */
2266 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 for (i = 0; i < n; i++) {
2269 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2270 int r;
2271 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 level = PyLong_FromLong(0);
2274 if (level == NULL)
2275 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 ADDOP_O(c, LOAD_CONST, level, consts);
2278 Py_DECREF(level);
2279 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2280 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (alias->asname) {
2283 r = compiler_import_as(c, alias->name, alias->asname);
2284 if (!r)
2285 return r;
2286 }
2287 else {
2288 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002289 Py_ssize_t dot = PyUnicode_FindChar(
2290 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2291 if (dot != -1)
2292 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002294 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 Py_DECREF(tmp);
2296 }
2297 if (!r)
2298 return r;
2299 }
2300 }
2301 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302}
2303
2304static int
2305compiler_from_import(struct compiler *c, stmt_ty s)
2306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 PyObject *names = PyTuple_New(n);
2310 PyObject *level;
2311 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (!empty_string) {
2314 empty_string = PyUnicode_FromString("");
2315 if (!empty_string)
2316 return 0;
2317 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 if (!names)
2320 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 level = PyLong_FromLong(s->v.ImportFrom.level);
2323 if (!level) {
2324 Py_DECREF(names);
2325 return 0;
2326 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 /* build up the names */
2329 for (i = 0; i < n; i++) {
2330 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2331 Py_INCREF(alias->name);
2332 PyTuple_SET_ITEM(names, i, alias->name);
2333 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2336 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2337 Py_DECREF(level);
2338 Py_DECREF(names);
2339 return compiler_error(c, "from __future__ imports must occur "
2340 "at the beginning of the file");
2341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 ADDOP_O(c, LOAD_CONST, level, consts);
2344 Py_DECREF(level);
2345 ADDOP_O(c, LOAD_CONST, names, consts);
2346 Py_DECREF(names);
2347 if (s->v.ImportFrom.module) {
2348 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2349 }
2350 else {
2351 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2352 }
2353 for (i = 0; i < n; i++) {
2354 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2355 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002357 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 assert(n == 1);
2359 ADDOP(c, IMPORT_STAR);
2360 return 1;
2361 }
2362
2363 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2364 store_name = alias->name;
2365 if (alias->asname)
2366 store_name = alias->asname;
2367
2368 if (!compiler_nameop(c, store_name, Store)) {
2369 Py_DECREF(names);
2370 return 0;
2371 }
2372 }
2373 /* remove imported module */
2374 ADDOP(c, POP_TOP);
2375 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376}
2377
2378static int
2379compiler_assert(struct compiler *c, stmt_ty s)
2380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 static PyObject *assertion_error = NULL;
2382 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383
Georg Brandl8334fd92010-12-04 10:26:46 +00002384 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 return 1;
2386 if (assertion_error == NULL) {
2387 assertion_error = PyUnicode_InternFromString("AssertionError");
2388 if (assertion_error == NULL)
2389 return 0;
2390 }
2391 if (s->v.Assert.test->kind == Tuple_kind &&
2392 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2393 const char* msg =
2394 "assertion is always true, perhaps remove parentheses?";
2395 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2396 c->u->u_lineno, NULL, NULL) == -1)
2397 return 0;
2398 }
2399 VISIT(c, expr, s->v.Assert.test);
2400 end = compiler_new_block(c);
2401 if (end == NULL)
2402 return 0;
2403 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2404 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2405 if (s->v.Assert.msg) {
2406 VISIT(c, expr, s->v.Assert.msg);
2407 ADDOP_I(c, CALL_FUNCTION, 1);
2408 }
2409 ADDOP_I(c, RAISE_VARARGS, 1);
2410 compiler_use_next_block(c, end);
2411 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412}
2413
2414static int
2415compiler_visit_stmt(struct compiler *c, stmt_ty s)
2416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 /* Always assign a lineno to the next instruction for a stmt. */
2420 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002421 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 switch (s->kind) {
2425 case FunctionDef_kind:
2426 return compiler_function(c, s);
2427 case ClassDef_kind:
2428 return compiler_class(c, s);
2429 case Return_kind:
2430 if (c->u->u_ste->ste_type != FunctionBlock)
2431 return compiler_error(c, "'return' outside function");
2432 if (s->v.Return.value) {
2433 VISIT(c, expr, s->v.Return.value);
2434 }
2435 else
2436 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2437 ADDOP(c, RETURN_VALUE);
2438 break;
2439 case Delete_kind:
2440 VISIT_SEQ(c, expr, s->v.Delete.targets)
2441 break;
2442 case Assign_kind:
2443 n = asdl_seq_LEN(s->v.Assign.targets);
2444 VISIT(c, expr, s->v.Assign.value);
2445 for (i = 0; i < n; i++) {
2446 if (i < n - 1)
2447 ADDOP(c, DUP_TOP);
2448 VISIT(c, expr,
2449 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2450 }
2451 break;
2452 case AugAssign_kind:
2453 return compiler_augassign(c, s);
2454 case For_kind:
2455 return compiler_for(c, s);
2456 case While_kind:
2457 return compiler_while(c, s);
2458 case If_kind:
2459 return compiler_if(c, s);
2460 case Raise_kind:
2461 n = 0;
2462 if (s->v.Raise.exc) {
2463 VISIT(c, expr, s->v.Raise.exc);
2464 n++;
2465 if (s->v.Raise.cause) {
2466 VISIT(c, expr, s->v.Raise.cause);
2467 n++;
2468 }
2469 }
2470 ADDOP_I(c, RAISE_VARARGS, n);
2471 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002472 case Try_kind:
2473 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 case Assert_kind:
2475 return compiler_assert(c, s);
2476 case Import_kind:
2477 return compiler_import(c, s);
2478 case ImportFrom_kind:
2479 return compiler_from_import(c, s);
2480 case Global_kind:
2481 case Nonlocal_kind:
2482 break;
2483 case Expr_kind:
2484 if (c->c_interactive && c->c_nestlevel <= 1) {
2485 VISIT(c, expr, s->v.Expr.value);
2486 ADDOP(c, PRINT_EXPR);
2487 }
2488 else if (s->v.Expr.value->kind != Str_kind &&
2489 s->v.Expr.value->kind != Num_kind) {
2490 VISIT(c, expr, s->v.Expr.value);
2491 ADDOP(c, POP_TOP);
2492 }
2493 break;
2494 case Pass_kind:
2495 break;
2496 case Break_kind:
2497 if (!compiler_in_loop(c))
2498 return compiler_error(c, "'break' outside loop");
2499 ADDOP(c, BREAK_LOOP);
2500 break;
2501 case Continue_kind:
2502 return compiler_continue(c);
2503 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002504 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 }
2506 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507}
2508
2509static int
2510unaryop(unaryop_ty op)
2511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 switch (op) {
2513 case Invert:
2514 return UNARY_INVERT;
2515 case Not:
2516 return UNARY_NOT;
2517 case UAdd:
2518 return UNARY_POSITIVE;
2519 case USub:
2520 return UNARY_NEGATIVE;
2521 default:
2522 PyErr_Format(PyExc_SystemError,
2523 "unary op %d should not be possible", op);
2524 return 0;
2525 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526}
2527
2528static int
2529binop(struct compiler *c, operator_ty op)
2530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 switch (op) {
2532 case Add:
2533 return BINARY_ADD;
2534 case Sub:
2535 return BINARY_SUBTRACT;
2536 case Mult:
2537 return BINARY_MULTIPLY;
2538 case Div:
2539 return BINARY_TRUE_DIVIDE;
2540 case Mod:
2541 return BINARY_MODULO;
2542 case Pow:
2543 return BINARY_POWER;
2544 case LShift:
2545 return BINARY_LSHIFT;
2546 case RShift:
2547 return BINARY_RSHIFT;
2548 case BitOr:
2549 return BINARY_OR;
2550 case BitXor:
2551 return BINARY_XOR;
2552 case BitAnd:
2553 return BINARY_AND;
2554 case FloorDiv:
2555 return BINARY_FLOOR_DIVIDE;
2556 default:
2557 PyErr_Format(PyExc_SystemError,
2558 "binary op %d should not be possible", op);
2559 return 0;
2560 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561}
2562
2563static int
2564cmpop(cmpop_ty op)
2565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 switch (op) {
2567 case Eq:
2568 return PyCmp_EQ;
2569 case NotEq:
2570 return PyCmp_NE;
2571 case Lt:
2572 return PyCmp_LT;
2573 case LtE:
2574 return PyCmp_LE;
2575 case Gt:
2576 return PyCmp_GT;
2577 case GtE:
2578 return PyCmp_GE;
2579 case Is:
2580 return PyCmp_IS;
2581 case IsNot:
2582 return PyCmp_IS_NOT;
2583 case In:
2584 return PyCmp_IN;
2585 case NotIn:
2586 return PyCmp_NOT_IN;
2587 default:
2588 return PyCmp_BAD;
2589 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590}
2591
2592static int
2593inplace_binop(struct compiler *c, operator_ty op)
2594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 switch (op) {
2596 case Add:
2597 return INPLACE_ADD;
2598 case Sub:
2599 return INPLACE_SUBTRACT;
2600 case Mult:
2601 return INPLACE_MULTIPLY;
2602 case Div:
2603 return INPLACE_TRUE_DIVIDE;
2604 case Mod:
2605 return INPLACE_MODULO;
2606 case Pow:
2607 return INPLACE_POWER;
2608 case LShift:
2609 return INPLACE_LSHIFT;
2610 case RShift:
2611 return INPLACE_RSHIFT;
2612 case BitOr:
2613 return INPLACE_OR;
2614 case BitXor:
2615 return INPLACE_XOR;
2616 case BitAnd:
2617 return INPLACE_AND;
2618 case FloorDiv:
2619 return INPLACE_FLOOR_DIVIDE;
2620 default:
2621 PyErr_Format(PyExc_SystemError,
2622 "inplace binary op %d should not be possible", op);
2623 return 0;
2624 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625}
2626
2627static int
2628compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 int op, scope, arg;
2631 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 PyObject *dict = c->u->u_names;
2634 PyObject *mangled;
2635 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 mangled = _Py_Mangle(c->u->u_private, name);
2638 if (!mangled)
2639 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 op = 0;
2642 optype = OP_NAME;
2643 scope = PyST_GetScope(c->u->u_ste, mangled);
2644 switch (scope) {
2645 case FREE:
2646 dict = c->u->u_freevars;
2647 optype = OP_DEREF;
2648 break;
2649 case CELL:
2650 dict = c->u->u_cellvars;
2651 optype = OP_DEREF;
2652 break;
2653 case LOCAL:
2654 if (c->u->u_ste->ste_type == FunctionBlock)
2655 optype = OP_FAST;
2656 break;
2657 case GLOBAL_IMPLICIT:
2658 if (c->u->u_ste->ste_type == FunctionBlock &&
2659 !c->u->u_ste->ste_unoptimized)
2660 optype = OP_GLOBAL;
2661 break;
2662 case GLOBAL_EXPLICIT:
2663 optype = OP_GLOBAL;
2664 break;
2665 default:
2666 /* scope can be 0 */
2667 break;
2668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002671 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 switch (optype) {
2674 case OP_DEREF:
2675 switch (ctx) {
2676 case Load: op = LOAD_DEREF; break;
2677 case Store: op = STORE_DEREF; break;
2678 case AugLoad:
2679 case AugStore:
2680 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002681 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 case Param:
2683 default:
2684 PyErr_SetString(PyExc_SystemError,
2685 "param invalid for deref variable");
2686 return 0;
2687 }
2688 break;
2689 case OP_FAST:
2690 switch (ctx) {
2691 case Load: op = LOAD_FAST; break;
2692 case Store: op = STORE_FAST; break;
2693 case Del: op = DELETE_FAST; break;
2694 case AugLoad:
2695 case AugStore:
2696 break;
2697 case Param:
2698 default:
2699 PyErr_SetString(PyExc_SystemError,
2700 "param invalid for local variable");
2701 return 0;
2702 }
2703 ADDOP_O(c, op, mangled, varnames);
2704 Py_DECREF(mangled);
2705 return 1;
2706 case OP_GLOBAL:
2707 switch (ctx) {
2708 case Load: op = LOAD_GLOBAL; break;
2709 case Store: op = STORE_GLOBAL; break;
2710 case Del: op = DELETE_GLOBAL; break;
2711 case AugLoad:
2712 case AugStore:
2713 break;
2714 case Param:
2715 default:
2716 PyErr_SetString(PyExc_SystemError,
2717 "param invalid for global variable");
2718 return 0;
2719 }
2720 break;
2721 case OP_NAME:
2722 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002723 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 case Store: op = STORE_NAME; break;
2725 case Del: op = DELETE_NAME; break;
2726 case AugLoad:
2727 case AugStore:
2728 break;
2729 case Param:
2730 default:
2731 PyErr_SetString(PyExc_SystemError,
2732 "param invalid for name variable");
2733 return 0;
2734 }
2735 break;
2736 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 assert(op);
2739 arg = compiler_add_o(c, dict, mangled);
2740 Py_DECREF(mangled);
2741 if (arg < 0)
2742 return 0;
2743 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744}
2745
2746static int
2747compiler_boolop(struct compiler *c, expr_ty e)
2748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 basicblock *end;
2750 int jumpi, i, n;
2751 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 assert(e->kind == BoolOp_kind);
2754 if (e->v.BoolOp.op == And)
2755 jumpi = JUMP_IF_FALSE_OR_POP;
2756 else
2757 jumpi = JUMP_IF_TRUE_OR_POP;
2758 end = compiler_new_block(c);
2759 if (end == NULL)
2760 return 0;
2761 s = e->v.BoolOp.values;
2762 n = asdl_seq_LEN(s) - 1;
2763 assert(n >= 0);
2764 for (i = 0; i < n; ++i) {
2765 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2766 ADDOP_JABS(c, jumpi, end);
2767 }
2768 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2769 compiler_use_next_block(c, end);
2770 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771}
2772
2773static int
2774compiler_list(struct compiler *c, expr_ty e)
2775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 int n = asdl_seq_LEN(e->v.List.elts);
2777 if (e->v.List.ctx == Store) {
2778 int i, seen_star = 0;
2779 for (i = 0; i < n; i++) {
2780 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2781 if (elt->kind == Starred_kind && !seen_star) {
2782 if ((i >= (1 << 8)) ||
2783 (n-i-1 >= (INT_MAX >> 8)))
2784 return compiler_error(c,
2785 "too many expressions in "
2786 "star-unpacking assignment");
2787 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2788 seen_star = 1;
2789 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2790 } else if (elt->kind == Starred_kind) {
2791 return compiler_error(c,
2792 "two starred expressions in assignment");
2793 }
2794 }
2795 if (!seen_star) {
2796 ADDOP_I(c, UNPACK_SEQUENCE, n);
2797 }
2798 }
2799 VISIT_SEQ(c, expr, e->v.List.elts);
2800 if (e->v.List.ctx == Load) {
2801 ADDOP_I(c, BUILD_LIST, n);
2802 }
2803 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804}
2805
2806static int
2807compiler_tuple(struct compiler *c, expr_ty e)
2808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 int n = asdl_seq_LEN(e->v.Tuple.elts);
2810 if (e->v.Tuple.ctx == Store) {
2811 int i, seen_star = 0;
2812 for (i = 0; i < n; i++) {
2813 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2814 if (elt->kind == Starred_kind && !seen_star) {
2815 if ((i >= (1 << 8)) ||
2816 (n-i-1 >= (INT_MAX >> 8)))
2817 return compiler_error(c,
2818 "too many expressions in "
2819 "star-unpacking assignment");
2820 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2821 seen_star = 1;
2822 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2823 } else if (elt->kind == Starred_kind) {
2824 return compiler_error(c,
2825 "two starred expressions in assignment");
2826 }
2827 }
2828 if (!seen_star) {
2829 ADDOP_I(c, UNPACK_SEQUENCE, n);
2830 }
2831 }
2832 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2833 if (e->v.Tuple.ctx == Load) {
2834 ADDOP_I(c, BUILD_TUPLE, n);
2835 }
2836 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837}
2838
2839static int
2840compiler_compare(struct compiler *c, expr_ty e)
2841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 int i, n;
2843 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2846 VISIT(c, expr, e->v.Compare.left);
2847 n = asdl_seq_LEN(e->v.Compare.ops);
2848 assert(n > 0);
2849 if (n > 1) {
2850 cleanup = compiler_new_block(c);
2851 if (cleanup == NULL)
2852 return 0;
2853 VISIT(c, expr,
2854 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2855 }
2856 for (i = 1; i < n; i++) {
2857 ADDOP(c, DUP_TOP);
2858 ADDOP(c, ROT_THREE);
2859 ADDOP_I(c, COMPARE_OP,
2860 cmpop((cmpop_ty)(asdl_seq_GET(
2861 e->v.Compare.ops, i - 1))));
2862 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2863 NEXT_BLOCK(c);
2864 if (i < (n - 1))
2865 VISIT(c, expr,
2866 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2867 }
2868 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2869 ADDOP_I(c, COMPARE_OP,
2870 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2871 if (n > 1) {
2872 basicblock *end = compiler_new_block(c);
2873 if (end == NULL)
2874 return 0;
2875 ADDOP_JREL(c, JUMP_FORWARD, end);
2876 compiler_use_next_block(c, cleanup);
2877 ADDOP(c, ROT_TWO);
2878 ADDOP(c, POP_TOP);
2879 compiler_use_next_block(c, end);
2880 }
2881 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882}
2883
2884static int
2885compiler_call(struct compiler *c, expr_ty e)
2886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 VISIT(c, expr, e->v.Call.func);
2888 return compiler_call_helper(c, 0,
2889 e->v.Call.args,
2890 e->v.Call.keywords,
2891 e->v.Call.starargs,
2892 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002893}
2894
2895/* shared code between compiler_call and compiler_class */
2896static int
2897compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 int n, /* Args already pushed */
2899 asdl_seq *args,
2900 asdl_seq *keywords,
2901 expr_ty starargs,
2902 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 n += asdl_seq_LEN(args);
2907 VISIT_SEQ(c, expr, args);
2908 if (keywords) {
2909 VISIT_SEQ(c, keyword, keywords);
2910 n |= asdl_seq_LEN(keywords) << 8;
2911 }
2912 if (starargs) {
2913 VISIT(c, expr, starargs);
2914 code |= 1;
2915 }
2916 if (kwargs) {
2917 VISIT(c, expr, kwargs);
2918 code |= 2;
2919 }
2920 switch (code) {
2921 case 0:
2922 ADDOP_I(c, CALL_FUNCTION, n);
2923 break;
2924 case 1:
2925 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2926 break;
2927 case 2:
2928 ADDOP_I(c, CALL_FUNCTION_KW, n);
2929 break;
2930 case 3:
2931 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2932 break;
2933 }
2934 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935}
2936
Nick Coghlan650f0d02007-04-15 12:05:43 +00002937
2938/* List and set comprehensions and generator expressions work by creating a
2939 nested function to perform the actual iteration. This means that the
2940 iteration variables don't leak into the current scope.
2941 The defined function is called immediately following its definition, with the
2942 result of that call being the result of the expression.
2943 The LC/SC version returns the populated container, while the GE version is
2944 flagged in symtable.c as a generator, so it returns the generator object
2945 when the function is called.
2946 This code *knows* that the loop cannot contain break, continue, or return,
2947 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2948
2949 Possible cleanups:
2950 - iterate over the generator sequence instead of using recursion
2951*/
2952
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954compiler_comprehension_generator(struct compiler *c,
2955 asdl_seq *generators, int gen_index,
2956 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 /* generate code for the iterator, then each of the ifs,
2959 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 comprehension_ty gen;
2962 basicblock *start, *anchor, *skip, *if_cleanup;
2963 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 start = compiler_new_block(c);
2966 skip = compiler_new_block(c);
2967 if_cleanup = compiler_new_block(c);
2968 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2971 anchor == NULL)
2972 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 if (gen_index == 0) {
2977 /* Receive outermost iter as an implicit argument */
2978 c->u->u_argcount = 1;
2979 ADDOP_I(c, LOAD_FAST, 0);
2980 }
2981 else {
2982 /* Sub-iter - calculate on the fly */
2983 VISIT(c, expr, gen->iter);
2984 ADDOP(c, GET_ITER);
2985 }
2986 compiler_use_next_block(c, start);
2987 ADDOP_JREL(c, FOR_ITER, anchor);
2988 NEXT_BLOCK(c);
2989 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 /* XXX this needs to be cleaned up...a lot! */
2992 n = asdl_seq_LEN(gen->ifs);
2993 for (i = 0; i < n; i++) {
2994 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2995 VISIT(c, expr, e);
2996 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2997 NEXT_BLOCK(c);
2998 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 if (++gen_index < asdl_seq_LEN(generators))
3001 if (!compiler_comprehension_generator(c,
3002 generators, gen_index,
3003 elt, val, type))
3004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 /* only append after the last for generator */
3007 if (gen_index >= asdl_seq_LEN(generators)) {
3008 /* comprehension specific code */
3009 switch (type) {
3010 case COMP_GENEXP:
3011 VISIT(c, expr, elt);
3012 ADDOP(c, YIELD_VALUE);
3013 ADDOP(c, POP_TOP);
3014 break;
3015 case COMP_LISTCOMP:
3016 VISIT(c, expr, elt);
3017 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3018 break;
3019 case COMP_SETCOMP:
3020 VISIT(c, expr, elt);
3021 ADDOP_I(c, SET_ADD, gen_index + 1);
3022 break;
3023 case COMP_DICTCOMP:
3024 /* With 'd[k] = v', v is evaluated before k, so we do
3025 the same. */
3026 VISIT(c, expr, val);
3027 VISIT(c, expr, elt);
3028 ADDOP_I(c, MAP_ADD, gen_index + 1);
3029 break;
3030 default:
3031 return 0;
3032 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 compiler_use_next_block(c, skip);
3035 }
3036 compiler_use_next_block(c, if_cleanup);
3037 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3038 compiler_use_next_block(c, anchor);
3039
3040 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041}
3042
3043static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003044compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 PyCodeObject *co = NULL;
3048 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003049 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 outermost_iter = ((comprehension_ty)
3052 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003053
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003054 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3055 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 if (type != COMP_GENEXP) {
3059 int op;
3060 switch (type) {
3061 case COMP_LISTCOMP:
3062 op = BUILD_LIST;
3063 break;
3064 case COMP_SETCOMP:
3065 op = BUILD_SET;
3066 break;
3067 case COMP_DICTCOMP:
3068 op = BUILD_MAP;
3069 break;
3070 default:
3071 PyErr_Format(PyExc_SystemError,
3072 "unknown comprehension type %d", type);
3073 goto error_in_scope;
3074 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 ADDOP_I(c, op, 0);
3077 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 if (!compiler_comprehension_generator(c, generators, 0, elt,
3080 val, type))
3081 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 if (type != COMP_GENEXP) {
3084 ADDOP(c, RETURN_VALUE);
3085 }
3086
3087 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003088 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003090 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 goto error;
3092
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003093 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003095 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 Py_DECREF(co);
3097
3098 VISIT(c, expr, outermost_iter);
3099 ADDOP(c, GET_ITER);
3100 ADDOP_I(c, CALL_FUNCTION, 1);
3101 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003102error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003104error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003105 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 Py_XDECREF(co);
3107 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003108}
3109
3110static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111compiler_genexp(struct compiler *c, expr_ty e)
3112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 static identifier name;
3114 if (!name) {
3115 name = PyUnicode_FromString("<genexpr>");
3116 if (!name)
3117 return 0;
3118 }
3119 assert(e->kind == GeneratorExp_kind);
3120 return compiler_comprehension(c, e, COMP_GENEXP, name,
3121 e->v.GeneratorExp.generators,
3122 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123}
3124
3125static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003126compiler_listcomp(struct compiler *c, expr_ty e)
3127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 static identifier name;
3129 if (!name) {
3130 name = PyUnicode_FromString("<listcomp>");
3131 if (!name)
3132 return 0;
3133 }
3134 assert(e->kind == ListComp_kind);
3135 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3136 e->v.ListComp.generators,
3137 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003138}
3139
3140static int
3141compiler_setcomp(struct compiler *c, expr_ty e)
3142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 static identifier name;
3144 if (!name) {
3145 name = PyUnicode_FromString("<setcomp>");
3146 if (!name)
3147 return 0;
3148 }
3149 assert(e->kind == SetComp_kind);
3150 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3151 e->v.SetComp.generators,
3152 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003153}
3154
3155
3156static int
3157compiler_dictcomp(struct compiler *c, expr_ty e)
3158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 static identifier name;
3160 if (!name) {
3161 name = PyUnicode_FromString("<dictcomp>");
3162 if (!name)
3163 return 0;
3164 }
3165 assert(e->kind == DictComp_kind);
3166 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3167 e->v.DictComp.generators,
3168 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003169}
3170
3171
3172static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173compiler_visit_keyword(struct compiler *c, keyword_ty k)
3174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3176 VISIT(c, expr, k->value);
3177 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178}
3179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181 whether they are true or false.
3182
3183 Return values: 1 for true, 0 for false, -1 for non-constant.
3184 */
3185
3186static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003187expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 char *id;
3190 switch (e->kind) {
3191 case Ellipsis_kind:
3192 return 1;
3193 case Num_kind:
3194 return PyObject_IsTrue(e->v.Num.n);
3195 case Str_kind:
3196 return PyObject_IsTrue(e->v.Str.s);
3197 case Name_kind:
3198 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003199 id = PyUnicode_AsUTF8(e->v.Name.id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 if (strcmp(id, "True") == 0) return 1;
3201 if (strcmp(id, "False") == 0) return 0;
3202 if (strcmp(id, "None") == 0) return 0;
3203 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003204 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 /* fall through */
3206 default:
3207 return -1;
3208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209}
3210
Guido van Rossumc2e20742006-02-27 22:32:47 +00003211/*
3212 Implements the with statement from PEP 343.
3213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003215
3216 with EXPR as VAR:
3217 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218
Guido van Rossumc2e20742006-02-27 22:32:47 +00003219 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220
Thomas Wouters477c8d52006-05-27 19:21:47 +00003221 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003222 exit = context.__exit__ # not calling it
3223 value = context.__enter__()
3224 try:
3225 VAR = value # if VAR present in the syntax
3226 BLOCK
3227 finally:
3228 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003230 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003232 exit(*exc)
3233 */
3234static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003235compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003236{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003237 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003238 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003239
3240 assert(s->kind == With_kind);
3241
Guido van Rossumc2e20742006-02-27 22:32:47 +00003242 block = compiler_new_block(c);
3243 finally = compiler_new_block(c);
3244 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003245 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003246
Thomas Wouters477c8d52006-05-27 19:21:47 +00003247 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003248 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003249 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003250
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003251 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003252 compiler_use_next_block(c, block);
3253 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003254 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003255 }
3256
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003257 if (item->optional_vars) {
3258 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003259 }
3260 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003262 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003263 }
3264
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003265 pos++;
3266 if (pos == asdl_seq_LEN(s->v.With.items))
3267 /* BLOCK code */
3268 VISIT_SEQ(c, stmt, s->v.With.body)
3269 else if (!compiler_with(c, s, pos))
3270 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003271
3272 /* End of try block; start the finally block */
3273 ADDOP(c, POP_BLOCK);
3274 compiler_pop_fblock(c, FINALLY_TRY, block);
3275
3276 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3277 compiler_use_next_block(c, finally);
3278 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003279 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003280
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003281 /* Finally block starts; context.__exit__ is on the stack under
3282 the exception or return information. Just issue our magic
3283 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003284 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003285
3286 /* Finally block ends. */
3287 ADDOP(c, END_FINALLY);
3288 compiler_pop_fblock(c, FINALLY_END, finally);
3289 return 1;
3290}
3291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292static int
3293compiler_visit_expr(struct compiler *c, expr_ty e)
3294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 /* If expr e has a different line number than the last expr/stmt,
3298 set a new line number for the next instruction.
3299 */
3300 if (e->lineno > c->u->u_lineno) {
3301 c->u->u_lineno = e->lineno;
3302 c->u->u_lineno_set = 0;
3303 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003304 /* Updating the column offset is always harmless. */
3305 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 switch (e->kind) {
3307 case BoolOp_kind:
3308 return compiler_boolop(c, e);
3309 case BinOp_kind:
3310 VISIT(c, expr, e->v.BinOp.left);
3311 VISIT(c, expr, e->v.BinOp.right);
3312 ADDOP(c, binop(c, e->v.BinOp.op));
3313 break;
3314 case UnaryOp_kind:
3315 VISIT(c, expr, e->v.UnaryOp.operand);
3316 ADDOP(c, unaryop(e->v.UnaryOp.op));
3317 break;
3318 case Lambda_kind:
3319 return compiler_lambda(c, e);
3320 case IfExp_kind:
3321 return compiler_ifexp(c, e);
3322 case Dict_kind:
3323 n = asdl_seq_LEN(e->v.Dict.values);
3324 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3325 for (i = 0; i < n; i++) {
3326 VISIT(c, expr,
3327 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3328 VISIT(c, expr,
3329 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3330 ADDOP(c, STORE_MAP);
3331 }
3332 break;
3333 case Set_kind:
3334 n = asdl_seq_LEN(e->v.Set.elts);
3335 VISIT_SEQ(c, expr, e->v.Set.elts);
3336 ADDOP_I(c, BUILD_SET, n);
3337 break;
3338 case GeneratorExp_kind:
3339 return compiler_genexp(c, e);
3340 case ListComp_kind:
3341 return compiler_listcomp(c, e);
3342 case SetComp_kind:
3343 return compiler_setcomp(c, e);
3344 case DictComp_kind:
3345 return compiler_dictcomp(c, e);
3346 case Yield_kind:
3347 if (c->u->u_ste->ste_type != FunctionBlock)
3348 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003349 if (e->v.Yield.value) {
3350 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 }
3352 else {
3353 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3354 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003355 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003357 case YieldFrom_kind:
3358 if (c->u->u_ste->ste_type != FunctionBlock)
3359 return compiler_error(c, "'yield' outside function");
3360 VISIT(c, expr, e->v.YieldFrom.value);
3361 ADDOP(c, GET_ITER);
3362 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3363 ADDOP(c, YIELD_FROM);
3364 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 case Compare_kind:
3366 return compiler_compare(c, e);
3367 case Call_kind:
3368 return compiler_call(c, e);
3369 case Num_kind:
3370 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3371 break;
3372 case Str_kind:
3373 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3374 break;
3375 case Bytes_kind:
3376 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3377 break;
3378 case Ellipsis_kind:
3379 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3380 break;
3381 /* The following exprs can be assignment targets. */
3382 case Attribute_kind:
3383 if (e->v.Attribute.ctx != AugStore)
3384 VISIT(c, expr, e->v.Attribute.value);
3385 switch (e->v.Attribute.ctx) {
3386 case AugLoad:
3387 ADDOP(c, DUP_TOP);
3388 /* Fall through to load */
3389 case Load:
3390 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3391 break;
3392 case AugStore:
3393 ADDOP(c, ROT_TWO);
3394 /* Fall through to save */
3395 case Store:
3396 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3397 break;
3398 case Del:
3399 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3400 break;
3401 case Param:
3402 default:
3403 PyErr_SetString(PyExc_SystemError,
3404 "param invalid in attribute expression");
3405 return 0;
3406 }
3407 break;
3408 case Subscript_kind:
3409 switch (e->v.Subscript.ctx) {
3410 case AugLoad:
3411 VISIT(c, expr, e->v.Subscript.value);
3412 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3413 break;
3414 case Load:
3415 VISIT(c, expr, e->v.Subscript.value);
3416 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3417 break;
3418 case AugStore:
3419 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3420 break;
3421 case Store:
3422 VISIT(c, expr, e->v.Subscript.value);
3423 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3424 break;
3425 case Del:
3426 VISIT(c, expr, e->v.Subscript.value);
3427 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3428 break;
3429 case Param:
3430 default:
3431 PyErr_SetString(PyExc_SystemError,
3432 "param invalid in subscript expression");
3433 return 0;
3434 }
3435 break;
3436 case Starred_kind:
3437 switch (e->v.Starred.ctx) {
3438 case Store:
3439 /* In all legitimate cases, the Starred node was already replaced
3440 * by compiler_list/compiler_tuple. XXX: is that okay? */
3441 return compiler_error(c,
3442 "starred assignment target must be in a list or tuple");
3443 default:
3444 return compiler_error(c,
3445 "can use starred expression only as assignment target");
3446 }
3447 break;
3448 case Name_kind:
3449 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3450 /* child nodes of List and Tuple will have expr_context set */
3451 case List_kind:
3452 return compiler_list(c, e);
3453 case Tuple_kind:
3454 return compiler_tuple(c, e);
3455 }
3456 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457}
3458
3459static int
3460compiler_augassign(struct compiler *c, stmt_ty s)
3461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 expr_ty e = s->v.AugAssign.target;
3463 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 switch (e->kind) {
3468 case Attribute_kind:
3469 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3470 AugLoad, e->lineno, e->col_offset, c->c_arena);
3471 if (auge == NULL)
3472 return 0;
3473 VISIT(c, expr, auge);
3474 VISIT(c, expr, s->v.AugAssign.value);
3475 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3476 auge->v.Attribute.ctx = AugStore;
3477 VISIT(c, expr, auge);
3478 break;
3479 case Subscript_kind:
3480 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3481 AugLoad, e->lineno, e->col_offset, c->c_arena);
3482 if (auge == NULL)
3483 return 0;
3484 VISIT(c, expr, auge);
3485 VISIT(c, expr, s->v.AugAssign.value);
3486 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3487 auge->v.Subscript.ctx = AugStore;
3488 VISIT(c, expr, auge);
3489 break;
3490 case Name_kind:
3491 if (!compiler_nameop(c, e->v.Name.id, Load))
3492 return 0;
3493 VISIT(c, expr, s->v.AugAssign.value);
3494 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3495 return compiler_nameop(c, e->v.Name.id, Store);
3496 default:
3497 PyErr_Format(PyExc_SystemError,
3498 "invalid node type (%d) for augmented assignment",
3499 e->kind);
3500 return 0;
3501 }
3502 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503}
3504
3505static int
3506compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 struct fblockinfo *f;
3509 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3510 PyErr_SetString(PyExc_SystemError,
3511 "too many statically nested blocks");
3512 return 0;
3513 }
3514 f = &c->u->u_fblock[c->u->u_nfblocks++];
3515 f->fb_type = t;
3516 f->fb_block = b;
3517 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518}
3519
3520static void
3521compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 struct compiler_unit *u = c->u;
3524 assert(u->u_nfblocks > 0);
3525 u->u_nfblocks--;
3526 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3527 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528}
3529
Thomas Wouters89f507f2006-12-13 04:49:30 +00003530static int
3531compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 int i;
3533 struct compiler_unit *u = c->u;
3534 for (i = 0; i < u->u_nfblocks; ++i) {
3535 if (u->u_fblock[i].fb_type == LOOP)
3536 return 1;
3537 }
3538 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003539}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540/* Raises a SyntaxError and returns 0.
3541 If something goes wrong, a different exception may be raised.
3542*/
3543
3544static int
3545compiler_error(struct compiler *c, const char *errstr)
3546{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003547 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3551 if (!loc) {
3552 Py_INCREF(Py_None);
3553 loc = Py_None;
3554 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003555 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003556 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 if (!u)
3558 goto exit;
3559 v = Py_BuildValue("(zO)", errstr, u);
3560 if (!v)
3561 goto exit;
3562 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_DECREF(loc);
3565 Py_XDECREF(u);
3566 Py_XDECREF(v);
3567 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568}
3569
3570static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571compiler_handle_subscr(struct compiler *c, const char *kind,
3572 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 /* XXX this code is duplicated */
3577 switch (ctx) {
3578 case AugLoad: /* fall through to Load */
3579 case Load: op = BINARY_SUBSCR; break;
3580 case AugStore:/* fall through to Store */
3581 case Store: op = STORE_SUBSCR; break;
3582 case Del: op = DELETE_SUBSCR; break;
3583 case Param:
3584 PyErr_Format(PyExc_SystemError,
3585 "invalid %s kind %d in subscript\n",
3586 kind, ctx);
3587 return 0;
3588 }
3589 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003590 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 }
3592 else if (ctx == AugStore) {
3593 ADDOP(c, ROT_THREE);
3594 }
3595 ADDOP(c, op);
3596 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597}
3598
3599static int
3600compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 int n = 2;
3603 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 /* only handles the cases where BUILD_SLICE is emitted */
3606 if (s->v.Slice.lower) {
3607 VISIT(c, expr, s->v.Slice.lower);
3608 }
3609 else {
3610 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3611 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 if (s->v.Slice.upper) {
3614 VISIT(c, expr, s->v.Slice.upper);
3615 }
3616 else {
3617 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3618 }
3619
3620 if (s->v.Slice.step) {
3621 n++;
3622 VISIT(c, expr, s->v.Slice.step);
3623 }
3624 ADDOP_I(c, BUILD_SLICE, n);
3625 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626}
3627
3628static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3630 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 switch (s->kind) {
3633 case Slice_kind:
3634 return compiler_slice(c, s, ctx);
3635 case Index_kind:
3636 VISIT(c, expr, s->v.Index.value);
3637 break;
3638 case ExtSlice_kind:
3639 default:
3640 PyErr_SetString(PyExc_SystemError,
3641 "extended slice invalid in nested slice");
3642 return 0;
3643 }
3644 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645}
3646
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647static int
3648compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 char * kindname = NULL;
3651 switch (s->kind) {
3652 case Index_kind:
3653 kindname = "index";
3654 if (ctx != AugStore) {
3655 VISIT(c, expr, s->v.Index.value);
3656 }
3657 break;
3658 case Slice_kind:
3659 kindname = "slice";
3660 if (ctx != AugStore) {
3661 if (!compiler_slice(c, s, ctx))
3662 return 0;
3663 }
3664 break;
3665 case ExtSlice_kind:
3666 kindname = "extended slice";
3667 if (ctx != AugStore) {
3668 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3669 for (i = 0; i < n; i++) {
3670 slice_ty sub = (slice_ty)asdl_seq_GET(
3671 s->v.ExtSlice.dims, i);
3672 if (!compiler_visit_nested_slice(c, sub, ctx))
3673 return 0;
3674 }
3675 ADDOP_I(c, BUILD_TUPLE, n);
3676 }
3677 break;
3678 default:
3679 PyErr_Format(PyExc_SystemError,
3680 "invalid subscript kind %d", s->kind);
3681 return 0;
3682 }
3683 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684}
3685
Thomas Wouters89f507f2006-12-13 04:49:30 +00003686/* End of the compiler section, beginning of the assembler section */
3687
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688/* do depth-first search of basic block graph, starting with block.
3689 post records the block indices in post-order.
3690
3691 XXX must handle implicit jumps from one block to next
3692*/
3693
Thomas Wouters89f507f2006-12-13 04:49:30 +00003694struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 PyObject *a_bytecode; /* string containing bytecode */
3696 int a_offset; /* offset into bytecode */
3697 int a_nblocks; /* number of reachable blocks */
3698 basicblock **a_postorder; /* list of blocks in dfs postorder */
3699 PyObject *a_lnotab; /* string containing lnotab */
3700 int a_lnotab_off; /* offset into lnotab */
3701 int a_lineno; /* last lineno of emitted instruction */
3702 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003703};
3704
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003705static void
3706dfs(struct compiler *c, basicblock *b, struct assembler *a)
3707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 int i;
3709 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 if (b->b_seen)
3712 return;
3713 b->b_seen = 1;
3714 if (b->b_next != NULL)
3715 dfs(c, b->b_next, a);
3716 for (i = 0; i < b->b_iused; i++) {
3717 instr = &b->b_instr[i];
3718 if (instr->i_jrel || instr->i_jabs)
3719 dfs(c, instr->i_target, a);
3720 }
3721 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722}
3723
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003724static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 int i, target_depth;
3728 struct instr *instr;
3729 if (b->b_seen || b->b_startdepth >= depth)
3730 return maxdepth;
3731 b->b_seen = 1;
3732 b->b_startdepth = depth;
3733 for (i = 0; i < b->b_iused; i++) {
3734 instr = &b->b_instr[i];
3735 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3736 if (depth > maxdepth)
3737 maxdepth = depth;
3738 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3739 if (instr->i_jrel || instr->i_jabs) {
3740 target_depth = depth;
3741 if (instr->i_opcode == FOR_ITER) {
3742 target_depth = depth-2;
3743 } else if (instr->i_opcode == SETUP_FINALLY ||
3744 instr->i_opcode == SETUP_EXCEPT) {
3745 target_depth = depth+3;
3746 if (target_depth > maxdepth)
3747 maxdepth = target_depth;
3748 }
3749 maxdepth = stackdepth_walk(c, instr->i_target,
3750 target_depth, maxdepth);
3751 if (instr->i_opcode == JUMP_ABSOLUTE ||
3752 instr->i_opcode == JUMP_FORWARD) {
3753 goto out; /* remaining code is dead */
3754 }
3755 }
3756 }
3757 if (b->b_next)
3758 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 b->b_seen = 0;
3761 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762}
3763
3764/* Find the flow path that needs the largest stack. We assume that
3765 * cycles in the flow graph have no net effect on the stack depth.
3766 */
3767static int
3768stackdepth(struct compiler *c)
3769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 basicblock *b, *entryblock;
3771 entryblock = NULL;
3772 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3773 b->b_seen = 0;
3774 b->b_startdepth = INT_MIN;
3775 entryblock = b;
3776 }
3777 if (!entryblock)
3778 return 0;
3779 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780}
3781
3782static int
3783assemble_init(struct assembler *a, int nblocks, int firstlineno)
3784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 memset(a, 0, sizeof(struct assembler));
3786 a->a_lineno = firstlineno;
3787 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3788 if (!a->a_bytecode)
3789 return 0;
3790 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3791 if (!a->a_lnotab)
3792 return 0;
3793 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3794 PyErr_NoMemory();
3795 return 0;
3796 }
3797 a->a_postorder = (basicblock **)PyObject_Malloc(
3798 sizeof(basicblock *) * nblocks);
3799 if (!a->a_postorder) {
3800 PyErr_NoMemory();
3801 return 0;
3802 }
3803 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804}
3805
3806static void
3807assemble_free(struct assembler *a)
3808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 Py_XDECREF(a->a_bytecode);
3810 Py_XDECREF(a->a_lnotab);
3811 if (a->a_postorder)
3812 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813}
3814
3815/* Return the size of a basic block in bytes. */
3816
3817static int
3818instrsize(struct instr *instr)
3819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 if (!instr->i_hasarg)
3821 return 1; /* 1 byte for the opcode*/
3822 if (instr->i_oparg > 0xffff)
3823 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3824 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825}
3826
3827static int
3828blocksize(basicblock *b)
3829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 int i;
3831 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 for (i = 0; i < b->b_iused; i++)
3834 size += instrsize(&b->b_instr[i]);
3835 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836}
3837
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003838/* Appends a pair to the end of the line number table, a_lnotab, representing
3839 the instruction's bytecode offset and line number. See
3840 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003841
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003842static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 int d_bytecode, d_lineno;
3846 int len;
3847 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 d_bytecode = a->a_offset - a->a_lineno_off;
3850 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 assert(d_bytecode >= 0);
3853 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 if(d_bytecode == 0 && d_lineno == 0)
3856 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 if (d_bytecode > 255) {
3859 int j, nbytes, ncodes = d_bytecode / 255;
3860 nbytes = a->a_lnotab_off + 2 * ncodes;
3861 len = PyBytes_GET_SIZE(a->a_lnotab);
3862 if (nbytes >= len) {
3863 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3864 len = nbytes;
3865 else if (len <= INT_MAX / 2)
3866 len *= 2;
3867 else {
3868 PyErr_NoMemory();
3869 return 0;
3870 }
3871 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3872 return 0;
3873 }
3874 lnotab = (unsigned char *)
3875 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3876 for (j = 0; j < ncodes; j++) {
3877 *lnotab++ = 255;
3878 *lnotab++ = 0;
3879 }
3880 d_bytecode -= ncodes * 255;
3881 a->a_lnotab_off += ncodes * 2;
3882 }
3883 assert(d_bytecode <= 255);
3884 if (d_lineno > 255) {
3885 int j, nbytes, ncodes = d_lineno / 255;
3886 nbytes = a->a_lnotab_off + 2 * ncodes;
3887 len = PyBytes_GET_SIZE(a->a_lnotab);
3888 if (nbytes >= len) {
3889 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3890 len = nbytes;
3891 else if (len <= INT_MAX / 2)
3892 len *= 2;
3893 else {
3894 PyErr_NoMemory();
3895 return 0;
3896 }
3897 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3898 return 0;
3899 }
3900 lnotab = (unsigned char *)
3901 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3902 *lnotab++ = d_bytecode;
3903 *lnotab++ = 255;
3904 d_bytecode = 0;
3905 for (j = 1; j < ncodes; j++) {
3906 *lnotab++ = 0;
3907 *lnotab++ = 255;
3908 }
3909 d_lineno -= ncodes * 255;
3910 a->a_lnotab_off += ncodes * 2;
3911 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 len = PyBytes_GET_SIZE(a->a_lnotab);
3914 if (a->a_lnotab_off + 2 >= len) {
3915 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3916 return 0;
3917 }
3918 lnotab = (unsigned char *)
3919 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 a->a_lnotab_off += 2;
3922 if (d_bytecode) {
3923 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003924 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 }
3926 else { /* First line of a block; def stmt, etc. */
3927 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003928 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 }
3930 a->a_lineno = i->i_lineno;
3931 a->a_lineno_off = a->a_offset;
3932 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003933}
3934
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935/* assemble_emit()
3936 Extend the bytecode with a new instruction.
3937 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003938*/
3939
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003940static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003941assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 int size, arg = 0, ext = 0;
3944 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3945 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 size = instrsize(i);
3948 if (i->i_hasarg) {
3949 arg = i->i_oparg;
3950 ext = arg >> 16;
3951 }
3952 if (i->i_lineno && !assemble_lnotab(a, i))
3953 return 0;
3954 if (a->a_offset + size >= len) {
3955 if (len > PY_SSIZE_T_MAX / 2)
3956 return 0;
3957 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3958 return 0;
3959 }
3960 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3961 a->a_offset += size;
3962 if (size == 6) {
3963 assert(i->i_hasarg);
3964 *code++ = (char)EXTENDED_ARG;
3965 *code++ = ext & 0xff;
3966 *code++ = ext >> 8;
3967 arg &= 0xffff;
3968 }
3969 *code++ = i->i_opcode;
3970 if (i->i_hasarg) {
3971 assert(size == 3 || size == 6);
3972 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003973 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 }
3975 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003976}
3977
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003978static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003979assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 basicblock *b;
3982 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3983 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 /* Compute the size of each block and fixup jump args.
3986 Replace block pointer with position in bytecode. */
3987 do {
3988 totsize = 0;
3989 for (i = a->a_nblocks - 1; i >= 0; i--) {
3990 b = a->a_postorder[i];
3991 bsize = blocksize(b);
3992 b->b_offset = totsize;
3993 totsize += bsize;
3994 }
3995 last_extended_arg_count = extended_arg_count;
3996 extended_arg_count = 0;
3997 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3998 bsize = b->b_offset;
3999 for (i = 0; i < b->b_iused; i++) {
4000 struct instr *instr = &b->b_instr[i];
4001 /* Relative jumps are computed relative to
4002 the instruction pointer after fetching
4003 the jump instruction.
4004 */
4005 bsize += instrsize(instr);
4006 if (instr->i_jabs)
4007 instr->i_oparg = instr->i_target->b_offset;
4008 else if (instr->i_jrel) {
4009 int delta = instr->i_target->b_offset - bsize;
4010 instr->i_oparg = delta;
4011 }
4012 else
4013 continue;
4014 if (instr->i_oparg > 0xffff)
4015 extended_arg_count++;
4016 }
4017 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 /* XXX: This is an awful hack that could hurt performance, but
4020 on the bright side it should work until we come up
4021 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 The issue is that in the first loop blocksize() is called
4024 which calls instrsize() which requires i_oparg be set
4025 appropriately. There is a bootstrap problem because
4026 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 So we loop until we stop seeing new EXTENDED_ARGs.
4029 The only EXTENDED_ARGs that could be popping up are
4030 ones in jump instructions. So this should converge
4031 fairly quickly.
4032 */
4033 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004034}
4035
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004036static PyObject *
4037dict_keys_inorder(PyObject *dict, int offset)
4038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 PyObject *tuple, *k, *v;
4040 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 tuple = PyTuple_New(size);
4043 if (tuple == NULL)
4044 return NULL;
4045 while (PyDict_Next(dict, &pos, &k, &v)) {
4046 i = PyLong_AS_LONG(v);
4047 /* The keys of the dictionary are tuples. (see compiler_add_o)
4048 The object we want is always first, though. */
4049 k = PyTuple_GET_ITEM(k, 0);
4050 Py_INCREF(k);
4051 assert((i - offset) < size);
4052 assert((i - offset) >= 0);
4053 PyTuple_SET_ITEM(tuple, i - offset, k);
4054 }
4055 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004056}
4057
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004058static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004059compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 PySTEntryObject *ste = c->u->u_ste;
4062 int flags = 0, n;
4063 if (ste->ste_type != ModuleBlock)
4064 flags |= CO_NEWLOCALS;
4065 if (ste->ste_type == FunctionBlock) {
4066 if (!ste->ste_unoptimized)
4067 flags |= CO_OPTIMIZED;
4068 if (ste->ste_nested)
4069 flags |= CO_NESTED;
4070 if (ste->ste_generator)
4071 flags |= CO_GENERATOR;
4072 if (ste->ste_varargs)
4073 flags |= CO_VARARGS;
4074 if (ste->ste_varkeywords)
4075 flags |= CO_VARKEYWORDS;
4076 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 /* (Only) inherit compilerflags in PyCF_MASK */
4079 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 n = PyDict_Size(c->u->u_freevars);
4082 if (n < 0)
4083 return -1;
4084 if (n == 0) {
4085 n = PyDict_Size(c->u->u_cellvars);
4086 if (n < 0)
4087 return -1;
4088 if (n == 0) {
4089 flags |= CO_NOFREE;
4090 }
4091 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004094}
4095
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096static PyCodeObject *
4097makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 PyObject *tmp;
4100 PyCodeObject *co = NULL;
4101 PyObject *consts = NULL;
4102 PyObject *names = NULL;
4103 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 PyObject *name = NULL;
4105 PyObject *freevars = NULL;
4106 PyObject *cellvars = NULL;
4107 PyObject *bytecode = NULL;
4108 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 tmp = dict_keys_inorder(c->u->u_consts, 0);
4111 if (!tmp)
4112 goto error;
4113 consts = PySequence_List(tmp); /* optimize_code requires a list */
4114 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 names = dict_keys_inorder(c->u->u_names, 0);
4117 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4118 if (!consts || !names || !varnames)
4119 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4122 if (!cellvars)
4123 goto error;
4124 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4125 if (!freevars)
4126 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 nlocals = PyDict_Size(c->u->u_varnames);
4128 flags = compute_code_flags(c);
4129 if (flags < 0)
4130 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4133 if (!bytecode)
4134 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4137 if (!tmp)
4138 goto error;
4139 Py_DECREF(consts);
4140 consts = tmp;
4141
4142 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4143 nlocals, stackdepth(c), flags,
4144 bytecode, consts, names, varnames,
4145 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004146 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 c->u->u_firstlineno,
4148 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004149 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 Py_XDECREF(consts);
4151 Py_XDECREF(names);
4152 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 Py_XDECREF(name);
4154 Py_XDECREF(freevars);
4155 Py_XDECREF(cellvars);
4156 Py_XDECREF(bytecode);
4157 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004158}
4159
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004160
4161/* For debugging purposes only */
4162#if 0
4163static void
4164dump_instr(const struct instr *i)
4165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 const char *jrel = i->i_jrel ? "jrel " : "";
4167 const char *jabs = i->i_jabs ? "jabs " : "";
4168 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 *arg = '\0';
4171 if (i->i_hasarg)
4172 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4175 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004176}
4177
4178static void
4179dump_basicblock(const basicblock *b)
4180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 const char *seen = b->b_seen ? "seen " : "";
4182 const char *b_return = b->b_return ? "return " : "";
4183 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4184 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4185 if (b->b_instr) {
4186 int i;
4187 for (i = 0; i < b->b_iused; i++) {
4188 fprintf(stderr, " [%02d] ", i);
4189 dump_instr(b->b_instr + i);
4190 }
4191 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004192}
4193#endif
4194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195static PyCodeObject *
4196assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 basicblock *b, *entryblock;
4199 struct assembler a;
4200 int i, j, nblocks;
4201 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 /* Make sure every block that falls off the end returns None.
4204 XXX NEXT_BLOCK() isn't quite right, because if the last
4205 block ends with a jump or return b_next shouldn't set.
4206 */
4207 if (!c->u->u_curblock->b_return) {
4208 NEXT_BLOCK(c);
4209 if (addNone)
4210 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4211 ADDOP(c, RETURN_VALUE);
4212 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 nblocks = 0;
4215 entryblock = NULL;
4216 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4217 nblocks++;
4218 entryblock = b;
4219 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 /* Set firstlineno if it wasn't explicitly set. */
4222 if (!c->u->u_firstlineno) {
4223 if (entryblock && entryblock->b_instr)
4224 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4225 else
4226 c->u->u_firstlineno = 1;
4227 }
4228 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4229 goto error;
4230 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 /* Can't modify the bytecode after computing jump offsets. */
4233 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 /* Emit code in reverse postorder from dfs. */
4236 for (i = a.a_nblocks - 1; i >= 0; i--) {
4237 b = a.a_postorder[i];
4238 for (j = 0; j < b->b_iused; j++)
4239 if (!assemble_emit(&a, &b->b_instr[j]))
4240 goto error;
4241 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4244 goto error;
4245 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4246 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004249 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 assemble_free(&a);
4251 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004252}
Georg Brandl8334fd92010-12-04 10:26:46 +00004253
4254#undef PyAST_Compile
4255PyAPI_FUNC(PyCodeObject *)
4256PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4257 PyArena *arena)
4258{
4259 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4260}
4261
4262