blob: 1ecbae81812b133c63ea097cbabb29bbd0b91e28 [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:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -0400973 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 return 1;
975 case STORE_DEREF:
976 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000977 case DELETE_DEREF:
978 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 default:
980 fprintf(stderr, "opcode = %d\n", opcode);
981 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 }
984 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985}
986
987/* Add an opcode with no argument.
988 Returns 0 on failure, 1 on success.
989*/
990
991static int
992compiler_addop(struct compiler *c, int opcode)
993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 basicblock *b;
995 struct instr *i;
996 int off;
997 off = compiler_next_instr(c, c->u->u_curblock);
998 if (off < 0)
999 return 0;
1000 b = c->u->u_curblock;
1001 i = &b->b_instr[off];
1002 i->i_opcode = opcode;
1003 i->i_hasarg = 0;
1004 if (opcode == RETURN_VALUE)
1005 b->b_return = 1;
1006 compiler_set_lineno(c, off);
1007 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008}
1009
1010static int
1011compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 PyObject *t, *v;
1014 Py_ssize_t arg;
1015 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* necessary to make sure types aren't coerced (e.g., int and long) */
1018 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1019 if (PyFloat_Check(o)) {
1020 d = PyFloat_AS_DOUBLE(o);
1021 /* all we need is to make the tuple different in either the 0.0
1022 * or -0.0 case from all others, just to avoid the "coercion".
1023 */
1024 if (d == 0.0 && copysign(1.0, d) < 0.0)
1025 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1026 else
1027 t = PyTuple_Pack(2, o, o->ob_type);
1028 }
1029 else if (PyComplex_Check(o)) {
1030 Py_complex z;
1031 int real_negzero, imag_negzero;
1032 /* For the complex case we must make complex(x, 0.)
1033 different from complex(x, -0.) and complex(0., y)
1034 different from complex(-0., y), for any x and y.
1035 All four complex zeros must be distinguished.*/
1036 z = PyComplex_AsCComplex(o);
1037 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1038 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1039 if (real_negzero && imag_negzero) {
1040 t = PyTuple_Pack(5, o, o->ob_type,
1041 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001042 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 else if (imag_negzero) {
1044 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001045 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 else if (real_negzero) {
1047 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1048 }
1049 else {
1050 t = PyTuple_Pack(2, o, o->ob_type);
1051 }
1052 }
1053 else {
1054 t = PyTuple_Pack(2, o, o->ob_type);
1055 }
1056 if (t == NULL)
1057 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 v = PyDict_GetItem(dict, t);
1060 if (!v) {
1061 if (PyErr_Occurred())
1062 return -1;
1063 arg = PyDict_Size(dict);
1064 v = PyLong_FromLong(arg);
1065 if (!v) {
1066 Py_DECREF(t);
1067 return -1;
1068 }
1069 if (PyDict_SetItem(dict, t, v) < 0) {
1070 Py_DECREF(t);
1071 Py_DECREF(v);
1072 return -1;
1073 }
1074 Py_DECREF(v);
1075 }
1076 else
1077 arg = PyLong_AsLong(v);
1078 Py_DECREF(t);
1079 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080}
1081
1082static int
1083compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085{
1086 int arg = compiler_add_o(c, dict, o);
1087 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001088 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089 return compiler_addop_i(c, opcode, arg);
1090}
1091
1092static int
1093compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095{
1096 int arg;
1097 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1098 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001099 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001100 arg = compiler_add_o(c, dict, mangled);
1101 Py_DECREF(mangled);
1102 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001103 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104 return compiler_addop_i(c, opcode, arg);
1105}
1106
1107/* Add an opcode with an integer argument.
1108 Returns 0 on failure, 1 on success.
1109*/
1110
1111static int
1112compiler_addop_i(struct compiler *c, int opcode, int oparg)
1113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 struct instr *i;
1115 int off;
1116 off = compiler_next_instr(c, c->u->u_curblock);
1117 if (off < 0)
1118 return 0;
1119 i = &c->u->u_curblock->b_instr[off];
1120 i->i_opcode = opcode;
1121 i->i_oparg = oparg;
1122 i->i_hasarg = 1;
1123 compiler_set_lineno(c, off);
1124 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125}
1126
1127static int
1128compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 struct instr *i;
1131 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 assert(b != NULL);
1134 off = compiler_next_instr(c, c->u->u_curblock);
1135 if (off < 0)
1136 return 0;
1137 i = &c->u->u_curblock->b_instr[off];
1138 i->i_opcode = opcode;
1139 i->i_target = b;
1140 i->i_hasarg = 1;
1141 if (absolute)
1142 i->i_jabs = 1;
1143 else
1144 i->i_jrel = 1;
1145 compiler_set_lineno(c, off);
1146 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147}
1148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1150 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 it as the current block. NEXT_BLOCK() also creates an implicit jump
1152 from the current block to the new block.
1153*/
1154
Thomas Wouters89f507f2006-12-13 04:49:30 +00001155/* The returns inside these macros make it impossible to decref objects
1156 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157*/
1158
1159
1160#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (compiler_use_new_block((C)) == NULL) \
1162 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163}
1164
1165#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (compiler_next_block((C)) == NULL) \
1167 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168}
1169
1170#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (!compiler_addop((C), (OP))) \
1172 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173}
1174
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001175#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (!compiler_addop((C), (OP))) { \
1177 compiler_exit_scope(c); \
1178 return 0; \
1179 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001180}
1181
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1184 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185}
1186
1187#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1189 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001190}
1191
1192#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (!compiler_addop_i((C), (OP), (O))) \
1194 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195}
1196
1197#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (!compiler_addop_j((C), (OP), (O), 1)) \
1199 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200}
1201
1202#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (!compiler_addop_j((C), (OP), (O), 0)) \
1204 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205}
1206
1207/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1208 the ASDL name to synthesize the name of the C type and the visit function.
1209*/
1210
1211#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (!compiler_visit_ ## TYPE((C), (V))) \
1213 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214}
1215
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001216#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (!compiler_visit_ ## TYPE((C), (V))) { \
1218 compiler_exit_scope(c); \
1219 return 0; \
1220 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001221}
1222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (!compiler_visit_slice((C), (V), (CTX))) \
1225 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226}
1227
1228#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 int _i; \
1230 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1231 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1232 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1233 if (!compiler_visit_ ## TYPE((C), elt)) \
1234 return 0; \
1235 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001238#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 int _i; \
1240 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1241 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1242 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1243 if (!compiler_visit_ ## TYPE((C), elt)) { \
1244 compiler_exit_scope(c); \
1245 return 0; \
1246 } \
1247 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001248}
1249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250static int
1251compiler_isdocstring(stmt_ty s)
1252{
1253 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001254 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255 return s->v.Expr.value->kind == Str_kind;
1256}
1257
1258/* Compile a sequence of statements, checking for a docstring. */
1259
1260static int
1261compiler_body(struct compiler *c, asdl_seq *stmts)
1262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 int i = 0;
1264 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (!asdl_seq_LEN(stmts))
1267 return 1;
1268 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001269 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* don't generate docstrings if -OO */
1271 i = 1;
1272 VISIT(c, expr, st->v.Expr.value);
1273 if (!compiler_nameop(c, __doc__, Store))
1274 return 0;
1275 }
1276 for (; i < asdl_seq_LEN(stmts); i++)
1277 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1278 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
1281static PyCodeObject *
1282compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 PyCodeObject *co;
1285 int addNone = 1;
1286 static PyObject *module;
1287 if (!module) {
1288 module = PyUnicode_InternFromString("<module>");
1289 if (!module)
1290 return NULL;
1291 }
1292 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001293 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 return NULL;
1295 switch (mod->kind) {
1296 case Module_kind:
1297 if (!compiler_body(c, mod->v.Module.body)) {
1298 compiler_exit_scope(c);
1299 return 0;
1300 }
1301 break;
1302 case Interactive_kind:
1303 c->c_interactive = 1;
1304 VISIT_SEQ_IN_SCOPE(c, stmt,
1305 mod->v.Interactive.body);
1306 break;
1307 case Expression_kind:
1308 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1309 addNone = 0;
1310 break;
1311 case Suite_kind:
1312 PyErr_SetString(PyExc_SystemError,
1313 "suite should not be possible");
1314 return 0;
1315 default:
1316 PyErr_Format(PyExc_SystemError,
1317 "module kind %d should not be possible",
1318 mod->kind);
1319 return 0;
1320 }
1321 co = assemble(c, addNone);
1322 compiler_exit_scope(c);
1323 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001324}
1325
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326/* The test for LOCAL must come before the test for FREE in order to
1327 handle classes where name is both local and free. The local var is
1328 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001329*/
1330
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331static int
1332get_ref_type(struct compiler *c, PyObject *name)
1333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 int scope = PyST_GetScope(c->u->u_ste, name);
1335 if (scope == 0) {
1336 char buf[350];
1337 PyOS_snprintf(buf, sizeof(buf),
1338 "unknown scope for %.100s in %.100s(%s) in %s\n"
1339 "symbols: %s\nlocals: %s\nglobals: %s",
1340 PyBytes_AS_STRING(name),
1341 PyBytes_AS_STRING(c->u->u_name),
1342 PyObject_REPR(c->u->u_ste->ste_id),
1343 c->c_filename,
1344 PyObject_REPR(c->u->u_ste->ste_symbols),
1345 PyObject_REPR(c->u->u_varnames),
1346 PyObject_REPR(c->u->u_names)
1347 );
1348 Py_FatalError(buf);
1349 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352}
1353
1354static int
1355compiler_lookup_arg(PyObject *dict, PyObject *name)
1356{
1357 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001358 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001360 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001362 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001364 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001365 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366}
1367
1368static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001369compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001372 if (qualname == NULL)
1373 qualname = co->co_name;
1374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (free == 0) {
1376 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001377 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 ADDOP_I(c, MAKE_FUNCTION, args);
1379 return 1;
1380 }
1381 for (i = 0; i < free; ++i) {
1382 /* Bypass com_addop_varname because it will generate
1383 LOAD_DEREF but LOAD_CLOSURE is needed.
1384 */
1385 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1386 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 /* Special case: If a class contains a method with a
1389 free variable that has the same name as a method,
1390 the name will be considered free *and* local in the
1391 class. It should be handled by the closure, as
1392 well as by the normal name loookup logic.
1393 */
1394 reftype = get_ref_type(c, name);
1395 if (reftype == CELL)
1396 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1397 else /* (reftype == FREE) */
1398 arg = compiler_lookup_arg(c->u->u_freevars, name);
1399 if (arg == -1) {
1400 fprintf(stderr,
1401 "lookup %s in %s %d %d\n"
1402 "freevars of %s: %s\n",
1403 PyObject_REPR(name),
1404 PyBytes_AS_STRING(c->u->u_name),
1405 reftype, arg,
1406 _PyUnicode_AsString(co->co_name),
1407 PyObject_REPR(co->co_freevars));
1408 Py_FatalError("compiler_make_closure()");
1409 }
1410 ADDOP_I(c, LOAD_CLOSURE, arg);
1411 }
1412 ADDOP_I(c, BUILD_TUPLE, free);
1413 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001414 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 ADDOP_I(c, MAKE_CLOSURE, args);
1416 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417}
1418
1419static int
1420compiler_decorators(struct compiler *c, asdl_seq* decos)
1421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 if (!decos)
1425 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1428 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1429 }
1430 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431}
1432
1433static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001434compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 int i, default_count = 0;
1438 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1439 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1440 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1441 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001442 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1443 if (!mangled)
1444 return -1;
1445 ADDOP_O(c, LOAD_CONST, mangled, consts);
1446 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (!compiler_visit_expr(c, default_)) {
1448 return -1;
1449 }
1450 default_count++;
1451 }
1452 }
1453 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001454}
1455
1456static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001457compiler_visit_argannotation(struct compiler *c, identifier id,
1458 expr_ty annotation, PyObject *names)
1459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (annotation) {
1461 VISIT(c, expr, annotation);
1462 if (PyList_Append(names, id))
1463 return -1;
1464 }
1465 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001466}
1467
1468static int
1469compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1470 PyObject *names)
1471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 int i, error;
1473 for (i = 0; i < asdl_seq_LEN(args); i++) {
1474 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1475 error = compiler_visit_argannotation(
1476 c,
1477 arg->arg,
1478 arg->annotation,
1479 names);
1480 if (error)
1481 return error;
1482 }
1483 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001484}
1485
1486static int
1487compiler_visit_annotations(struct compiler *c, arguments_ty args,
1488 expr_ty returns)
1489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 /* Push arg annotations and a list of the argument names. Return the #
1491 of items pushed. The expressions are evaluated out-of-order wrt the
1492 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1495 */
1496 static identifier return_str;
1497 PyObject *names;
1498 int len;
1499 names = PyList_New(0);
1500 if (!names)
1501 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (compiler_visit_argannotations(c, args->args, names))
1504 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001505 if (args->vararg && args->vararg->annotation &&
1506 compiler_visit_argannotation(c, args->vararg->arg,
1507 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 goto error;
1509 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1510 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001511 if (args->kwarg && args->kwarg->annotation &&
1512 compiler_visit_argannotation(c, args->kwarg->arg,
1513 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 if (!return_str) {
1517 return_str = PyUnicode_InternFromString("return");
1518 if (!return_str)
1519 goto error;
1520 }
1521 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1522 goto error;
1523 }
1524
1525 len = PyList_GET_SIZE(names);
1526 if (len > 65534) {
1527 /* len must fit in 16 bits, and len is incremented below */
1528 PyErr_SetString(PyExc_SyntaxError,
1529 "too many annotations");
1530 goto error;
1531 }
1532 if (len) {
1533 /* convert names to a tuple and place on stack */
1534 PyObject *elt;
1535 int i;
1536 PyObject *s = PyTuple_New(len);
1537 if (!s)
1538 goto error;
1539 for (i = 0; i < len; i++) {
1540 elt = PyList_GET_ITEM(names, i);
1541 Py_INCREF(elt);
1542 PyTuple_SET_ITEM(s, i, elt);
1543 }
1544 ADDOP_O(c, LOAD_CONST, s, consts);
1545 Py_DECREF(s);
1546 len++; /* include the just-pushed tuple */
1547 }
1548 Py_DECREF(names);
1549 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001550
1551error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 Py_DECREF(names);
1553 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001554}
1555
1556static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557compiler_function(struct compiler *c, stmt_ty s)
1558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001560 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 arguments_ty args = s->v.FunctionDef.args;
1562 expr_ty returns = s->v.FunctionDef.returns;
1563 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1564 stmt_ty st;
1565 int i, n, docstring, kw_default_count = 0, arglength;
1566 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (!compiler_decorators(c, decos))
1571 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001572 if (args->defaults)
1573 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (args->kwonlyargs) {
1575 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1576 args->kw_defaults);
1577 if (res < 0)
1578 return 0;
1579 kw_default_count = res;
1580 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 num_annotations = compiler_visit_annotations(c, args, returns);
1582 if (num_annotations < 0)
1583 return 0;
1584 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001585
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001586 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1587 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 s->lineno))
1589 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1592 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001593 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 first_const = st->v.Expr.value->v.Str.s;
1595 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1596 compiler_exit_scope(c);
1597 return 0;
1598 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 c->u->u_argcount = asdl_seq_LEN(args->args);
1601 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1602 n = asdl_seq_LEN(s->v.FunctionDef.body);
1603 /* if there was a docstring, we need to skip the first statement */
1604 for (i = docstring; i < n; i++) {
1605 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1606 VISIT_IN_SCOPE(c, stmt, st);
1607 }
1608 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001609 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001611 if (qualname == NULL || co == NULL) {
1612 Py_XDECREF(qualname);
1613 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 arglength = asdl_seq_LEN(args->defaults);
1618 arglength |= kw_default_count << 8;
1619 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001620 compiler_make_closure(c, co, arglength, qualname);
1621 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 /* decorators */
1625 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1626 ADDOP_I(c, CALL_FUNCTION, 1);
1627 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001630}
1631
1632static int
1633compiler_class(struct compiler *c, stmt_ty s)
1634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 PyCodeObject *co;
1636 PyObject *str;
1637 int i;
1638 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (!compiler_decorators(c, decos))
1641 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* ultimately generate code for:
1644 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1645 where:
1646 <func> is a function/closure created from the class body;
1647 it has a single argument (__locals__) where the dict
1648 (or MutableSequence) representing the locals is passed
1649 <name> is the class name
1650 <bases> is the positional arguments and *varargs argument
1651 <keywords> is the keyword arguments and **kwds argument
1652 This borrows from compiler_call.
1653 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001656 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1657 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return 0;
1659 /* this block represents what we do in the new scope */
1660 {
1661 /* use the class name for name mangling */
1662 Py_INCREF(s->v.ClassDef.name);
1663 Py_XDECREF(c->u->u_private);
1664 c->u->u_private = s->v.ClassDef.name;
1665 /* force it to have one mandatory argument */
1666 c->u->u_argcount = 1;
1667 /* load the first argument (__locals__) ... */
1668 ADDOP_I(c, LOAD_FAST, 0);
1669 /* ... and store it into f_locals */
1670 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1671 /* load (global) __name__ ... */
1672 str = PyUnicode_InternFromString("__name__");
1673 if (!str || !compiler_nameop(c, str, Load)) {
1674 Py_XDECREF(str);
1675 compiler_exit_scope(c);
1676 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 Py_DECREF(str);
1679 /* ... and store it as __module__ */
1680 str = PyUnicode_InternFromString("__module__");
1681 if (!str || !compiler_nameop(c, str, Store)) {
1682 Py_XDECREF(str);
1683 compiler_exit_scope(c);
1684 return 0;
1685 }
1686 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001687 /* store the __qualname__ */
1688 str = compiler_scope_qualname(c);
1689 if (!str) {
1690 compiler_exit_scope(c);
1691 return 0;
1692 }
1693 ADDOP_O(c, LOAD_CONST, str, consts);
1694 Py_DECREF(str);
1695 str = PyUnicode_InternFromString("__qualname__");
1696 if (!str || !compiler_nameop(c, str, Store)) {
1697 Py_XDECREF(str);
1698 compiler_exit_scope(c);
1699 return 0;
1700 }
1701 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* compile the body proper */
1703 if (!compiler_body(c, s->v.ClassDef.body)) {
1704 compiler_exit_scope(c);
1705 return 0;
1706 }
1707 /* return the (empty) __class__ cell */
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001708 str = PyUnicode_InternFromString("__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (str == NULL) {
1710 compiler_exit_scope(c);
1711 return 0;
1712 }
1713 i = compiler_lookup_arg(c->u->u_cellvars, str);
1714 Py_DECREF(str);
1715 if (i == -1) {
1716 /* This happens when nobody references the cell */
1717 PyErr_Clear();
1718 /* Return None */
1719 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1720 }
1721 else {
1722 /* Return the cell where to store __class__ */
1723 ADDOP_I(c, LOAD_CLOSURE, i);
1724 }
1725 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1726 /* create the code object */
1727 co = assemble(c, 1);
1728 }
1729 /* leave the new scope */
1730 compiler_exit_scope(c);
1731 if (co == NULL)
1732 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 /* 2. load the 'build_class' function */
1735 ADDOP(c, LOAD_BUILD_CLASS);
1736
1737 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001738 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 Py_DECREF(co);
1740
1741 /* 4. load class name */
1742 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1743
1744 /* 5. generate the rest of the code for the call */
1745 if (!compiler_call_helper(c, 2,
1746 s->v.ClassDef.bases,
1747 s->v.ClassDef.keywords,
1748 s->v.ClassDef.starargs,
1749 s->v.ClassDef.kwargs))
1750 return 0;
1751
1752 /* 6. apply decorators */
1753 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1754 ADDOP_I(c, CALL_FUNCTION, 1);
1755 }
1756
1757 /* 7. store into <name> */
1758 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1759 return 0;
1760 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001761}
1762
1763static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001764compiler_ifexp(struct compiler *c, expr_ty e)
1765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 basicblock *end, *next;
1767
1768 assert(e->kind == IfExp_kind);
1769 end = compiler_new_block(c);
1770 if (end == NULL)
1771 return 0;
1772 next = compiler_new_block(c);
1773 if (next == NULL)
1774 return 0;
1775 VISIT(c, expr, e->v.IfExp.test);
1776 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1777 VISIT(c, expr, e->v.IfExp.body);
1778 ADDOP_JREL(c, JUMP_FORWARD, end);
1779 compiler_use_next_block(c, next);
1780 VISIT(c, expr, e->v.IfExp.orelse);
1781 compiler_use_next_block(c, end);
1782 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001783}
1784
1785static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786compiler_lambda(struct compiler *c, expr_ty e)
1787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001789 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 static identifier name;
1791 int kw_default_count = 0, arglength;
1792 arguments_ty args = e->v.Lambda.args;
1793 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 if (!name) {
1796 name = PyUnicode_InternFromString("<lambda>");
1797 if (!name)
1798 return 0;
1799 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001801 if (args->defaults)
1802 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (args->kwonlyargs) {
1804 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1805 args->kw_defaults);
1806 if (res < 0) return 0;
1807 kw_default_count = res;
1808 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001809 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1810 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 /* Make None the first constant, so the lambda can't have a
1814 docstring. */
1815 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1816 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 c->u->u_argcount = asdl_seq_LEN(args->args);
1819 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1820 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1821 if (c->u->u_ste->ste_generator) {
1822 ADDOP_IN_SCOPE(c, POP_TOP);
1823 }
1824 else {
1825 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1826 }
1827 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001828 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001830 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 arglength = asdl_seq_LEN(args->defaults);
1834 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001835 compiler_make_closure(c, co, arglength, qualname);
1836 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 Py_DECREF(co);
1838
1839 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840}
1841
1842static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001843compiler_if(struct compiler *c, stmt_ty s)
1844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 basicblock *end, *next;
1846 int constant;
1847 assert(s->kind == If_kind);
1848 end = compiler_new_block(c);
1849 if (end == NULL)
1850 return 0;
1851
Georg Brandl8334fd92010-12-04 10:26:46 +00001852 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 /* constant = 0: "if 0"
1854 * constant = 1: "if 1", "if 2", ...
1855 * constant = -1: rest */
1856 if (constant == 0) {
1857 if (s->v.If.orelse)
1858 VISIT_SEQ(c, stmt, s->v.If.orelse);
1859 } else if (constant == 1) {
1860 VISIT_SEQ(c, stmt, s->v.If.body);
1861 } else {
1862 if (s->v.If.orelse) {
1863 next = compiler_new_block(c);
1864 if (next == NULL)
1865 return 0;
1866 }
1867 else
1868 next = end;
1869 VISIT(c, expr, s->v.If.test);
1870 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1871 VISIT_SEQ(c, stmt, s->v.If.body);
1872 ADDOP_JREL(c, JUMP_FORWARD, end);
1873 if (s->v.If.orelse) {
1874 compiler_use_next_block(c, next);
1875 VISIT_SEQ(c, stmt, s->v.If.orelse);
1876 }
1877 }
1878 compiler_use_next_block(c, end);
1879 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880}
1881
1882static int
1883compiler_for(struct compiler *c, stmt_ty s)
1884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 start = compiler_new_block(c);
1888 cleanup = compiler_new_block(c);
1889 end = compiler_new_block(c);
1890 if (start == NULL || end == NULL || cleanup == NULL)
1891 return 0;
1892 ADDOP_JREL(c, SETUP_LOOP, end);
1893 if (!compiler_push_fblock(c, LOOP, start))
1894 return 0;
1895 VISIT(c, expr, s->v.For.iter);
1896 ADDOP(c, GET_ITER);
1897 compiler_use_next_block(c, start);
1898 ADDOP_JREL(c, FOR_ITER, cleanup);
1899 VISIT(c, expr, s->v.For.target);
1900 VISIT_SEQ(c, stmt, s->v.For.body);
1901 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1902 compiler_use_next_block(c, cleanup);
1903 ADDOP(c, POP_BLOCK);
1904 compiler_pop_fblock(c, LOOP, start);
1905 VISIT_SEQ(c, stmt, s->v.For.orelse);
1906 compiler_use_next_block(c, end);
1907 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908}
1909
1910static int
1911compiler_while(struct compiler *c, stmt_ty s)
1912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001914 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (constant == 0) {
1917 if (s->v.While.orelse)
1918 VISIT_SEQ(c, stmt, s->v.While.orelse);
1919 return 1;
1920 }
1921 loop = compiler_new_block(c);
1922 end = compiler_new_block(c);
1923 if (constant == -1) {
1924 anchor = compiler_new_block(c);
1925 if (anchor == NULL)
1926 return 0;
1927 }
1928 if (loop == NULL || end == NULL)
1929 return 0;
1930 if (s->v.While.orelse) {
1931 orelse = compiler_new_block(c);
1932 if (orelse == NULL)
1933 return 0;
1934 }
1935 else
1936 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 ADDOP_JREL(c, SETUP_LOOP, end);
1939 compiler_use_next_block(c, loop);
1940 if (!compiler_push_fblock(c, LOOP, loop))
1941 return 0;
1942 if (constant == -1) {
1943 VISIT(c, expr, s->v.While.test);
1944 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1945 }
1946 VISIT_SEQ(c, stmt, s->v.While.body);
1947 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* XXX should the two POP instructions be in a separate block
1950 if there is no else clause ?
1951 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (constant == -1) {
1954 compiler_use_next_block(c, anchor);
1955 ADDOP(c, POP_BLOCK);
1956 }
1957 compiler_pop_fblock(c, LOOP, loop);
1958 if (orelse != NULL) /* what if orelse is just pass? */
1959 VISIT_SEQ(c, stmt, s->v.While.orelse);
1960 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963}
1964
1965static int
1966compiler_continue(struct compiler *c)
1967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1969 static const char IN_FINALLY_ERROR_MSG[] =
1970 "'continue' not supported inside 'finally' clause";
1971 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (!c->u->u_nfblocks)
1974 return compiler_error(c, LOOP_ERROR_MSG);
1975 i = c->u->u_nfblocks - 1;
1976 switch (c->u->u_fblock[i].fb_type) {
1977 case LOOP:
1978 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1979 break;
1980 case EXCEPT:
1981 case FINALLY_TRY:
1982 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1983 /* Prevent continue anywhere under a finally
1984 even if hidden in a sub-try or except. */
1985 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1986 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1987 }
1988 if (i == -1)
1989 return compiler_error(c, LOOP_ERROR_MSG);
1990 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1991 break;
1992 case FINALLY_END:
1993 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1994 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997}
1998
1999/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000
2001 SETUP_FINALLY L
2002 <code for body>
2003 POP_BLOCK
2004 LOAD_CONST <None>
2005 L: <code for finalbody>
2006 END_FINALLY
2007
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008 The special instructions use the block stack. Each block
2009 stack entry contains the instruction that created it (here
2010 SETUP_FINALLY), the level of the value stack at the time the
2011 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 Pushes the current value stack level and the label
2015 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 Pops en entry from the block stack, and pops the value
2018 stack until its level is the same as indicated on the
2019 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 Pops a variable number of entries from the *value* stack
2022 and re-raises the exception they specify. The number of
2023 entries popped depends on the (pseudo) exception type.
2024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025 The block stack is unwound when an exception is raised:
2026 when a SETUP_FINALLY entry is found, the exception is pushed
2027 onto the value stack (and the exception condition is cleared),
2028 and the interpreter jumps to the label gotten from the block
2029 stack.
2030*/
2031
2032static int
2033compiler_try_finally(struct compiler *c, stmt_ty s)
2034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 basicblock *body, *end;
2036 body = compiler_new_block(c);
2037 end = compiler_new_block(c);
2038 if (body == NULL || end == NULL)
2039 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 ADDOP_JREL(c, SETUP_FINALLY, end);
2042 compiler_use_next_block(c, body);
2043 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2044 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002045 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2046 if (!compiler_try_except(c, s))
2047 return 0;
2048 }
2049 else {
2050 VISIT_SEQ(c, stmt, s->v.Try.body);
2051 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 ADDOP(c, POP_BLOCK);
2053 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2056 compiler_use_next_block(c, end);
2057 if (!compiler_push_fblock(c, FINALLY_END, end))
2058 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002059 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 ADDOP(c, END_FINALLY);
2061 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064}
2065
2066/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002067 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 (The contents of the value stack is shown in [], with the top
2069 at the right; 'tb' is trace-back info, 'val' the exception's
2070 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071
2072 Value stack Label Instruction Argument
2073 [] SETUP_EXCEPT L1
2074 [] <code for S>
2075 [] POP_BLOCK
2076 [] JUMP_FORWARD L0
2077
2078 [tb, val, exc] L1: DUP )
2079 [tb, val, exc, exc] <evaluate E1> )
2080 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2081 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2082 [tb, val, exc] POP
2083 [tb, val] <assign to V1> (or POP if no V1)
2084 [tb] POP
2085 [] <code for S1>
2086 JUMP_FORWARD L0
2087
2088 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 .............................etc.......................
2090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2092
2093 [] L0: <next statement>
2094
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 Of course, parts are not generated if Vi or Ei is not present.
2096*/
2097static int
2098compiler_try_except(struct compiler *c, stmt_ty s)
2099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 basicblock *body, *orelse, *except, *end;
2101 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 body = compiler_new_block(c);
2104 except = compiler_new_block(c);
2105 orelse = compiler_new_block(c);
2106 end = compiler_new_block(c);
2107 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2108 return 0;
2109 ADDOP_JREL(c, SETUP_EXCEPT, except);
2110 compiler_use_next_block(c, body);
2111 if (!compiler_push_fblock(c, EXCEPT, body))
2112 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002113 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 ADDOP(c, POP_BLOCK);
2115 compiler_pop_fblock(c, EXCEPT, body);
2116 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002117 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 compiler_use_next_block(c, except);
2119 for (i = 0; i < n; i++) {
2120 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002121 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 if (!handler->v.ExceptHandler.type && i < n-1)
2123 return compiler_error(c, "default 'except:' must be last");
2124 c->u->u_lineno_set = 0;
2125 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002126 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 except = compiler_new_block(c);
2128 if (except == NULL)
2129 return 0;
2130 if (handler->v.ExceptHandler.type) {
2131 ADDOP(c, DUP_TOP);
2132 VISIT(c, expr, handler->v.ExceptHandler.type);
2133 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2134 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2135 }
2136 ADDOP(c, POP_TOP);
2137 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002138 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002139
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002140 cleanup_end = compiler_new_block(c);
2141 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002142 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002143 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002144
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002145 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2146 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002148 /*
2149 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002150 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002151 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002152 try:
2153 # body
2154 finally:
2155 name = None
2156 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002157 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002159 /* second try: */
2160 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2161 compiler_use_next_block(c, cleanup_body);
2162 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2163 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002165 /* second # body */
2166 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2167 ADDOP(c, POP_BLOCK);
2168 ADDOP(c, POP_EXCEPT);
2169 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002171 /* finally: */
2172 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2173 compiler_use_next_block(c, cleanup_end);
2174 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2175 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002177 /* name = None */
2178 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2179 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002181 /* del name */
2182 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002184 ADDOP(c, END_FINALLY);
2185 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 }
2187 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002188 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002190 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002191 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002192 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193
Guido van Rossumb940e112007-01-10 16:19:56 +00002194 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002195 ADDOP(c, POP_TOP);
2196 compiler_use_next_block(c, cleanup_body);
2197 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2198 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002200 ADDOP(c, POP_EXCEPT);
2201 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 }
2203 ADDOP_JREL(c, JUMP_FORWARD, end);
2204 compiler_use_next_block(c, except);
2205 }
2206 ADDOP(c, END_FINALLY);
2207 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002208 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 compiler_use_next_block(c, end);
2210 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211}
2212
2213static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002214compiler_try(struct compiler *c, stmt_ty s) {
2215 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2216 return compiler_try_finally(c, s);
2217 else
2218 return compiler_try_except(c, s);
2219}
2220
2221
2222static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223compiler_import_as(struct compiler *c, identifier name, identifier asname)
2224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* The IMPORT_NAME opcode was already generated. This function
2226 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 If there is a dot in name, we need to split it and emit a
2229 LOAD_ATTR for each name.
2230 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002231 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2232 PyUnicode_GET_LENGTH(name), 1);
2233 if (dot == -2)
2234 return -1;
2235 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 Py_ssize_t pos = dot + 1;
2238 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 dot = PyUnicode_FindChar(name, '.', pos,
2241 PyUnicode_GET_LENGTH(name), 1);
2242 if (dot == -2)
2243 return -1;
2244 attr = PyUnicode_Substring(name, pos,
2245 (dot != -1) ? dot :
2246 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (!attr)
2248 return -1;
2249 ADDOP_O(c, LOAD_ATTR, attr, names);
2250 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 }
2253 }
2254 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255}
2256
2257static int
2258compiler_import(struct compiler *c, stmt_ty s)
2259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 /* The Import node stores a module name like a.b.c as a single
2261 string. This is convenient for all cases except
2262 import a.b.c as d
2263 where we need to parse that string to extract the individual
2264 module names.
2265 XXX Perhaps change the representation to make this case simpler?
2266 */
2267 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 for (i = 0; i < n; i++) {
2270 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2271 int r;
2272 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 level = PyLong_FromLong(0);
2275 if (level == NULL)
2276 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 ADDOP_O(c, LOAD_CONST, level, consts);
2279 Py_DECREF(level);
2280 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2281 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 if (alias->asname) {
2284 r = compiler_import_as(c, alias->name, alias->asname);
2285 if (!r)
2286 return r;
2287 }
2288 else {
2289 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002290 Py_ssize_t dot = PyUnicode_FindChar(
2291 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2292 if (dot != -1)
2293 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002295 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 Py_DECREF(tmp);
2297 }
2298 if (!r)
2299 return r;
2300 }
2301 }
2302 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303}
2304
2305static int
2306compiler_from_import(struct compiler *c, stmt_ty s)
2307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 PyObject *names = PyTuple_New(n);
2311 PyObject *level;
2312 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 if (!empty_string) {
2315 empty_string = PyUnicode_FromString("");
2316 if (!empty_string)
2317 return 0;
2318 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 if (!names)
2321 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 level = PyLong_FromLong(s->v.ImportFrom.level);
2324 if (!level) {
2325 Py_DECREF(names);
2326 return 0;
2327 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* build up the names */
2330 for (i = 0; i < n; i++) {
2331 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2332 Py_INCREF(alias->name);
2333 PyTuple_SET_ITEM(names, i, alias->name);
2334 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2337 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2338 Py_DECREF(level);
2339 Py_DECREF(names);
2340 return compiler_error(c, "from __future__ imports must occur "
2341 "at the beginning of the file");
2342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 ADDOP_O(c, LOAD_CONST, level, consts);
2345 Py_DECREF(level);
2346 ADDOP_O(c, LOAD_CONST, names, consts);
2347 Py_DECREF(names);
2348 if (s->v.ImportFrom.module) {
2349 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2350 }
2351 else {
2352 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2353 }
2354 for (i = 0; i < n; i++) {
2355 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2356 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002358 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 assert(n == 1);
2360 ADDOP(c, IMPORT_STAR);
2361 return 1;
2362 }
2363
2364 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2365 store_name = alias->name;
2366 if (alias->asname)
2367 store_name = alias->asname;
2368
2369 if (!compiler_nameop(c, store_name, Store)) {
2370 Py_DECREF(names);
2371 return 0;
2372 }
2373 }
2374 /* remove imported module */
2375 ADDOP(c, POP_TOP);
2376 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377}
2378
2379static int
2380compiler_assert(struct compiler *c, stmt_ty s)
2381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 static PyObject *assertion_error = NULL;
2383 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384
Georg Brandl8334fd92010-12-04 10:26:46 +00002385 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 return 1;
2387 if (assertion_error == NULL) {
2388 assertion_error = PyUnicode_InternFromString("AssertionError");
2389 if (assertion_error == NULL)
2390 return 0;
2391 }
2392 if (s->v.Assert.test->kind == Tuple_kind &&
2393 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2394 const char* msg =
2395 "assertion is always true, perhaps remove parentheses?";
2396 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2397 c->u->u_lineno, NULL, NULL) == -1)
2398 return 0;
2399 }
2400 VISIT(c, expr, s->v.Assert.test);
2401 end = compiler_new_block(c);
2402 if (end == NULL)
2403 return 0;
2404 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2405 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2406 if (s->v.Assert.msg) {
2407 VISIT(c, expr, s->v.Assert.msg);
2408 ADDOP_I(c, CALL_FUNCTION, 1);
2409 }
2410 ADDOP_I(c, RAISE_VARARGS, 1);
2411 compiler_use_next_block(c, end);
2412 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413}
2414
2415static int
2416compiler_visit_stmt(struct compiler *c, stmt_ty s)
2417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 /* Always assign a lineno to the next instruction for a stmt. */
2421 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002422 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 switch (s->kind) {
2426 case FunctionDef_kind:
2427 return compiler_function(c, s);
2428 case ClassDef_kind:
2429 return compiler_class(c, s);
2430 case Return_kind:
2431 if (c->u->u_ste->ste_type != FunctionBlock)
2432 return compiler_error(c, "'return' outside function");
2433 if (s->v.Return.value) {
2434 VISIT(c, expr, s->v.Return.value);
2435 }
2436 else
2437 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2438 ADDOP(c, RETURN_VALUE);
2439 break;
2440 case Delete_kind:
2441 VISIT_SEQ(c, expr, s->v.Delete.targets)
2442 break;
2443 case Assign_kind:
2444 n = asdl_seq_LEN(s->v.Assign.targets);
2445 VISIT(c, expr, s->v.Assign.value);
2446 for (i = 0; i < n; i++) {
2447 if (i < n - 1)
2448 ADDOP(c, DUP_TOP);
2449 VISIT(c, expr,
2450 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2451 }
2452 break;
2453 case AugAssign_kind:
2454 return compiler_augassign(c, s);
2455 case For_kind:
2456 return compiler_for(c, s);
2457 case While_kind:
2458 return compiler_while(c, s);
2459 case If_kind:
2460 return compiler_if(c, s);
2461 case Raise_kind:
2462 n = 0;
2463 if (s->v.Raise.exc) {
2464 VISIT(c, expr, s->v.Raise.exc);
2465 n++;
2466 if (s->v.Raise.cause) {
2467 VISIT(c, expr, s->v.Raise.cause);
2468 n++;
2469 }
2470 }
2471 ADDOP_I(c, RAISE_VARARGS, n);
2472 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002473 case Try_kind:
2474 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 case Assert_kind:
2476 return compiler_assert(c, s);
2477 case Import_kind:
2478 return compiler_import(c, s);
2479 case ImportFrom_kind:
2480 return compiler_from_import(c, s);
2481 case Global_kind:
2482 case Nonlocal_kind:
2483 break;
2484 case Expr_kind:
2485 if (c->c_interactive && c->c_nestlevel <= 1) {
2486 VISIT(c, expr, s->v.Expr.value);
2487 ADDOP(c, PRINT_EXPR);
2488 }
2489 else if (s->v.Expr.value->kind != Str_kind &&
2490 s->v.Expr.value->kind != Num_kind) {
2491 VISIT(c, expr, s->v.Expr.value);
2492 ADDOP(c, POP_TOP);
2493 }
2494 break;
2495 case Pass_kind:
2496 break;
2497 case Break_kind:
2498 if (!compiler_in_loop(c))
2499 return compiler_error(c, "'break' outside loop");
2500 ADDOP(c, BREAK_LOOP);
2501 break;
2502 case Continue_kind:
2503 return compiler_continue(c);
2504 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002505 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 }
2507 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508}
2509
2510static int
2511unaryop(unaryop_ty op)
2512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 switch (op) {
2514 case Invert:
2515 return UNARY_INVERT;
2516 case Not:
2517 return UNARY_NOT;
2518 case UAdd:
2519 return UNARY_POSITIVE;
2520 case USub:
2521 return UNARY_NEGATIVE;
2522 default:
2523 PyErr_Format(PyExc_SystemError,
2524 "unary op %d should not be possible", op);
2525 return 0;
2526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527}
2528
2529static int
2530binop(struct compiler *c, operator_ty op)
2531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 switch (op) {
2533 case Add:
2534 return BINARY_ADD;
2535 case Sub:
2536 return BINARY_SUBTRACT;
2537 case Mult:
2538 return BINARY_MULTIPLY;
2539 case Div:
2540 return BINARY_TRUE_DIVIDE;
2541 case Mod:
2542 return BINARY_MODULO;
2543 case Pow:
2544 return BINARY_POWER;
2545 case LShift:
2546 return BINARY_LSHIFT;
2547 case RShift:
2548 return BINARY_RSHIFT;
2549 case BitOr:
2550 return BINARY_OR;
2551 case BitXor:
2552 return BINARY_XOR;
2553 case BitAnd:
2554 return BINARY_AND;
2555 case FloorDiv:
2556 return BINARY_FLOOR_DIVIDE;
2557 default:
2558 PyErr_Format(PyExc_SystemError,
2559 "binary op %d should not be possible", op);
2560 return 0;
2561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562}
2563
2564static int
2565cmpop(cmpop_ty op)
2566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 switch (op) {
2568 case Eq:
2569 return PyCmp_EQ;
2570 case NotEq:
2571 return PyCmp_NE;
2572 case Lt:
2573 return PyCmp_LT;
2574 case LtE:
2575 return PyCmp_LE;
2576 case Gt:
2577 return PyCmp_GT;
2578 case GtE:
2579 return PyCmp_GE;
2580 case Is:
2581 return PyCmp_IS;
2582 case IsNot:
2583 return PyCmp_IS_NOT;
2584 case In:
2585 return PyCmp_IN;
2586 case NotIn:
2587 return PyCmp_NOT_IN;
2588 default:
2589 return PyCmp_BAD;
2590 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591}
2592
2593static int
2594inplace_binop(struct compiler *c, operator_ty op)
2595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 switch (op) {
2597 case Add:
2598 return INPLACE_ADD;
2599 case Sub:
2600 return INPLACE_SUBTRACT;
2601 case Mult:
2602 return INPLACE_MULTIPLY;
2603 case Div:
2604 return INPLACE_TRUE_DIVIDE;
2605 case Mod:
2606 return INPLACE_MODULO;
2607 case Pow:
2608 return INPLACE_POWER;
2609 case LShift:
2610 return INPLACE_LSHIFT;
2611 case RShift:
2612 return INPLACE_RSHIFT;
2613 case BitOr:
2614 return INPLACE_OR;
2615 case BitXor:
2616 return INPLACE_XOR;
2617 case BitAnd:
2618 return INPLACE_AND;
2619 case FloorDiv:
2620 return INPLACE_FLOOR_DIVIDE;
2621 default:
2622 PyErr_Format(PyExc_SystemError,
2623 "inplace binary op %d should not be possible", op);
2624 return 0;
2625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626}
2627
2628static int
2629compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 int op, scope, arg;
2632 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 PyObject *dict = c->u->u_names;
2635 PyObject *mangled;
2636 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 mangled = _Py_Mangle(c->u->u_private, name);
2639 if (!mangled)
2640 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002641
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002642 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2643 PyUnicode_CompareWithASCIIString(name, "True") &&
2644 PyUnicode_CompareWithASCIIString(name, "False"));
2645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 op = 0;
2647 optype = OP_NAME;
2648 scope = PyST_GetScope(c->u->u_ste, mangled);
2649 switch (scope) {
2650 case FREE:
2651 dict = c->u->u_freevars;
2652 optype = OP_DEREF;
2653 break;
2654 case CELL:
2655 dict = c->u->u_cellvars;
2656 optype = OP_DEREF;
2657 break;
2658 case LOCAL:
2659 if (c->u->u_ste->ste_type == FunctionBlock)
2660 optype = OP_FAST;
2661 break;
2662 case GLOBAL_IMPLICIT:
2663 if (c->u->u_ste->ste_type == FunctionBlock &&
2664 !c->u->u_ste->ste_unoptimized)
2665 optype = OP_GLOBAL;
2666 break;
2667 case GLOBAL_EXPLICIT:
2668 optype = OP_GLOBAL;
2669 break;
2670 default:
2671 /* scope can be 0 */
2672 break;
2673 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 switch (optype) {
2679 case OP_DEREF:
2680 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002681 case Load:
2682 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2683 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 case Store: op = STORE_DEREF; break;
2685 case AugLoad:
2686 case AugStore:
2687 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002688 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 case Param:
2690 default:
2691 PyErr_SetString(PyExc_SystemError,
2692 "param invalid for deref variable");
2693 return 0;
2694 }
2695 break;
2696 case OP_FAST:
2697 switch (ctx) {
2698 case Load: op = LOAD_FAST; break;
2699 case Store: op = STORE_FAST; break;
2700 case Del: op = DELETE_FAST; break;
2701 case AugLoad:
2702 case AugStore:
2703 break;
2704 case Param:
2705 default:
2706 PyErr_SetString(PyExc_SystemError,
2707 "param invalid for local variable");
2708 return 0;
2709 }
2710 ADDOP_O(c, op, mangled, varnames);
2711 Py_DECREF(mangled);
2712 return 1;
2713 case OP_GLOBAL:
2714 switch (ctx) {
2715 case Load: op = LOAD_GLOBAL; break;
2716 case Store: op = STORE_GLOBAL; break;
2717 case Del: op = DELETE_GLOBAL; break;
2718 case AugLoad:
2719 case AugStore:
2720 break;
2721 case Param:
2722 default:
2723 PyErr_SetString(PyExc_SystemError,
2724 "param invalid for global variable");
2725 return 0;
2726 }
2727 break;
2728 case OP_NAME:
2729 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002730 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 case Store: op = STORE_NAME; break;
2732 case Del: op = DELETE_NAME; break;
2733 case AugLoad:
2734 case AugStore:
2735 break;
2736 case Param:
2737 default:
2738 PyErr_SetString(PyExc_SystemError,
2739 "param invalid for name variable");
2740 return 0;
2741 }
2742 break;
2743 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 assert(op);
2746 arg = compiler_add_o(c, dict, mangled);
2747 Py_DECREF(mangled);
2748 if (arg < 0)
2749 return 0;
2750 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751}
2752
2753static int
2754compiler_boolop(struct compiler *c, expr_ty e)
2755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 basicblock *end;
2757 int jumpi, i, n;
2758 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 assert(e->kind == BoolOp_kind);
2761 if (e->v.BoolOp.op == And)
2762 jumpi = JUMP_IF_FALSE_OR_POP;
2763 else
2764 jumpi = JUMP_IF_TRUE_OR_POP;
2765 end = compiler_new_block(c);
2766 if (end == NULL)
2767 return 0;
2768 s = e->v.BoolOp.values;
2769 n = asdl_seq_LEN(s) - 1;
2770 assert(n >= 0);
2771 for (i = 0; i < n; ++i) {
2772 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2773 ADDOP_JABS(c, jumpi, end);
2774 }
2775 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2776 compiler_use_next_block(c, end);
2777 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778}
2779
2780static int
2781compiler_list(struct compiler *c, expr_ty e)
2782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 int n = asdl_seq_LEN(e->v.List.elts);
2784 if (e->v.List.ctx == Store) {
2785 int i, seen_star = 0;
2786 for (i = 0; i < n; i++) {
2787 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2788 if (elt->kind == Starred_kind && !seen_star) {
2789 if ((i >= (1 << 8)) ||
2790 (n-i-1 >= (INT_MAX >> 8)))
2791 return compiler_error(c,
2792 "too many expressions in "
2793 "star-unpacking assignment");
2794 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2795 seen_star = 1;
2796 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2797 } else if (elt->kind == Starred_kind) {
2798 return compiler_error(c,
2799 "two starred expressions in assignment");
2800 }
2801 }
2802 if (!seen_star) {
2803 ADDOP_I(c, UNPACK_SEQUENCE, n);
2804 }
2805 }
2806 VISIT_SEQ(c, expr, e->v.List.elts);
2807 if (e->v.List.ctx == Load) {
2808 ADDOP_I(c, BUILD_LIST, n);
2809 }
2810 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811}
2812
2813static int
2814compiler_tuple(struct compiler *c, expr_ty e)
2815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 int n = asdl_seq_LEN(e->v.Tuple.elts);
2817 if (e->v.Tuple.ctx == Store) {
2818 int i, seen_star = 0;
2819 for (i = 0; i < n; i++) {
2820 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2821 if (elt->kind == Starred_kind && !seen_star) {
2822 if ((i >= (1 << 8)) ||
2823 (n-i-1 >= (INT_MAX >> 8)))
2824 return compiler_error(c,
2825 "too many expressions in "
2826 "star-unpacking assignment");
2827 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2828 seen_star = 1;
2829 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2830 } else if (elt->kind == Starred_kind) {
2831 return compiler_error(c,
2832 "two starred expressions in assignment");
2833 }
2834 }
2835 if (!seen_star) {
2836 ADDOP_I(c, UNPACK_SEQUENCE, n);
2837 }
2838 }
2839 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2840 if (e->v.Tuple.ctx == Load) {
2841 ADDOP_I(c, BUILD_TUPLE, n);
2842 }
2843 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844}
2845
2846static int
2847compiler_compare(struct compiler *c, expr_ty e)
2848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 int i, n;
2850 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2853 VISIT(c, expr, e->v.Compare.left);
2854 n = asdl_seq_LEN(e->v.Compare.ops);
2855 assert(n > 0);
2856 if (n > 1) {
2857 cleanup = compiler_new_block(c);
2858 if (cleanup == NULL)
2859 return 0;
2860 VISIT(c, expr,
2861 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2862 }
2863 for (i = 1; i < n; i++) {
2864 ADDOP(c, DUP_TOP);
2865 ADDOP(c, ROT_THREE);
2866 ADDOP_I(c, COMPARE_OP,
2867 cmpop((cmpop_ty)(asdl_seq_GET(
2868 e->v.Compare.ops, i - 1))));
2869 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2870 NEXT_BLOCK(c);
2871 if (i < (n - 1))
2872 VISIT(c, expr,
2873 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2874 }
2875 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2876 ADDOP_I(c, COMPARE_OP,
2877 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2878 if (n > 1) {
2879 basicblock *end = compiler_new_block(c);
2880 if (end == NULL)
2881 return 0;
2882 ADDOP_JREL(c, JUMP_FORWARD, end);
2883 compiler_use_next_block(c, cleanup);
2884 ADDOP(c, ROT_TWO);
2885 ADDOP(c, POP_TOP);
2886 compiler_use_next_block(c, end);
2887 }
2888 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889}
2890
2891static int
2892compiler_call(struct compiler *c, expr_ty e)
2893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 VISIT(c, expr, e->v.Call.func);
2895 return compiler_call_helper(c, 0,
2896 e->v.Call.args,
2897 e->v.Call.keywords,
2898 e->v.Call.starargs,
2899 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002900}
2901
2902/* shared code between compiler_call and compiler_class */
2903static int
2904compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 int n, /* Args already pushed */
2906 asdl_seq *args,
2907 asdl_seq *keywords,
2908 expr_ty starargs,
2909 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 n += asdl_seq_LEN(args);
2914 VISIT_SEQ(c, expr, args);
2915 if (keywords) {
2916 VISIT_SEQ(c, keyword, keywords);
2917 n |= asdl_seq_LEN(keywords) << 8;
2918 }
2919 if (starargs) {
2920 VISIT(c, expr, starargs);
2921 code |= 1;
2922 }
2923 if (kwargs) {
2924 VISIT(c, expr, kwargs);
2925 code |= 2;
2926 }
2927 switch (code) {
2928 case 0:
2929 ADDOP_I(c, CALL_FUNCTION, n);
2930 break;
2931 case 1:
2932 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2933 break;
2934 case 2:
2935 ADDOP_I(c, CALL_FUNCTION_KW, n);
2936 break;
2937 case 3:
2938 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2939 break;
2940 }
2941 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942}
2943
Nick Coghlan650f0d02007-04-15 12:05:43 +00002944
2945/* List and set comprehensions and generator expressions work by creating a
2946 nested function to perform the actual iteration. This means that the
2947 iteration variables don't leak into the current scope.
2948 The defined function is called immediately following its definition, with the
2949 result of that call being the result of the expression.
2950 The LC/SC version returns the populated container, while the GE version is
2951 flagged in symtable.c as a generator, so it returns the generator object
2952 when the function is called.
2953 This code *knows* that the loop cannot contain break, continue, or return,
2954 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2955
2956 Possible cleanups:
2957 - iterate over the generator sequence instead of using recursion
2958*/
2959
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961compiler_comprehension_generator(struct compiler *c,
2962 asdl_seq *generators, int gen_index,
2963 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 /* generate code for the iterator, then each of the ifs,
2966 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 comprehension_ty gen;
2969 basicblock *start, *anchor, *skip, *if_cleanup;
2970 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 start = compiler_new_block(c);
2973 skip = compiler_new_block(c);
2974 if_cleanup = compiler_new_block(c);
2975 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2978 anchor == NULL)
2979 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 if (gen_index == 0) {
2984 /* Receive outermost iter as an implicit argument */
2985 c->u->u_argcount = 1;
2986 ADDOP_I(c, LOAD_FAST, 0);
2987 }
2988 else {
2989 /* Sub-iter - calculate on the fly */
2990 VISIT(c, expr, gen->iter);
2991 ADDOP(c, GET_ITER);
2992 }
2993 compiler_use_next_block(c, start);
2994 ADDOP_JREL(c, FOR_ITER, anchor);
2995 NEXT_BLOCK(c);
2996 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 /* XXX this needs to be cleaned up...a lot! */
2999 n = asdl_seq_LEN(gen->ifs);
3000 for (i = 0; i < n; i++) {
3001 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3002 VISIT(c, expr, e);
3003 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3004 NEXT_BLOCK(c);
3005 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 if (++gen_index < asdl_seq_LEN(generators))
3008 if (!compiler_comprehension_generator(c,
3009 generators, gen_index,
3010 elt, val, type))
3011 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 /* only append after the last for generator */
3014 if (gen_index >= asdl_seq_LEN(generators)) {
3015 /* comprehension specific code */
3016 switch (type) {
3017 case COMP_GENEXP:
3018 VISIT(c, expr, elt);
3019 ADDOP(c, YIELD_VALUE);
3020 ADDOP(c, POP_TOP);
3021 break;
3022 case COMP_LISTCOMP:
3023 VISIT(c, expr, elt);
3024 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3025 break;
3026 case COMP_SETCOMP:
3027 VISIT(c, expr, elt);
3028 ADDOP_I(c, SET_ADD, gen_index + 1);
3029 break;
3030 case COMP_DICTCOMP:
3031 /* With 'd[k] = v', v is evaluated before k, so we do
3032 the same. */
3033 VISIT(c, expr, val);
3034 VISIT(c, expr, elt);
3035 ADDOP_I(c, MAP_ADD, gen_index + 1);
3036 break;
3037 default:
3038 return 0;
3039 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 compiler_use_next_block(c, skip);
3042 }
3043 compiler_use_next_block(c, if_cleanup);
3044 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3045 compiler_use_next_block(c, anchor);
3046
3047 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048}
3049
3050static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003051compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 PyCodeObject *co = NULL;
3055 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003056 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 outermost_iter = ((comprehension_ty)
3059 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003060
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003061 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3062 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 if (type != COMP_GENEXP) {
3066 int op;
3067 switch (type) {
3068 case COMP_LISTCOMP:
3069 op = BUILD_LIST;
3070 break;
3071 case COMP_SETCOMP:
3072 op = BUILD_SET;
3073 break;
3074 case COMP_DICTCOMP:
3075 op = BUILD_MAP;
3076 break;
3077 default:
3078 PyErr_Format(PyExc_SystemError,
3079 "unknown comprehension type %d", type);
3080 goto error_in_scope;
3081 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 ADDOP_I(c, op, 0);
3084 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 if (!compiler_comprehension_generator(c, generators, 0, elt,
3087 val, type))
3088 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 if (type != COMP_GENEXP) {
3091 ADDOP(c, RETURN_VALUE);
3092 }
3093
3094 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003095 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003097 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 goto error;
3099
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003100 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003102 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 Py_DECREF(co);
3104
3105 VISIT(c, expr, outermost_iter);
3106 ADDOP(c, GET_ITER);
3107 ADDOP_I(c, CALL_FUNCTION, 1);
3108 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003109error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003111error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003112 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 Py_XDECREF(co);
3114 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003115}
3116
3117static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118compiler_genexp(struct compiler *c, expr_ty e)
3119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 static identifier name;
3121 if (!name) {
3122 name = PyUnicode_FromString("<genexpr>");
3123 if (!name)
3124 return 0;
3125 }
3126 assert(e->kind == GeneratorExp_kind);
3127 return compiler_comprehension(c, e, COMP_GENEXP, name,
3128 e->v.GeneratorExp.generators,
3129 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130}
3131
3132static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003133compiler_listcomp(struct compiler *c, expr_ty e)
3134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 static identifier name;
3136 if (!name) {
3137 name = PyUnicode_FromString("<listcomp>");
3138 if (!name)
3139 return 0;
3140 }
3141 assert(e->kind == ListComp_kind);
3142 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3143 e->v.ListComp.generators,
3144 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003145}
3146
3147static int
3148compiler_setcomp(struct compiler *c, expr_ty e)
3149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 static identifier name;
3151 if (!name) {
3152 name = PyUnicode_FromString("<setcomp>");
3153 if (!name)
3154 return 0;
3155 }
3156 assert(e->kind == SetComp_kind);
3157 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3158 e->v.SetComp.generators,
3159 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003160}
3161
3162
3163static int
3164compiler_dictcomp(struct compiler *c, expr_ty e)
3165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 static identifier name;
3167 if (!name) {
3168 name = PyUnicode_FromString("<dictcomp>");
3169 if (!name)
3170 return 0;
3171 }
3172 assert(e->kind == DictComp_kind);
3173 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3174 e->v.DictComp.generators,
3175 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003176}
3177
3178
3179static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180compiler_visit_keyword(struct compiler *c, keyword_ty k)
3181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3183 VISIT(c, expr, k->value);
3184 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185}
3186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188 whether they are true or false.
3189
3190 Return values: 1 for true, 0 for false, -1 for non-constant.
3191 */
3192
3193static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003194expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 char *id;
3197 switch (e->kind) {
3198 case Ellipsis_kind:
3199 return 1;
3200 case Num_kind:
3201 return PyObject_IsTrue(e->v.Num.n);
3202 case Str_kind:
3203 return PyObject_IsTrue(e->v.Str.s);
3204 case Name_kind:
3205 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003206 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003207 if (id && strcmp(id, "__debug__") == 0)
3208 return !c->c_optimize;
3209 return -1;
3210 case NameConstant_kind: {
3211 PyObject *o = e->v.NameConstant.value;
3212 if (o == Py_None)
3213 return 0;
3214 else if (o == Py_True)
3215 return 1;
3216 else if (o == Py_False)
3217 return 0;
3218 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 default:
3220 return -1;
3221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222}
3223
Guido van Rossumc2e20742006-02-27 22:32:47 +00003224/*
3225 Implements the with statement from PEP 343.
3226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003228
3229 with EXPR as VAR:
3230 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231
Guido van Rossumc2e20742006-02-27 22:32:47 +00003232 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233
Thomas Wouters477c8d52006-05-27 19:21:47 +00003234 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003235 exit = context.__exit__ # not calling it
3236 value = context.__enter__()
3237 try:
3238 VAR = value # if VAR present in the syntax
3239 BLOCK
3240 finally:
3241 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003243 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003245 exit(*exc)
3246 */
3247static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003248compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003249{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003250 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003251 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003252
3253 assert(s->kind == With_kind);
3254
Guido van Rossumc2e20742006-02-27 22:32:47 +00003255 block = compiler_new_block(c);
3256 finally = compiler_new_block(c);
3257 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003258 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003259
Thomas Wouters477c8d52006-05-27 19:21:47 +00003260 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003261 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003262 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003263
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003264 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003265 compiler_use_next_block(c, block);
3266 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003267 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003268 }
3269
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003270 if (item->optional_vars) {
3271 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003272 }
3273 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003275 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003276 }
3277
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003278 pos++;
3279 if (pos == asdl_seq_LEN(s->v.With.items))
3280 /* BLOCK code */
3281 VISIT_SEQ(c, stmt, s->v.With.body)
3282 else if (!compiler_with(c, s, pos))
3283 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003284
3285 /* End of try block; start the finally block */
3286 ADDOP(c, POP_BLOCK);
3287 compiler_pop_fblock(c, FINALLY_TRY, block);
3288
3289 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3290 compiler_use_next_block(c, finally);
3291 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003292 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003293
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003294 /* Finally block starts; context.__exit__ is on the stack under
3295 the exception or return information. Just issue our magic
3296 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003297 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003298
3299 /* Finally block ends. */
3300 ADDOP(c, END_FINALLY);
3301 compiler_pop_fblock(c, FINALLY_END, finally);
3302 return 1;
3303}
3304
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305static int
3306compiler_visit_expr(struct compiler *c, expr_ty e)
3307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 /* If expr e has a different line number than the last expr/stmt,
3311 set a new line number for the next instruction.
3312 */
3313 if (e->lineno > c->u->u_lineno) {
3314 c->u->u_lineno = e->lineno;
3315 c->u->u_lineno_set = 0;
3316 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003317 /* Updating the column offset is always harmless. */
3318 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 switch (e->kind) {
3320 case BoolOp_kind:
3321 return compiler_boolop(c, e);
3322 case BinOp_kind:
3323 VISIT(c, expr, e->v.BinOp.left);
3324 VISIT(c, expr, e->v.BinOp.right);
3325 ADDOP(c, binop(c, e->v.BinOp.op));
3326 break;
3327 case UnaryOp_kind:
3328 VISIT(c, expr, e->v.UnaryOp.operand);
3329 ADDOP(c, unaryop(e->v.UnaryOp.op));
3330 break;
3331 case Lambda_kind:
3332 return compiler_lambda(c, e);
3333 case IfExp_kind:
3334 return compiler_ifexp(c, e);
3335 case Dict_kind:
3336 n = asdl_seq_LEN(e->v.Dict.values);
3337 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3338 for (i = 0; i < n; i++) {
3339 VISIT(c, expr,
3340 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3341 VISIT(c, expr,
3342 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3343 ADDOP(c, STORE_MAP);
3344 }
3345 break;
3346 case Set_kind:
3347 n = asdl_seq_LEN(e->v.Set.elts);
3348 VISIT_SEQ(c, expr, e->v.Set.elts);
3349 ADDOP_I(c, BUILD_SET, n);
3350 break;
3351 case GeneratorExp_kind:
3352 return compiler_genexp(c, e);
3353 case ListComp_kind:
3354 return compiler_listcomp(c, e);
3355 case SetComp_kind:
3356 return compiler_setcomp(c, e);
3357 case DictComp_kind:
3358 return compiler_dictcomp(c, e);
3359 case Yield_kind:
3360 if (c->u->u_ste->ste_type != FunctionBlock)
3361 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003362 if (e->v.Yield.value) {
3363 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 }
3365 else {
3366 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3367 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003368 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003370 case YieldFrom_kind:
3371 if (c->u->u_ste->ste_type != FunctionBlock)
3372 return compiler_error(c, "'yield' outside function");
3373 VISIT(c, expr, e->v.YieldFrom.value);
3374 ADDOP(c, GET_ITER);
3375 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3376 ADDOP(c, YIELD_FROM);
3377 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 case Compare_kind:
3379 return compiler_compare(c, e);
3380 case Call_kind:
3381 return compiler_call(c, e);
3382 case Num_kind:
3383 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3384 break;
3385 case Str_kind:
3386 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3387 break;
3388 case Bytes_kind:
3389 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3390 break;
3391 case Ellipsis_kind:
3392 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3393 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003394 case NameConstant_kind:
3395 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3396 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 /* The following exprs can be assignment targets. */
3398 case Attribute_kind:
3399 if (e->v.Attribute.ctx != AugStore)
3400 VISIT(c, expr, e->v.Attribute.value);
3401 switch (e->v.Attribute.ctx) {
3402 case AugLoad:
3403 ADDOP(c, DUP_TOP);
3404 /* Fall through to load */
3405 case Load:
3406 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3407 break;
3408 case AugStore:
3409 ADDOP(c, ROT_TWO);
3410 /* Fall through to save */
3411 case Store:
3412 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3413 break;
3414 case Del:
3415 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3416 break;
3417 case Param:
3418 default:
3419 PyErr_SetString(PyExc_SystemError,
3420 "param invalid in attribute expression");
3421 return 0;
3422 }
3423 break;
3424 case Subscript_kind:
3425 switch (e->v.Subscript.ctx) {
3426 case AugLoad:
3427 VISIT(c, expr, e->v.Subscript.value);
3428 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3429 break;
3430 case Load:
3431 VISIT(c, expr, e->v.Subscript.value);
3432 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3433 break;
3434 case AugStore:
3435 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3436 break;
3437 case Store:
3438 VISIT(c, expr, e->v.Subscript.value);
3439 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3440 break;
3441 case Del:
3442 VISIT(c, expr, e->v.Subscript.value);
3443 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3444 break;
3445 case Param:
3446 default:
3447 PyErr_SetString(PyExc_SystemError,
3448 "param invalid in subscript expression");
3449 return 0;
3450 }
3451 break;
3452 case Starred_kind:
3453 switch (e->v.Starred.ctx) {
3454 case Store:
3455 /* In all legitimate cases, the Starred node was already replaced
3456 * by compiler_list/compiler_tuple. XXX: is that okay? */
3457 return compiler_error(c,
3458 "starred assignment target must be in a list or tuple");
3459 default:
3460 return compiler_error(c,
3461 "can use starred expression only as assignment target");
3462 }
3463 break;
3464 case Name_kind:
3465 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3466 /* child nodes of List and Tuple will have expr_context set */
3467 case List_kind:
3468 return compiler_list(c, e);
3469 case Tuple_kind:
3470 return compiler_tuple(c, e);
3471 }
3472 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473}
3474
3475static int
3476compiler_augassign(struct compiler *c, stmt_ty s)
3477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 expr_ty e = s->v.AugAssign.target;
3479 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 switch (e->kind) {
3484 case Attribute_kind:
3485 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3486 AugLoad, e->lineno, e->col_offset, c->c_arena);
3487 if (auge == NULL)
3488 return 0;
3489 VISIT(c, expr, auge);
3490 VISIT(c, expr, s->v.AugAssign.value);
3491 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3492 auge->v.Attribute.ctx = AugStore;
3493 VISIT(c, expr, auge);
3494 break;
3495 case Subscript_kind:
3496 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3497 AugLoad, e->lineno, e->col_offset, c->c_arena);
3498 if (auge == NULL)
3499 return 0;
3500 VISIT(c, expr, auge);
3501 VISIT(c, expr, s->v.AugAssign.value);
3502 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3503 auge->v.Subscript.ctx = AugStore;
3504 VISIT(c, expr, auge);
3505 break;
3506 case Name_kind:
3507 if (!compiler_nameop(c, e->v.Name.id, Load))
3508 return 0;
3509 VISIT(c, expr, s->v.AugAssign.value);
3510 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3511 return compiler_nameop(c, e->v.Name.id, Store);
3512 default:
3513 PyErr_Format(PyExc_SystemError,
3514 "invalid node type (%d) for augmented assignment",
3515 e->kind);
3516 return 0;
3517 }
3518 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519}
3520
3521static int
3522compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 struct fblockinfo *f;
3525 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3526 PyErr_SetString(PyExc_SystemError,
3527 "too many statically nested blocks");
3528 return 0;
3529 }
3530 f = &c->u->u_fblock[c->u->u_nfblocks++];
3531 f->fb_type = t;
3532 f->fb_block = b;
3533 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534}
3535
3536static void
3537compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 struct compiler_unit *u = c->u;
3540 assert(u->u_nfblocks > 0);
3541 u->u_nfblocks--;
3542 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3543 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544}
3545
Thomas Wouters89f507f2006-12-13 04:49:30 +00003546static int
3547compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 int i;
3549 struct compiler_unit *u = c->u;
3550 for (i = 0; i < u->u_nfblocks; ++i) {
3551 if (u->u_fblock[i].fb_type == LOOP)
3552 return 1;
3553 }
3554 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003555}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556/* Raises a SyntaxError and returns 0.
3557 If something goes wrong, a different exception may be raised.
3558*/
3559
3560static int
3561compiler_error(struct compiler *c, const char *errstr)
3562{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003563 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3567 if (!loc) {
3568 Py_INCREF(Py_None);
3569 loc = Py_None;
3570 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003571 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003572 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 if (!u)
3574 goto exit;
3575 v = Py_BuildValue("(zO)", errstr, u);
3576 if (!v)
3577 goto exit;
3578 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 Py_DECREF(loc);
3581 Py_XDECREF(u);
3582 Py_XDECREF(v);
3583 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584}
3585
3586static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587compiler_handle_subscr(struct compiler *c, const char *kind,
3588 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 /* XXX this code is duplicated */
3593 switch (ctx) {
3594 case AugLoad: /* fall through to Load */
3595 case Load: op = BINARY_SUBSCR; break;
3596 case AugStore:/* fall through to Store */
3597 case Store: op = STORE_SUBSCR; break;
3598 case Del: op = DELETE_SUBSCR; break;
3599 case Param:
3600 PyErr_Format(PyExc_SystemError,
3601 "invalid %s kind %d in subscript\n",
3602 kind, ctx);
3603 return 0;
3604 }
3605 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003606 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 }
3608 else if (ctx == AugStore) {
3609 ADDOP(c, ROT_THREE);
3610 }
3611 ADDOP(c, op);
3612 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613}
3614
3615static int
3616compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 int n = 2;
3619 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 /* only handles the cases where BUILD_SLICE is emitted */
3622 if (s->v.Slice.lower) {
3623 VISIT(c, expr, s->v.Slice.lower);
3624 }
3625 else {
3626 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3627 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 if (s->v.Slice.upper) {
3630 VISIT(c, expr, s->v.Slice.upper);
3631 }
3632 else {
3633 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3634 }
3635
3636 if (s->v.Slice.step) {
3637 n++;
3638 VISIT(c, expr, s->v.Slice.step);
3639 }
3640 ADDOP_I(c, BUILD_SLICE, n);
3641 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642}
3643
3644static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3646 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 switch (s->kind) {
3649 case Slice_kind:
3650 return compiler_slice(c, s, ctx);
3651 case Index_kind:
3652 VISIT(c, expr, s->v.Index.value);
3653 break;
3654 case ExtSlice_kind:
3655 default:
3656 PyErr_SetString(PyExc_SystemError,
3657 "extended slice invalid in nested slice");
3658 return 0;
3659 }
3660 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661}
3662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663static int
3664compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 char * kindname = NULL;
3667 switch (s->kind) {
3668 case Index_kind:
3669 kindname = "index";
3670 if (ctx != AugStore) {
3671 VISIT(c, expr, s->v.Index.value);
3672 }
3673 break;
3674 case Slice_kind:
3675 kindname = "slice";
3676 if (ctx != AugStore) {
3677 if (!compiler_slice(c, s, ctx))
3678 return 0;
3679 }
3680 break;
3681 case ExtSlice_kind:
3682 kindname = "extended slice";
3683 if (ctx != AugStore) {
3684 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3685 for (i = 0; i < n; i++) {
3686 slice_ty sub = (slice_ty)asdl_seq_GET(
3687 s->v.ExtSlice.dims, i);
3688 if (!compiler_visit_nested_slice(c, sub, ctx))
3689 return 0;
3690 }
3691 ADDOP_I(c, BUILD_TUPLE, n);
3692 }
3693 break;
3694 default:
3695 PyErr_Format(PyExc_SystemError,
3696 "invalid subscript kind %d", s->kind);
3697 return 0;
3698 }
3699 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700}
3701
Thomas Wouters89f507f2006-12-13 04:49:30 +00003702/* End of the compiler section, beginning of the assembler section */
3703
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704/* do depth-first search of basic block graph, starting with block.
3705 post records the block indices in post-order.
3706
3707 XXX must handle implicit jumps from one block to next
3708*/
3709
Thomas Wouters89f507f2006-12-13 04:49:30 +00003710struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 PyObject *a_bytecode; /* string containing bytecode */
3712 int a_offset; /* offset into bytecode */
3713 int a_nblocks; /* number of reachable blocks */
3714 basicblock **a_postorder; /* list of blocks in dfs postorder */
3715 PyObject *a_lnotab; /* string containing lnotab */
3716 int a_lnotab_off; /* offset into lnotab */
3717 int a_lineno; /* last lineno of emitted instruction */
3718 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003719};
3720
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721static void
3722dfs(struct compiler *c, basicblock *b, struct assembler *a)
3723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 int i;
3725 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 if (b->b_seen)
3728 return;
3729 b->b_seen = 1;
3730 if (b->b_next != NULL)
3731 dfs(c, b->b_next, a);
3732 for (i = 0; i < b->b_iused; i++) {
3733 instr = &b->b_instr[i];
3734 if (instr->i_jrel || instr->i_jabs)
3735 dfs(c, instr->i_target, a);
3736 }
3737 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738}
3739
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003740static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 int i, target_depth;
3744 struct instr *instr;
3745 if (b->b_seen || b->b_startdepth >= depth)
3746 return maxdepth;
3747 b->b_seen = 1;
3748 b->b_startdepth = depth;
3749 for (i = 0; i < b->b_iused; i++) {
3750 instr = &b->b_instr[i];
3751 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3752 if (depth > maxdepth)
3753 maxdepth = depth;
3754 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3755 if (instr->i_jrel || instr->i_jabs) {
3756 target_depth = depth;
3757 if (instr->i_opcode == FOR_ITER) {
3758 target_depth = depth-2;
3759 } else if (instr->i_opcode == SETUP_FINALLY ||
3760 instr->i_opcode == SETUP_EXCEPT) {
3761 target_depth = depth+3;
3762 if (target_depth > maxdepth)
3763 maxdepth = target_depth;
3764 }
3765 maxdepth = stackdepth_walk(c, instr->i_target,
3766 target_depth, maxdepth);
3767 if (instr->i_opcode == JUMP_ABSOLUTE ||
3768 instr->i_opcode == JUMP_FORWARD) {
3769 goto out; /* remaining code is dead */
3770 }
3771 }
3772 }
3773 if (b->b_next)
3774 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 b->b_seen = 0;
3777 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778}
3779
3780/* Find the flow path that needs the largest stack. We assume that
3781 * cycles in the flow graph have no net effect on the stack depth.
3782 */
3783static int
3784stackdepth(struct compiler *c)
3785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 basicblock *b, *entryblock;
3787 entryblock = NULL;
3788 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3789 b->b_seen = 0;
3790 b->b_startdepth = INT_MIN;
3791 entryblock = b;
3792 }
3793 if (!entryblock)
3794 return 0;
3795 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796}
3797
3798static int
3799assemble_init(struct assembler *a, int nblocks, int firstlineno)
3800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 memset(a, 0, sizeof(struct assembler));
3802 a->a_lineno = firstlineno;
3803 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3804 if (!a->a_bytecode)
3805 return 0;
3806 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3807 if (!a->a_lnotab)
3808 return 0;
3809 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3810 PyErr_NoMemory();
3811 return 0;
3812 }
3813 a->a_postorder = (basicblock **)PyObject_Malloc(
3814 sizeof(basicblock *) * nblocks);
3815 if (!a->a_postorder) {
3816 PyErr_NoMemory();
3817 return 0;
3818 }
3819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820}
3821
3822static void
3823assemble_free(struct assembler *a)
3824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 Py_XDECREF(a->a_bytecode);
3826 Py_XDECREF(a->a_lnotab);
3827 if (a->a_postorder)
3828 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829}
3830
3831/* Return the size of a basic block in bytes. */
3832
3833static int
3834instrsize(struct instr *instr)
3835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 if (!instr->i_hasarg)
3837 return 1; /* 1 byte for the opcode*/
3838 if (instr->i_oparg > 0xffff)
3839 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3840 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841}
3842
3843static int
3844blocksize(basicblock *b)
3845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 int i;
3847 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 for (i = 0; i < b->b_iused; i++)
3850 size += instrsize(&b->b_instr[i]);
3851 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003852}
3853
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003854/* Appends a pair to the end of the line number table, a_lnotab, representing
3855 the instruction's bytecode offset and line number. See
3856 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003857
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003858static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 int d_bytecode, d_lineno;
3862 int len;
3863 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 d_bytecode = a->a_offset - a->a_lineno_off;
3866 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 assert(d_bytecode >= 0);
3869 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if(d_bytecode == 0 && d_lineno == 0)
3872 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 if (d_bytecode > 255) {
3875 int j, nbytes, ncodes = d_bytecode / 255;
3876 nbytes = a->a_lnotab_off + 2 * ncodes;
3877 len = PyBytes_GET_SIZE(a->a_lnotab);
3878 if (nbytes >= len) {
3879 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3880 len = nbytes;
3881 else if (len <= INT_MAX / 2)
3882 len *= 2;
3883 else {
3884 PyErr_NoMemory();
3885 return 0;
3886 }
3887 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3888 return 0;
3889 }
3890 lnotab = (unsigned char *)
3891 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3892 for (j = 0; j < ncodes; j++) {
3893 *lnotab++ = 255;
3894 *lnotab++ = 0;
3895 }
3896 d_bytecode -= ncodes * 255;
3897 a->a_lnotab_off += ncodes * 2;
3898 }
3899 assert(d_bytecode <= 255);
3900 if (d_lineno > 255) {
3901 int j, nbytes, ncodes = d_lineno / 255;
3902 nbytes = a->a_lnotab_off + 2 * ncodes;
3903 len = PyBytes_GET_SIZE(a->a_lnotab);
3904 if (nbytes >= len) {
3905 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3906 len = nbytes;
3907 else if (len <= INT_MAX / 2)
3908 len *= 2;
3909 else {
3910 PyErr_NoMemory();
3911 return 0;
3912 }
3913 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3914 return 0;
3915 }
3916 lnotab = (unsigned char *)
3917 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3918 *lnotab++ = d_bytecode;
3919 *lnotab++ = 255;
3920 d_bytecode = 0;
3921 for (j = 1; j < ncodes; j++) {
3922 *lnotab++ = 0;
3923 *lnotab++ = 255;
3924 }
3925 d_lineno -= ncodes * 255;
3926 a->a_lnotab_off += ncodes * 2;
3927 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 len = PyBytes_GET_SIZE(a->a_lnotab);
3930 if (a->a_lnotab_off + 2 >= len) {
3931 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3932 return 0;
3933 }
3934 lnotab = (unsigned char *)
3935 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 a->a_lnotab_off += 2;
3938 if (d_bytecode) {
3939 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003940 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 }
3942 else { /* First line of a block; def stmt, etc. */
3943 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003944 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 }
3946 a->a_lineno = i->i_lineno;
3947 a->a_lineno_off = a->a_offset;
3948 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003949}
3950
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951/* assemble_emit()
3952 Extend the bytecode with a new instruction.
3953 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003954*/
3955
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003956static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 int size, arg = 0, ext = 0;
3960 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3961 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 size = instrsize(i);
3964 if (i->i_hasarg) {
3965 arg = i->i_oparg;
3966 ext = arg >> 16;
3967 }
3968 if (i->i_lineno && !assemble_lnotab(a, i))
3969 return 0;
3970 if (a->a_offset + size >= len) {
3971 if (len > PY_SSIZE_T_MAX / 2)
3972 return 0;
3973 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3974 return 0;
3975 }
3976 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3977 a->a_offset += size;
3978 if (size == 6) {
3979 assert(i->i_hasarg);
3980 *code++ = (char)EXTENDED_ARG;
3981 *code++ = ext & 0xff;
3982 *code++ = ext >> 8;
3983 arg &= 0xffff;
3984 }
3985 *code++ = i->i_opcode;
3986 if (i->i_hasarg) {
3987 assert(size == 3 || size == 6);
3988 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003989 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 }
3991 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003992}
3993
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003994static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003995assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 basicblock *b;
3998 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3999 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 /* Compute the size of each block and fixup jump args.
4002 Replace block pointer with position in bytecode. */
4003 do {
4004 totsize = 0;
4005 for (i = a->a_nblocks - 1; i >= 0; i--) {
4006 b = a->a_postorder[i];
4007 bsize = blocksize(b);
4008 b->b_offset = totsize;
4009 totsize += bsize;
4010 }
4011 last_extended_arg_count = extended_arg_count;
4012 extended_arg_count = 0;
4013 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4014 bsize = b->b_offset;
4015 for (i = 0; i < b->b_iused; i++) {
4016 struct instr *instr = &b->b_instr[i];
4017 /* Relative jumps are computed relative to
4018 the instruction pointer after fetching
4019 the jump instruction.
4020 */
4021 bsize += instrsize(instr);
4022 if (instr->i_jabs)
4023 instr->i_oparg = instr->i_target->b_offset;
4024 else if (instr->i_jrel) {
4025 int delta = instr->i_target->b_offset - bsize;
4026 instr->i_oparg = delta;
4027 }
4028 else
4029 continue;
4030 if (instr->i_oparg > 0xffff)
4031 extended_arg_count++;
4032 }
4033 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 /* XXX: This is an awful hack that could hurt performance, but
4036 on the bright side it should work until we come up
4037 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 The issue is that in the first loop blocksize() is called
4040 which calls instrsize() which requires i_oparg be set
4041 appropriately. There is a bootstrap problem because
4042 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 So we loop until we stop seeing new EXTENDED_ARGs.
4045 The only EXTENDED_ARGs that could be popping up are
4046 ones in jump instructions. So this should converge
4047 fairly quickly.
4048 */
4049 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004050}
4051
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004052static PyObject *
4053dict_keys_inorder(PyObject *dict, int offset)
4054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 PyObject *tuple, *k, *v;
4056 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 tuple = PyTuple_New(size);
4059 if (tuple == NULL)
4060 return NULL;
4061 while (PyDict_Next(dict, &pos, &k, &v)) {
4062 i = PyLong_AS_LONG(v);
4063 /* The keys of the dictionary are tuples. (see compiler_add_o)
4064 The object we want is always first, though. */
4065 k = PyTuple_GET_ITEM(k, 0);
4066 Py_INCREF(k);
4067 assert((i - offset) < size);
4068 assert((i - offset) >= 0);
4069 PyTuple_SET_ITEM(tuple, i - offset, k);
4070 }
4071 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004072}
4073
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004074static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004075compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 PySTEntryObject *ste = c->u->u_ste;
4078 int flags = 0, n;
4079 if (ste->ste_type != ModuleBlock)
4080 flags |= CO_NEWLOCALS;
4081 if (ste->ste_type == FunctionBlock) {
4082 if (!ste->ste_unoptimized)
4083 flags |= CO_OPTIMIZED;
4084 if (ste->ste_nested)
4085 flags |= CO_NESTED;
4086 if (ste->ste_generator)
4087 flags |= CO_GENERATOR;
4088 if (ste->ste_varargs)
4089 flags |= CO_VARARGS;
4090 if (ste->ste_varkeywords)
4091 flags |= CO_VARKEYWORDS;
4092 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 /* (Only) inherit compilerflags in PyCF_MASK */
4095 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 n = PyDict_Size(c->u->u_freevars);
4098 if (n < 0)
4099 return -1;
4100 if (n == 0) {
4101 n = PyDict_Size(c->u->u_cellvars);
4102 if (n < 0)
4103 return -1;
4104 if (n == 0) {
4105 flags |= CO_NOFREE;
4106 }
4107 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004110}
4111
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004112static PyCodeObject *
4113makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 PyObject *tmp;
4116 PyCodeObject *co = NULL;
4117 PyObject *consts = NULL;
4118 PyObject *names = NULL;
4119 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 PyObject *name = NULL;
4121 PyObject *freevars = NULL;
4122 PyObject *cellvars = NULL;
4123 PyObject *bytecode = NULL;
4124 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 tmp = dict_keys_inorder(c->u->u_consts, 0);
4127 if (!tmp)
4128 goto error;
4129 consts = PySequence_List(tmp); /* optimize_code requires a list */
4130 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 names = dict_keys_inorder(c->u->u_names, 0);
4133 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4134 if (!consts || !names || !varnames)
4135 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4138 if (!cellvars)
4139 goto error;
4140 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4141 if (!freevars)
4142 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 nlocals = PyDict_Size(c->u->u_varnames);
4144 flags = compute_code_flags(c);
4145 if (flags < 0)
4146 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4149 if (!bytecode)
4150 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4153 if (!tmp)
4154 goto error;
4155 Py_DECREF(consts);
4156 consts = tmp;
4157
4158 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4159 nlocals, stackdepth(c), flags,
4160 bytecode, consts, names, varnames,
4161 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004162 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 c->u->u_firstlineno,
4164 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 Py_XDECREF(consts);
4167 Py_XDECREF(names);
4168 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 Py_XDECREF(name);
4170 Py_XDECREF(freevars);
4171 Py_XDECREF(cellvars);
4172 Py_XDECREF(bytecode);
4173 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004174}
4175
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004176
4177/* For debugging purposes only */
4178#if 0
4179static void
4180dump_instr(const struct instr *i)
4181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 const char *jrel = i->i_jrel ? "jrel " : "";
4183 const char *jabs = i->i_jabs ? "jabs " : "";
4184 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 *arg = '\0';
4187 if (i->i_hasarg)
4188 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4191 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004192}
4193
4194static void
4195dump_basicblock(const basicblock *b)
4196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 const char *seen = b->b_seen ? "seen " : "";
4198 const char *b_return = b->b_return ? "return " : "";
4199 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4200 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4201 if (b->b_instr) {
4202 int i;
4203 for (i = 0; i < b->b_iused; i++) {
4204 fprintf(stderr, " [%02d] ", i);
4205 dump_instr(b->b_instr + i);
4206 }
4207 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004208}
4209#endif
4210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211static PyCodeObject *
4212assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 basicblock *b, *entryblock;
4215 struct assembler a;
4216 int i, j, nblocks;
4217 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 /* Make sure every block that falls off the end returns None.
4220 XXX NEXT_BLOCK() isn't quite right, because if the last
4221 block ends with a jump or return b_next shouldn't set.
4222 */
4223 if (!c->u->u_curblock->b_return) {
4224 NEXT_BLOCK(c);
4225 if (addNone)
4226 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4227 ADDOP(c, RETURN_VALUE);
4228 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 nblocks = 0;
4231 entryblock = NULL;
4232 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4233 nblocks++;
4234 entryblock = b;
4235 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 /* Set firstlineno if it wasn't explicitly set. */
4238 if (!c->u->u_firstlineno) {
4239 if (entryblock && entryblock->b_instr)
4240 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4241 else
4242 c->u->u_firstlineno = 1;
4243 }
4244 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4245 goto error;
4246 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 /* Can't modify the bytecode after computing jump offsets. */
4249 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 /* Emit code in reverse postorder from dfs. */
4252 for (i = a.a_nblocks - 1; i >= 0; i--) {
4253 b = a.a_postorder[i];
4254 for (j = 0; j < b->b_iused; j++)
4255 if (!assemble_emit(&a, &b->b_instr[j]))
4256 goto error;
4257 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4260 goto error;
4261 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4262 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004265 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 assemble_free(&a);
4267 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004268}
Georg Brandl8334fd92010-12-04 10:26:46 +00004269
4270#undef PyAST_Compile
4271PyAPI_FUNC(PyCodeObject *)
4272PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4273 PyArena *arena)
4274{
4275 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4276}
4277
4278