blob: 842ed50bec4cbc62f6143cfb16aeeeeaa808634d [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;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001504 if (args->vararg && args->vararg->annotation &&
1505 compiler_visit_argannotation(c, args->vararg->arg,
1506 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 goto error;
1508 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1509 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001510 if (args->kwarg && args->kwarg->annotation &&
1511 compiler_visit_argannotation(c, args->kwarg->arg,
1512 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 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;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001571 if (args->defaults)
1572 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (args->kwonlyargs) {
1574 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1575 args->kw_defaults);
1576 if (res < 0)
1577 return 0;
1578 kw_default_count = res;
1579 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 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
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001800 if (args->defaults)
1801 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (args->kwonlyargs) {
1803 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1804 args->kw_defaults);
1805 if (res < 0) return 0;
1806 kw_default_count = res;
1807 }
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
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002641 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2642 PyUnicode_CompareWithASCIIString(name, "True") &&
2643 PyUnicode_CompareWithASCIIString(name, "False"));
2644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 op = 0;
2646 optype = OP_NAME;
2647 scope = PyST_GetScope(c->u->u_ste, mangled);
2648 switch (scope) {
2649 case FREE:
2650 dict = c->u->u_freevars;
2651 optype = OP_DEREF;
2652 break;
2653 case CELL:
2654 dict = c->u->u_cellvars;
2655 optype = OP_DEREF;
2656 break;
2657 case LOCAL:
2658 if (c->u->u_ste->ste_type == FunctionBlock)
2659 optype = OP_FAST;
2660 break;
2661 case GLOBAL_IMPLICIT:
2662 if (c->u->u_ste->ste_type == FunctionBlock &&
2663 !c->u->u_ste->ste_unoptimized)
2664 optype = OP_GLOBAL;
2665 break;
2666 case GLOBAL_EXPLICIT:
2667 optype = OP_GLOBAL;
2668 break;
2669 default:
2670 /* scope can be 0 */
2671 break;
2672 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002675 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 switch (optype) {
2678 case OP_DEREF:
2679 switch (ctx) {
2680 case Load: op = LOAD_DEREF; break;
2681 case Store: op = STORE_DEREF; break;
2682 case AugLoad:
2683 case AugStore:
2684 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002685 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 case Param:
2687 default:
2688 PyErr_SetString(PyExc_SystemError,
2689 "param invalid for deref variable");
2690 return 0;
2691 }
2692 break;
2693 case OP_FAST:
2694 switch (ctx) {
2695 case Load: op = LOAD_FAST; break;
2696 case Store: op = STORE_FAST; break;
2697 case Del: op = DELETE_FAST; break;
2698 case AugLoad:
2699 case AugStore:
2700 break;
2701 case Param:
2702 default:
2703 PyErr_SetString(PyExc_SystemError,
2704 "param invalid for local variable");
2705 return 0;
2706 }
2707 ADDOP_O(c, op, mangled, varnames);
2708 Py_DECREF(mangled);
2709 return 1;
2710 case OP_GLOBAL:
2711 switch (ctx) {
2712 case Load: op = LOAD_GLOBAL; break;
2713 case Store: op = STORE_GLOBAL; break;
2714 case Del: op = DELETE_GLOBAL; break;
2715 case AugLoad:
2716 case AugStore:
2717 break;
2718 case Param:
2719 default:
2720 PyErr_SetString(PyExc_SystemError,
2721 "param invalid for global variable");
2722 return 0;
2723 }
2724 break;
2725 case OP_NAME:
2726 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002727 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 case Store: op = STORE_NAME; break;
2729 case Del: op = DELETE_NAME; break;
2730 case AugLoad:
2731 case AugStore:
2732 break;
2733 case Param:
2734 default:
2735 PyErr_SetString(PyExc_SystemError,
2736 "param invalid for name variable");
2737 return 0;
2738 }
2739 break;
2740 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 assert(op);
2743 arg = compiler_add_o(c, dict, mangled);
2744 Py_DECREF(mangled);
2745 if (arg < 0)
2746 return 0;
2747 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002748}
2749
2750static int
2751compiler_boolop(struct compiler *c, expr_ty e)
2752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 basicblock *end;
2754 int jumpi, i, n;
2755 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 assert(e->kind == BoolOp_kind);
2758 if (e->v.BoolOp.op == And)
2759 jumpi = JUMP_IF_FALSE_OR_POP;
2760 else
2761 jumpi = JUMP_IF_TRUE_OR_POP;
2762 end = compiler_new_block(c);
2763 if (end == NULL)
2764 return 0;
2765 s = e->v.BoolOp.values;
2766 n = asdl_seq_LEN(s) - 1;
2767 assert(n >= 0);
2768 for (i = 0; i < n; ++i) {
2769 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2770 ADDOP_JABS(c, jumpi, end);
2771 }
2772 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2773 compiler_use_next_block(c, end);
2774 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775}
2776
2777static int
2778compiler_list(struct compiler *c, expr_ty e)
2779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 int n = asdl_seq_LEN(e->v.List.elts);
2781 if (e->v.List.ctx == Store) {
2782 int i, seen_star = 0;
2783 for (i = 0; i < n; i++) {
2784 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2785 if (elt->kind == Starred_kind && !seen_star) {
2786 if ((i >= (1 << 8)) ||
2787 (n-i-1 >= (INT_MAX >> 8)))
2788 return compiler_error(c,
2789 "too many expressions in "
2790 "star-unpacking assignment");
2791 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2792 seen_star = 1;
2793 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2794 } else if (elt->kind == Starred_kind) {
2795 return compiler_error(c,
2796 "two starred expressions in assignment");
2797 }
2798 }
2799 if (!seen_star) {
2800 ADDOP_I(c, UNPACK_SEQUENCE, n);
2801 }
2802 }
2803 VISIT_SEQ(c, expr, e->v.List.elts);
2804 if (e->v.List.ctx == Load) {
2805 ADDOP_I(c, BUILD_LIST, n);
2806 }
2807 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002808}
2809
2810static int
2811compiler_tuple(struct compiler *c, expr_ty e)
2812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 int n = asdl_seq_LEN(e->v.Tuple.elts);
2814 if (e->v.Tuple.ctx == Store) {
2815 int i, seen_star = 0;
2816 for (i = 0; i < n; i++) {
2817 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2818 if (elt->kind == Starred_kind && !seen_star) {
2819 if ((i >= (1 << 8)) ||
2820 (n-i-1 >= (INT_MAX >> 8)))
2821 return compiler_error(c,
2822 "too many expressions in "
2823 "star-unpacking assignment");
2824 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2825 seen_star = 1;
2826 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2827 } else if (elt->kind == Starred_kind) {
2828 return compiler_error(c,
2829 "two starred expressions in assignment");
2830 }
2831 }
2832 if (!seen_star) {
2833 ADDOP_I(c, UNPACK_SEQUENCE, n);
2834 }
2835 }
2836 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2837 if (e->v.Tuple.ctx == Load) {
2838 ADDOP_I(c, BUILD_TUPLE, n);
2839 }
2840 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841}
2842
2843static int
2844compiler_compare(struct compiler *c, expr_ty e)
2845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 int i, n;
2847 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2850 VISIT(c, expr, e->v.Compare.left);
2851 n = asdl_seq_LEN(e->v.Compare.ops);
2852 assert(n > 0);
2853 if (n > 1) {
2854 cleanup = compiler_new_block(c);
2855 if (cleanup == NULL)
2856 return 0;
2857 VISIT(c, expr,
2858 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2859 }
2860 for (i = 1; i < n; i++) {
2861 ADDOP(c, DUP_TOP);
2862 ADDOP(c, ROT_THREE);
2863 ADDOP_I(c, COMPARE_OP,
2864 cmpop((cmpop_ty)(asdl_seq_GET(
2865 e->v.Compare.ops, i - 1))));
2866 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2867 NEXT_BLOCK(c);
2868 if (i < (n - 1))
2869 VISIT(c, expr,
2870 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2871 }
2872 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2873 ADDOP_I(c, COMPARE_OP,
2874 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2875 if (n > 1) {
2876 basicblock *end = compiler_new_block(c);
2877 if (end == NULL)
2878 return 0;
2879 ADDOP_JREL(c, JUMP_FORWARD, end);
2880 compiler_use_next_block(c, cleanup);
2881 ADDOP(c, ROT_TWO);
2882 ADDOP(c, POP_TOP);
2883 compiler_use_next_block(c, end);
2884 }
2885 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886}
2887
2888static int
2889compiler_call(struct compiler *c, expr_ty e)
2890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 VISIT(c, expr, e->v.Call.func);
2892 return compiler_call_helper(c, 0,
2893 e->v.Call.args,
2894 e->v.Call.keywords,
2895 e->v.Call.starargs,
2896 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002897}
2898
2899/* shared code between compiler_call and compiler_class */
2900static int
2901compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 int n, /* Args already pushed */
2903 asdl_seq *args,
2904 asdl_seq *keywords,
2905 expr_ty starargs,
2906 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 n += asdl_seq_LEN(args);
2911 VISIT_SEQ(c, expr, args);
2912 if (keywords) {
2913 VISIT_SEQ(c, keyword, keywords);
2914 n |= asdl_seq_LEN(keywords) << 8;
2915 }
2916 if (starargs) {
2917 VISIT(c, expr, starargs);
2918 code |= 1;
2919 }
2920 if (kwargs) {
2921 VISIT(c, expr, kwargs);
2922 code |= 2;
2923 }
2924 switch (code) {
2925 case 0:
2926 ADDOP_I(c, CALL_FUNCTION, n);
2927 break;
2928 case 1:
2929 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2930 break;
2931 case 2:
2932 ADDOP_I(c, CALL_FUNCTION_KW, n);
2933 break;
2934 case 3:
2935 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2936 break;
2937 }
2938 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939}
2940
Nick Coghlan650f0d02007-04-15 12:05:43 +00002941
2942/* List and set comprehensions and generator expressions work by creating a
2943 nested function to perform the actual iteration. This means that the
2944 iteration variables don't leak into the current scope.
2945 The defined function is called immediately following its definition, with the
2946 result of that call being the result of the expression.
2947 The LC/SC version returns the populated container, while the GE version is
2948 flagged in symtable.c as a generator, so it returns the generator object
2949 when the function is called.
2950 This code *knows* that the loop cannot contain break, continue, or return,
2951 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2952
2953 Possible cleanups:
2954 - iterate over the generator sequence instead of using recursion
2955*/
2956
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958compiler_comprehension_generator(struct compiler *c,
2959 asdl_seq *generators, int gen_index,
2960 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 /* generate code for the iterator, then each of the ifs,
2963 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 comprehension_ty gen;
2966 basicblock *start, *anchor, *skip, *if_cleanup;
2967 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 start = compiler_new_block(c);
2970 skip = compiler_new_block(c);
2971 if_cleanup = compiler_new_block(c);
2972 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2975 anchor == NULL)
2976 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 if (gen_index == 0) {
2981 /* Receive outermost iter as an implicit argument */
2982 c->u->u_argcount = 1;
2983 ADDOP_I(c, LOAD_FAST, 0);
2984 }
2985 else {
2986 /* Sub-iter - calculate on the fly */
2987 VISIT(c, expr, gen->iter);
2988 ADDOP(c, GET_ITER);
2989 }
2990 compiler_use_next_block(c, start);
2991 ADDOP_JREL(c, FOR_ITER, anchor);
2992 NEXT_BLOCK(c);
2993 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 /* XXX this needs to be cleaned up...a lot! */
2996 n = asdl_seq_LEN(gen->ifs);
2997 for (i = 0; i < n; i++) {
2998 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2999 VISIT(c, expr, e);
3000 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3001 NEXT_BLOCK(c);
3002 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 if (++gen_index < asdl_seq_LEN(generators))
3005 if (!compiler_comprehension_generator(c,
3006 generators, gen_index,
3007 elt, val, type))
3008 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 /* only append after the last for generator */
3011 if (gen_index >= asdl_seq_LEN(generators)) {
3012 /* comprehension specific code */
3013 switch (type) {
3014 case COMP_GENEXP:
3015 VISIT(c, expr, elt);
3016 ADDOP(c, YIELD_VALUE);
3017 ADDOP(c, POP_TOP);
3018 break;
3019 case COMP_LISTCOMP:
3020 VISIT(c, expr, elt);
3021 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3022 break;
3023 case COMP_SETCOMP:
3024 VISIT(c, expr, elt);
3025 ADDOP_I(c, SET_ADD, gen_index + 1);
3026 break;
3027 case COMP_DICTCOMP:
3028 /* With 'd[k] = v', v is evaluated before k, so we do
3029 the same. */
3030 VISIT(c, expr, val);
3031 VISIT(c, expr, elt);
3032 ADDOP_I(c, MAP_ADD, gen_index + 1);
3033 break;
3034 default:
3035 return 0;
3036 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 compiler_use_next_block(c, skip);
3039 }
3040 compiler_use_next_block(c, if_cleanup);
3041 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3042 compiler_use_next_block(c, anchor);
3043
3044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045}
3046
3047static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003048compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 PyCodeObject *co = NULL;
3052 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003053 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 outermost_iter = ((comprehension_ty)
3056 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003057
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003058 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3059 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 if (type != COMP_GENEXP) {
3063 int op;
3064 switch (type) {
3065 case COMP_LISTCOMP:
3066 op = BUILD_LIST;
3067 break;
3068 case COMP_SETCOMP:
3069 op = BUILD_SET;
3070 break;
3071 case COMP_DICTCOMP:
3072 op = BUILD_MAP;
3073 break;
3074 default:
3075 PyErr_Format(PyExc_SystemError,
3076 "unknown comprehension type %d", type);
3077 goto error_in_scope;
3078 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 ADDOP_I(c, op, 0);
3081 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 if (!compiler_comprehension_generator(c, generators, 0, elt,
3084 val, type))
3085 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 if (type != COMP_GENEXP) {
3088 ADDOP(c, RETURN_VALUE);
3089 }
3090
3091 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003092 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003094 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 goto error;
3096
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003097 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003099 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 Py_DECREF(co);
3101
3102 VISIT(c, expr, outermost_iter);
3103 ADDOP(c, GET_ITER);
3104 ADDOP_I(c, CALL_FUNCTION, 1);
3105 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003106error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003108error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003109 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 Py_XDECREF(co);
3111 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003112}
3113
3114static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115compiler_genexp(struct compiler *c, expr_ty e)
3116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 static identifier name;
3118 if (!name) {
3119 name = PyUnicode_FromString("<genexpr>");
3120 if (!name)
3121 return 0;
3122 }
3123 assert(e->kind == GeneratorExp_kind);
3124 return compiler_comprehension(c, e, COMP_GENEXP, name,
3125 e->v.GeneratorExp.generators,
3126 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127}
3128
3129static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003130compiler_listcomp(struct compiler *c, expr_ty e)
3131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 static identifier name;
3133 if (!name) {
3134 name = PyUnicode_FromString("<listcomp>");
3135 if (!name)
3136 return 0;
3137 }
3138 assert(e->kind == ListComp_kind);
3139 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3140 e->v.ListComp.generators,
3141 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003142}
3143
3144static int
3145compiler_setcomp(struct compiler *c, expr_ty e)
3146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 static identifier name;
3148 if (!name) {
3149 name = PyUnicode_FromString("<setcomp>");
3150 if (!name)
3151 return 0;
3152 }
3153 assert(e->kind == SetComp_kind);
3154 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3155 e->v.SetComp.generators,
3156 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003157}
3158
3159
3160static int
3161compiler_dictcomp(struct compiler *c, expr_ty e)
3162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 static identifier name;
3164 if (!name) {
3165 name = PyUnicode_FromString("<dictcomp>");
3166 if (!name)
3167 return 0;
3168 }
3169 assert(e->kind == DictComp_kind);
3170 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3171 e->v.DictComp.generators,
3172 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003173}
3174
3175
3176static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177compiler_visit_keyword(struct compiler *c, keyword_ty k)
3178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3180 VISIT(c, expr, k->value);
3181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182}
3183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185 whether they are true or false.
3186
3187 Return values: 1 for true, 0 for false, -1 for non-constant.
3188 */
3189
3190static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003191expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 char *id;
3194 switch (e->kind) {
3195 case Ellipsis_kind:
3196 return 1;
3197 case Num_kind:
3198 return PyObject_IsTrue(e->v.Num.n);
3199 case Str_kind:
3200 return PyObject_IsTrue(e->v.Str.s);
3201 case Name_kind:
3202 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003203 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003204 if (id && strcmp(id, "__debug__") == 0)
3205 return !c->c_optimize;
3206 return -1;
3207 case NameConstant_kind: {
3208 PyObject *o = e->v.NameConstant.value;
3209 if (o == Py_None)
3210 return 0;
3211 else if (o == Py_True)
3212 return 1;
3213 else if (o == Py_False)
3214 return 0;
3215 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 default:
3217 return -1;
3218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219}
3220
Guido van Rossumc2e20742006-02-27 22:32:47 +00003221/*
3222 Implements the with statement from PEP 343.
3223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003225
3226 with EXPR as VAR:
3227 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228
Guido van Rossumc2e20742006-02-27 22:32:47 +00003229 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230
Thomas Wouters477c8d52006-05-27 19:21:47 +00003231 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003232 exit = context.__exit__ # not calling it
3233 value = context.__enter__()
3234 try:
3235 VAR = value # if VAR present in the syntax
3236 BLOCK
3237 finally:
3238 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003240 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003242 exit(*exc)
3243 */
3244static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003245compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003246{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003247 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003248 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003249
3250 assert(s->kind == With_kind);
3251
Guido van Rossumc2e20742006-02-27 22:32:47 +00003252 block = compiler_new_block(c);
3253 finally = compiler_new_block(c);
3254 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003255 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003256
Thomas Wouters477c8d52006-05-27 19:21:47 +00003257 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003258 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003259 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003260
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003261 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003262 compiler_use_next_block(c, block);
3263 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003264 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003265 }
3266
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003267 if (item->optional_vars) {
3268 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003269 }
3270 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003272 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003273 }
3274
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003275 pos++;
3276 if (pos == asdl_seq_LEN(s->v.With.items))
3277 /* BLOCK code */
3278 VISIT_SEQ(c, stmt, s->v.With.body)
3279 else if (!compiler_with(c, s, pos))
3280 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003281
3282 /* End of try block; start the finally block */
3283 ADDOP(c, POP_BLOCK);
3284 compiler_pop_fblock(c, FINALLY_TRY, block);
3285
3286 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3287 compiler_use_next_block(c, finally);
3288 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003289 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003290
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003291 /* Finally block starts; context.__exit__ is on the stack under
3292 the exception or return information. Just issue our magic
3293 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003294 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003295
3296 /* Finally block ends. */
3297 ADDOP(c, END_FINALLY);
3298 compiler_pop_fblock(c, FINALLY_END, finally);
3299 return 1;
3300}
3301
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302static int
3303compiler_visit_expr(struct compiler *c, expr_ty e)
3304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 /* If expr e has a different line number than the last expr/stmt,
3308 set a new line number for the next instruction.
3309 */
3310 if (e->lineno > c->u->u_lineno) {
3311 c->u->u_lineno = e->lineno;
3312 c->u->u_lineno_set = 0;
3313 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003314 /* Updating the column offset is always harmless. */
3315 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 switch (e->kind) {
3317 case BoolOp_kind:
3318 return compiler_boolop(c, e);
3319 case BinOp_kind:
3320 VISIT(c, expr, e->v.BinOp.left);
3321 VISIT(c, expr, e->v.BinOp.right);
3322 ADDOP(c, binop(c, e->v.BinOp.op));
3323 break;
3324 case UnaryOp_kind:
3325 VISIT(c, expr, e->v.UnaryOp.operand);
3326 ADDOP(c, unaryop(e->v.UnaryOp.op));
3327 break;
3328 case Lambda_kind:
3329 return compiler_lambda(c, e);
3330 case IfExp_kind:
3331 return compiler_ifexp(c, e);
3332 case Dict_kind:
3333 n = asdl_seq_LEN(e->v.Dict.values);
3334 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3335 for (i = 0; i < n; i++) {
3336 VISIT(c, expr,
3337 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3338 VISIT(c, expr,
3339 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3340 ADDOP(c, STORE_MAP);
3341 }
3342 break;
3343 case Set_kind:
3344 n = asdl_seq_LEN(e->v.Set.elts);
3345 VISIT_SEQ(c, expr, e->v.Set.elts);
3346 ADDOP_I(c, BUILD_SET, n);
3347 break;
3348 case GeneratorExp_kind:
3349 return compiler_genexp(c, e);
3350 case ListComp_kind:
3351 return compiler_listcomp(c, e);
3352 case SetComp_kind:
3353 return compiler_setcomp(c, e);
3354 case DictComp_kind:
3355 return compiler_dictcomp(c, e);
3356 case Yield_kind:
3357 if (c->u->u_ste->ste_type != FunctionBlock)
3358 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003359 if (e->v.Yield.value) {
3360 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 }
3362 else {
3363 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3364 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003365 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003367 case YieldFrom_kind:
3368 if (c->u->u_ste->ste_type != FunctionBlock)
3369 return compiler_error(c, "'yield' outside function");
3370 VISIT(c, expr, e->v.YieldFrom.value);
3371 ADDOP(c, GET_ITER);
3372 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3373 ADDOP(c, YIELD_FROM);
3374 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 case Compare_kind:
3376 return compiler_compare(c, e);
3377 case Call_kind:
3378 return compiler_call(c, e);
3379 case Num_kind:
3380 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3381 break;
3382 case Str_kind:
3383 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3384 break;
3385 case Bytes_kind:
3386 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3387 break;
3388 case Ellipsis_kind:
3389 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3390 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003391 case NameConstant_kind:
3392 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3393 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 /* The following exprs can be assignment targets. */
3395 case Attribute_kind:
3396 if (e->v.Attribute.ctx != AugStore)
3397 VISIT(c, expr, e->v.Attribute.value);
3398 switch (e->v.Attribute.ctx) {
3399 case AugLoad:
3400 ADDOP(c, DUP_TOP);
3401 /* Fall through to load */
3402 case Load:
3403 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3404 break;
3405 case AugStore:
3406 ADDOP(c, ROT_TWO);
3407 /* Fall through to save */
3408 case Store:
3409 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3410 break;
3411 case Del:
3412 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3413 break;
3414 case Param:
3415 default:
3416 PyErr_SetString(PyExc_SystemError,
3417 "param invalid in attribute expression");
3418 return 0;
3419 }
3420 break;
3421 case Subscript_kind:
3422 switch (e->v.Subscript.ctx) {
3423 case AugLoad:
3424 VISIT(c, expr, e->v.Subscript.value);
3425 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3426 break;
3427 case Load:
3428 VISIT(c, expr, e->v.Subscript.value);
3429 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3430 break;
3431 case AugStore:
3432 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3433 break;
3434 case Store:
3435 VISIT(c, expr, e->v.Subscript.value);
3436 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3437 break;
3438 case Del:
3439 VISIT(c, expr, e->v.Subscript.value);
3440 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3441 break;
3442 case Param:
3443 default:
3444 PyErr_SetString(PyExc_SystemError,
3445 "param invalid in subscript expression");
3446 return 0;
3447 }
3448 break;
3449 case Starred_kind:
3450 switch (e->v.Starred.ctx) {
3451 case Store:
3452 /* In all legitimate cases, the Starred node was already replaced
3453 * by compiler_list/compiler_tuple. XXX: is that okay? */
3454 return compiler_error(c,
3455 "starred assignment target must be in a list or tuple");
3456 default:
3457 return compiler_error(c,
3458 "can use starred expression only as assignment target");
3459 }
3460 break;
3461 case Name_kind:
3462 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3463 /* child nodes of List and Tuple will have expr_context set */
3464 case List_kind:
3465 return compiler_list(c, e);
3466 case Tuple_kind:
3467 return compiler_tuple(c, e);
3468 }
3469 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003470}
3471
3472static int
3473compiler_augassign(struct compiler *c, stmt_ty s)
3474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 expr_ty e = s->v.AugAssign.target;
3476 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 switch (e->kind) {
3481 case Attribute_kind:
3482 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3483 AugLoad, e->lineno, e->col_offset, c->c_arena);
3484 if (auge == NULL)
3485 return 0;
3486 VISIT(c, expr, auge);
3487 VISIT(c, expr, s->v.AugAssign.value);
3488 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3489 auge->v.Attribute.ctx = AugStore;
3490 VISIT(c, expr, auge);
3491 break;
3492 case Subscript_kind:
3493 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3494 AugLoad, e->lineno, e->col_offset, c->c_arena);
3495 if (auge == NULL)
3496 return 0;
3497 VISIT(c, expr, auge);
3498 VISIT(c, expr, s->v.AugAssign.value);
3499 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3500 auge->v.Subscript.ctx = AugStore;
3501 VISIT(c, expr, auge);
3502 break;
3503 case Name_kind:
3504 if (!compiler_nameop(c, e->v.Name.id, Load))
3505 return 0;
3506 VISIT(c, expr, s->v.AugAssign.value);
3507 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3508 return compiler_nameop(c, e->v.Name.id, Store);
3509 default:
3510 PyErr_Format(PyExc_SystemError,
3511 "invalid node type (%d) for augmented assignment",
3512 e->kind);
3513 return 0;
3514 }
3515 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516}
3517
3518static int
3519compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 struct fblockinfo *f;
3522 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3523 PyErr_SetString(PyExc_SystemError,
3524 "too many statically nested blocks");
3525 return 0;
3526 }
3527 f = &c->u->u_fblock[c->u->u_nfblocks++];
3528 f->fb_type = t;
3529 f->fb_block = b;
3530 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531}
3532
3533static void
3534compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 struct compiler_unit *u = c->u;
3537 assert(u->u_nfblocks > 0);
3538 u->u_nfblocks--;
3539 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3540 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541}
3542
Thomas Wouters89f507f2006-12-13 04:49:30 +00003543static int
3544compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 int i;
3546 struct compiler_unit *u = c->u;
3547 for (i = 0; i < u->u_nfblocks; ++i) {
3548 if (u->u_fblock[i].fb_type == LOOP)
3549 return 1;
3550 }
3551 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003552}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553/* Raises a SyntaxError and returns 0.
3554 If something goes wrong, a different exception may be raised.
3555*/
3556
3557static int
3558compiler_error(struct compiler *c, const char *errstr)
3559{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003560 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3564 if (!loc) {
3565 Py_INCREF(Py_None);
3566 loc = Py_None;
3567 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003568 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003569 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 if (!u)
3571 goto exit;
3572 v = Py_BuildValue("(zO)", errstr, u);
3573 if (!v)
3574 goto exit;
3575 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 Py_DECREF(loc);
3578 Py_XDECREF(u);
3579 Py_XDECREF(v);
3580 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581}
3582
3583static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584compiler_handle_subscr(struct compiler *c, const char *kind,
3585 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 /* XXX this code is duplicated */
3590 switch (ctx) {
3591 case AugLoad: /* fall through to Load */
3592 case Load: op = BINARY_SUBSCR; break;
3593 case AugStore:/* fall through to Store */
3594 case Store: op = STORE_SUBSCR; break;
3595 case Del: op = DELETE_SUBSCR; break;
3596 case Param:
3597 PyErr_Format(PyExc_SystemError,
3598 "invalid %s kind %d in subscript\n",
3599 kind, ctx);
3600 return 0;
3601 }
3602 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003603 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 }
3605 else if (ctx == AugStore) {
3606 ADDOP(c, ROT_THREE);
3607 }
3608 ADDOP(c, op);
3609 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610}
3611
3612static int
3613compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 int n = 2;
3616 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 /* only handles the cases where BUILD_SLICE is emitted */
3619 if (s->v.Slice.lower) {
3620 VISIT(c, expr, s->v.Slice.lower);
3621 }
3622 else {
3623 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3624 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 if (s->v.Slice.upper) {
3627 VISIT(c, expr, s->v.Slice.upper);
3628 }
3629 else {
3630 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3631 }
3632
3633 if (s->v.Slice.step) {
3634 n++;
3635 VISIT(c, expr, s->v.Slice.step);
3636 }
3637 ADDOP_I(c, BUILD_SLICE, n);
3638 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639}
3640
3641static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3643 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 switch (s->kind) {
3646 case Slice_kind:
3647 return compiler_slice(c, s, ctx);
3648 case Index_kind:
3649 VISIT(c, expr, s->v.Index.value);
3650 break;
3651 case ExtSlice_kind:
3652 default:
3653 PyErr_SetString(PyExc_SystemError,
3654 "extended slice invalid in nested slice");
3655 return 0;
3656 }
3657 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658}
3659
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660static int
3661compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 char * kindname = NULL;
3664 switch (s->kind) {
3665 case Index_kind:
3666 kindname = "index";
3667 if (ctx != AugStore) {
3668 VISIT(c, expr, s->v.Index.value);
3669 }
3670 break;
3671 case Slice_kind:
3672 kindname = "slice";
3673 if (ctx != AugStore) {
3674 if (!compiler_slice(c, s, ctx))
3675 return 0;
3676 }
3677 break;
3678 case ExtSlice_kind:
3679 kindname = "extended slice";
3680 if (ctx != AugStore) {
3681 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3682 for (i = 0; i < n; i++) {
3683 slice_ty sub = (slice_ty)asdl_seq_GET(
3684 s->v.ExtSlice.dims, i);
3685 if (!compiler_visit_nested_slice(c, sub, ctx))
3686 return 0;
3687 }
3688 ADDOP_I(c, BUILD_TUPLE, n);
3689 }
3690 break;
3691 default:
3692 PyErr_Format(PyExc_SystemError,
3693 "invalid subscript kind %d", s->kind);
3694 return 0;
3695 }
3696 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003697}
3698
Thomas Wouters89f507f2006-12-13 04:49:30 +00003699/* End of the compiler section, beginning of the assembler section */
3700
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003701/* do depth-first search of basic block graph, starting with block.
3702 post records the block indices in post-order.
3703
3704 XXX must handle implicit jumps from one block to next
3705*/
3706
Thomas Wouters89f507f2006-12-13 04:49:30 +00003707struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 PyObject *a_bytecode; /* string containing bytecode */
3709 int a_offset; /* offset into bytecode */
3710 int a_nblocks; /* number of reachable blocks */
3711 basicblock **a_postorder; /* list of blocks in dfs postorder */
3712 PyObject *a_lnotab; /* string containing lnotab */
3713 int a_lnotab_off; /* offset into lnotab */
3714 int a_lineno; /* last lineno of emitted instruction */
3715 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003716};
3717
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718static void
3719dfs(struct compiler *c, basicblock *b, struct assembler *a)
3720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 int i;
3722 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 if (b->b_seen)
3725 return;
3726 b->b_seen = 1;
3727 if (b->b_next != NULL)
3728 dfs(c, b->b_next, a);
3729 for (i = 0; i < b->b_iused; i++) {
3730 instr = &b->b_instr[i];
3731 if (instr->i_jrel || instr->i_jabs)
3732 dfs(c, instr->i_target, a);
3733 }
3734 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735}
3736
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003737static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 int i, target_depth;
3741 struct instr *instr;
3742 if (b->b_seen || b->b_startdepth >= depth)
3743 return maxdepth;
3744 b->b_seen = 1;
3745 b->b_startdepth = depth;
3746 for (i = 0; i < b->b_iused; i++) {
3747 instr = &b->b_instr[i];
3748 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3749 if (depth > maxdepth)
3750 maxdepth = depth;
3751 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3752 if (instr->i_jrel || instr->i_jabs) {
3753 target_depth = depth;
3754 if (instr->i_opcode == FOR_ITER) {
3755 target_depth = depth-2;
3756 } else if (instr->i_opcode == SETUP_FINALLY ||
3757 instr->i_opcode == SETUP_EXCEPT) {
3758 target_depth = depth+3;
3759 if (target_depth > maxdepth)
3760 maxdepth = target_depth;
3761 }
3762 maxdepth = stackdepth_walk(c, instr->i_target,
3763 target_depth, maxdepth);
3764 if (instr->i_opcode == JUMP_ABSOLUTE ||
3765 instr->i_opcode == JUMP_FORWARD) {
3766 goto out; /* remaining code is dead */
3767 }
3768 }
3769 }
3770 if (b->b_next)
3771 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 b->b_seen = 0;
3774 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775}
3776
3777/* Find the flow path that needs the largest stack. We assume that
3778 * cycles in the flow graph have no net effect on the stack depth.
3779 */
3780static int
3781stackdepth(struct compiler *c)
3782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 basicblock *b, *entryblock;
3784 entryblock = NULL;
3785 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3786 b->b_seen = 0;
3787 b->b_startdepth = INT_MIN;
3788 entryblock = b;
3789 }
3790 if (!entryblock)
3791 return 0;
3792 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793}
3794
3795static int
3796assemble_init(struct assembler *a, int nblocks, int firstlineno)
3797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 memset(a, 0, sizeof(struct assembler));
3799 a->a_lineno = firstlineno;
3800 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3801 if (!a->a_bytecode)
3802 return 0;
3803 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3804 if (!a->a_lnotab)
3805 return 0;
3806 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3807 PyErr_NoMemory();
3808 return 0;
3809 }
3810 a->a_postorder = (basicblock **)PyObject_Malloc(
3811 sizeof(basicblock *) * nblocks);
3812 if (!a->a_postorder) {
3813 PyErr_NoMemory();
3814 return 0;
3815 }
3816 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817}
3818
3819static void
3820assemble_free(struct assembler *a)
3821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 Py_XDECREF(a->a_bytecode);
3823 Py_XDECREF(a->a_lnotab);
3824 if (a->a_postorder)
3825 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826}
3827
3828/* Return the size of a basic block in bytes. */
3829
3830static int
3831instrsize(struct instr *instr)
3832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 if (!instr->i_hasarg)
3834 return 1; /* 1 byte for the opcode*/
3835 if (instr->i_oparg > 0xffff)
3836 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3837 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838}
3839
3840static int
3841blocksize(basicblock *b)
3842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 int i;
3844 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 for (i = 0; i < b->b_iused; i++)
3847 size += instrsize(&b->b_instr[i]);
3848 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849}
3850
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003851/* Appends a pair to the end of the line number table, a_lnotab, representing
3852 the instruction's bytecode offset and line number. See
3853 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003854
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003855static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003856assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 int d_bytecode, d_lineno;
3859 int len;
3860 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 d_bytecode = a->a_offset - a->a_lineno_off;
3863 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 assert(d_bytecode >= 0);
3866 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 if(d_bytecode == 0 && d_lineno == 0)
3869 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if (d_bytecode > 255) {
3872 int j, nbytes, ncodes = d_bytecode / 255;
3873 nbytes = a->a_lnotab_off + 2 * ncodes;
3874 len = PyBytes_GET_SIZE(a->a_lnotab);
3875 if (nbytes >= len) {
3876 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3877 len = nbytes;
3878 else if (len <= INT_MAX / 2)
3879 len *= 2;
3880 else {
3881 PyErr_NoMemory();
3882 return 0;
3883 }
3884 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3885 return 0;
3886 }
3887 lnotab = (unsigned char *)
3888 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3889 for (j = 0; j < ncodes; j++) {
3890 *lnotab++ = 255;
3891 *lnotab++ = 0;
3892 }
3893 d_bytecode -= ncodes * 255;
3894 a->a_lnotab_off += ncodes * 2;
3895 }
3896 assert(d_bytecode <= 255);
3897 if (d_lineno > 255) {
3898 int j, nbytes, ncodes = d_lineno / 255;
3899 nbytes = a->a_lnotab_off + 2 * ncodes;
3900 len = PyBytes_GET_SIZE(a->a_lnotab);
3901 if (nbytes >= len) {
3902 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3903 len = nbytes;
3904 else if (len <= INT_MAX / 2)
3905 len *= 2;
3906 else {
3907 PyErr_NoMemory();
3908 return 0;
3909 }
3910 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3911 return 0;
3912 }
3913 lnotab = (unsigned char *)
3914 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3915 *lnotab++ = d_bytecode;
3916 *lnotab++ = 255;
3917 d_bytecode = 0;
3918 for (j = 1; j < ncodes; j++) {
3919 *lnotab++ = 0;
3920 *lnotab++ = 255;
3921 }
3922 d_lineno -= ncodes * 255;
3923 a->a_lnotab_off += ncodes * 2;
3924 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 len = PyBytes_GET_SIZE(a->a_lnotab);
3927 if (a->a_lnotab_off + 2 >= len) {
3928 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3929 return 0;
3930 }
3931 lnotab = (unsigned char *)
3932 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 a->a_lnotab_off += 2;
3935 if (d_bytecode) {
3936 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003937 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 }
3939 else { /* First line of a block; def stmt, etc. */
3940 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003941 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 }
3943 a->a_lineno = i->i_lineno;
3944 a->a_lineno_off = a->a_offset;
3945 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003946}
3947
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003948/* assemble_emit()
3949 Extend the bytecode with a new instruction.
3950 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003951*/
3952
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003953static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003954assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 int size, arg = 0, ext = 0;
3957 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3958 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 size = instrsize(i);
3961 if (i->i_hasarg) {
3962 arg = i->i_oparg;
3963 ext = arg >> 16;
3964 }
3965 if (i->i_lineno && !assemble_lnotab(a, i))
3966 return 0;
3967 if (a->a_offset + size >= len) {
3968 if (len > PY_SSIZE_T_MAX / 2)
3969 return 0;
3970 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3971 return 0;
3972 }
3973 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3974 a->a_offset += size;
3975 if (size == 6) {
3976 assert(i->i_hasarg);
3977 *code++ = (char)EXTENDED_ARG;
3978 *code++ = ext & 0xff;
3979 *code++ = ext >> 8;
3980 arg &= 0xffff;
3981 }
3982 *code++ = i->i_opcode;
3983 if (i->i_hasarg) {
3984 assert(size == 3 || size == 6);
3985 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003986 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 }
3988 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003989}
3990
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003991static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003992assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 basicblock *b;
3995 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3996 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 /* Compute the size of each block and fixup jump args.
3999 Replace block pointer with position in bytecode. */
4000 do {
4001 totsize = 0;
4002 for (i = a->a_nblocks - 1; i >= 0; i--) {
4003 b = a->a_postorder[i];
4004 bsize = blocksize(b);
4005 b->b_offset = totsize;
4006 totsize += bsize;
4007 }
4008 last_extended_arg_count = extended_arg_count;
4009 extended_arg_count = 0;
4010 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4011 bsize = b->b_offset;
4012 for (i = 0; i < b->b_iused; i++) {
4013 struct instr *instr = &b->b_instr[i];
4014 /* Relative jumps are computed relative to
4015 the instruction pointer after fetching
4016 the jump instruction.
4017 */
4018 bsize += instrsize(instr);
4019 if (instr->i_jabs)
4020 instr->i_oparg = instr->i_target->b_offset;
4021 else if (instr->i_jrel) {
4022 int delta = instr->i_target->b_offset - bsize;
4023 instr->i_oparg = delta;
4024 }
4025 else
4026 continue;
4027 if (instr->i_oparg > 0xffff)
4028 extended_arg_count++;
4029 }
4030 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 /* XXX: This is an awful hack that could hurt performance, but
4033 on the bright side it should work until we come up
4034 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 The issue is that in the first loop blocksize() is called
4037 which calls instrsize() which requires i_oparg be set
4038 appropriately. There is a bootstrap problem because
4039 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 So we loop until we stop seeing new EXTENDED_ARGs.
4042 The only EXTENDED_ARGs that could be popping up are
4043 ones in jump instructions. So this should converge
4044 fairly quickly.
4045 */
4046 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004047}
4048
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004049static PyObject *
4050dict_keys_inorder(PyObject *dict, int offset)
4051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 PyObject *tuple, *k, *v;
4053 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 tuple = PyTuple_New(size);
4056 if (tuple == NULL)
4057 return NULL;
4058 while (PyDict_Next(dict, &pos, &k, &v)) {
4059 i = PyLong_AS_LONG(v);
4060 /* The keys of the dictionary are tuples. (see compiler_add_o)
4061 The object we want is always first, though. */
4062 k = PyTuple_GET_ITEM(k, 0);
4063 Py_INCREF(k);
4064 assert((i - offset) < size);
4065 assert((i - offset) >= 0);
4066 PyTuple_SET_ITEM(tuple, i - offset, k);
4067 }
4068 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004069}
4070
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004071static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004072compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 PySTEntryObject *ste = c->u->u_ste;
4075 int flags = 0, n;
4076 if (ste->ste_type != ModuleBlock)
4077 flags |= CO_NEWLOCALS;
4078 if (ste->ste_type == FunctionBlock) {
4079 if (!ste->ste_unoptimized)
4080 flags |= CO_OPTIMIZED;
4081 if (ste->ste_nested)
4082 flags |= CO_NESTED;
4083 if (ste->ste_generator)
4084 flags |= CO_GENERATOR;
4085 if (ste->ste_varargs)
4086 flags |= CO_VARARGS;
4087 if (ste->ste_varkeywords)
4088 flags |= CO_VARKEYWORDS;
4089 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 /* (Only) inherit compilerflags in PyCF_MASK */
4092 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 n = PyDict_Size(c->u->u_freevars);
4095 if (n < 0)
4096 return -1;
4097 if (n == 0) {
4098 n = PyDict_Size(c->u->u_cellvars);
4099 if (n < 0)
4100 return -1;
4101 if (n == 0) {
4102 flags |= CO_NOFREE;
4103 }
4104 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004107}
4108
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109static PyCodeObject *
4110makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 PyObject *tmp;
4113 PyCodeObject *co = NULL;
4114 PyObject *consts = NULL;
4115 PyObject *names = NULL;
4116 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 PyObject *name = NULL;
4118 PyObject *freevars = NULL;
4119 PyObject *cellvars = NULL;
4120 PyObject *bytecode = NULL;
4121 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 tmp = dict_keys_inorder(c->u->u_consts, 0);
4124 if (!tmp)
4125 goto error;
4126 consts = PySequence_List(tmp); /* optimize_code requires a list */
4127 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 names = dict_keys_inorder(c->u->u_names, 0);
4130 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4131 if (!consts || !names || !varnames)
4132 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4135 if (!cellvars)
4136 goto error;
4137 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4138 if (!freevars)
4139 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 nlocals = PyDict_Size(c->u->u_varnames);
4141 flags = compute_code_flags(c);
4142 if (flags < 0)
4143 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4146 if (!bytecode)
4147 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4150 if (!tmp)
4151 goto error;
4152 Py_DECREF(consts);
4153 consts = tmp;
4154
4155 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4156 nlocals, stackdepth(c), flags,
4157 bytecode, consts, names, varnames,
4158 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004159 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 c->u->u_firstlineno,
4161 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 Py_XDECREF(consts);
4164 Py_XDECREF(names);
4165 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 Py_XDECREF(name);
4167 Py_XDECREF(freevars);
4168 Py_XDECREF(cellvars);
4169 Py_XDECREF(bytecode);
4170 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004171}
4172
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004173
4174/* For debugging purposes only */
4175#if 0
4176static void
4177dump_instr(const struct instr *i)
4178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 const char *jrel = i->i_jrel ? "jrel " : "";
4180 const char *jabs = i->i_jabs ? "jabs " : "";
4181 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 *arg = '\0';
4184 if (i->i_hasarg)
4185 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4188 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004189}
4190
4191static void
4192dump_basicblock(const basicblock *b)
4193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 const char *seen = b->b_seen ? "seen " : "";
4195 const char *b_return = b->b_return ? "return " : "";
4196 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4197 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4198 if (b->b_instr) {
4199 int i;
4200 for (i = 0; i < b->b_iused; i++) {
4201 fprintf(stderr, " [%02d] ", i);
4202 dump_instr(b->b_instr + i);
4203 }
4204 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004205}
4206#endif
4207
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208static PyCodeObject *
4209assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 basicblock *b, *entryblock;
4212 struct assembler a;
4213 int i, j, nblocks;
4214 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 /* Make sure every block that falls off the end returns None.
4217 XXX NEXT_BLOCK() isn't quite right, because if the last
4218 block ends with a jump or return b_next shouldn't set.
4219 */
4220 if (!c->u->u_curblock->b_return) {
4221 NEXT_BLOCK(c);
4222 if (addNone)
4223 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4224 ADDOP(c, RETURN_VALUE);
4225 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 nblocks = 0;
4228 entryblock = NULL;
4229 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4230 nblocks++;
4231 entryblock = b;
4232 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 /* Set firstlineno if it wasn't explicitly set. */
4235 if (!c->u->u_firstlineno) {
4236 if (entryblock && entryblock->b_instr)
4237 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4238 else
4239 c->u->u_firstlineno = 1;
4240 }
4241 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4242 goto error;
4243 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 /* Can't modify the bytecode after computing jump offsets. */
4246 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 /* Emit code in reverse postorder from dfs. */
4249 for (i = a.a_nblocks - 1; i >= 0; i--) {
4250 b = a.a_postorder[i];
4251 for (j = 0; j < b->b_iused; j++)
4252 if (!assemble_emit(&a, &b->b_instr[j]))
4253 goto error;
4254 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4257 goto error;
4258 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4259 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004262 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 assemble_free(&a);
4264 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004265}
Georg Brandl8334fd92010-12-04 10:26:46 +00004266
4267#undef PyAST_Compile
4268PyAPI_FUNC(PyCodeObject *)
4269PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4270 PyArena *arena)
4271{
4272 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4273}
4274
4275