blob: 10e9ad27f56f5d9ff2cba806b024706d1b40380d [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().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144*/
145
146struct compiler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 const char *c_filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500148 PyObject *c_filename_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 struct symtable *c_st;
150 PyFutureFeatures *c_future; /* pointer to module's __future__ */
151 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152
Georg Brandl8334fd92010-12-04 10:26:46 +0000153 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 int c_interactive; /* true if in interactive mode */
155 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 struct compiler_unit *u; /* compiler state for current block */
158 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
159 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160};
161
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100162static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163static void compiler_free(struct compiler *);
164static basicblock *compiler_new_block(struct compiler *);
165static int compiler_next_instr(struct compiler *, basicblock *);
166static int compiler_addop(struct compiler *, int);
167static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
168static int compiler_addop_i(struct compiler *, int, int);
169static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170static basicblock *compiler_use_new_block(struct compiler *);
171static int compiler_error(struct compiler *, const char *);
172static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
173
174static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
175static int compiler_visit_stmt(struct compiler *, stmt_ty);
176static int compiler_visit_keyword(struct compiler *, keyword_ty);
177static int compiler_visit_expr(struct compiler *, expr_ty);
178static int compiler_augassign(struct compiler *, stmt_ty);
179static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181
182static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000186/* Returns true if there is a loop on the fblock stack. */
187static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188
189static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000190static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500192static int compiler_with(struct compiler *, stmt_ty, int);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000193static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 asdl_seq *args,
195 asdl_seq *keywords,
196 expr_ty starargs,
197 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500198static int compiler_try_except(struct compiler *, stmt_ty);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200static PyCodeObject *assemble(struct compiler *, int addNone);
201static PyObject *__doc__;
202
Benjamin Petersonb173f782009-05-05 22:31:58 +0000203#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* Name mangling: __private becomes _classname__private.
209 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200210 PyObject *result;
211 size_t nlen, plen, ipriv;
212 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyUnicode_READ_CHAR(ident, 0) != '_' ||
215 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 Py_INCREF(ident);
217 return ident;
218 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200219 nlen = PyUnicode_GET_LENGTH(ident);
220 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 The only time a name with a dot can occur is when
224 we are compiling an import statement that has a
225 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 TODO(jhylton): Decide whether we want to support
228 mangling of the module name, e.g. __M.X.
229 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200230 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
231 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
232 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 Py_INCREF(ident);
234 return ident; /* Don't mangle __whatever__ */
235 }
236 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200237 ipriv = 0;
238 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
239 ipriv++;
240 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 Py_INCREF(ident);
242 return ident; /* Don't mangle if class is just underscores */
243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200244 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 assert(1 <= PY_SSIZE_T_MAX - nlen);
247 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
250 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
251 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
252
253 result = PyUnicode_New(1 + nlen + plen, maxchar);
254 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
257 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200258 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
259 Py_DECREF(result);
260 return NULL;
261 }
262 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
263 Py_DECREF(result);
264 return NULL;
265 }
Victor Stinner8f825062012-04-27 13:55:39 +0200266 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000268}
269
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270static int
271compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 c->c_stack = PyList_New(0);
276 if (!c->c_stack)
277 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280}
281
282PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +0000283PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
284 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 struct compiler c;
287 PyCodeObject *co = NULL;
288 PyCompilerFlags local_flags;
289 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (!__doc__) {
292 __doc__ = PyUnicode_InternFromString("__doc__");
293 if (!__doc__)
294 return NULL;
295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (!compiler_init(&c))
298 return NULL;
299 c.c_filename = filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500300 c.c_filename_obj = PyUnicode_DecodeFSDefault(filename);
301 if (!c.c_filename_obj)
302 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 c.c_arena = arena;
304 c.c_future = PyFuture_FromAST(mod, filename);
305 if (c.c_future == NULL)
306 goto finally;
307 if (!flags) {
308 local_flags.cf_flags = 0;
309 flags = &local_flags;
310 }
311 merged = c.c_future->ff_features | flags->cf_flags;
312 c.c_future->ff_features = merged;
313 flags->cf_flags = merged;
314 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000315 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_st = PySymtable_Build(mod, filename, c.c_future);
319 if (c.c_st == NULL) {
320 if (!PyErr_Occurred())
321 PyErr_SetString(PyExc_SystemError, "no symtable");
322 goto finally;
323 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326
Thomas Wouters1175c432006-02-27 22:49:54 +0000327 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 compiler_free(&c);
329 assert(co || PyErr_Occurred());
330 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331}
332
333PyCodeObject *
334PyNode_Compile(struct _node *n, const char *filename)
335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyCodeObject *co = NULL;
337 mod_ty mod;
338 PyArena *arena = PyArena_New();
339 if (!arena)
340 return NULL;
341 mod = PyAST_FromNode(n, NULL, filename, arena);
342 if (mod)
343 co = PyAST_Compile(mod, filename, NULL, arena);
344 PyArena_Free(arena);
345 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000346}
347
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000348static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (c->c_st)
352 PySymtable_Free(c->c_st);
353 if (c->c_future)
354 PyObject_Free(c->c_future);
Benjamin Peterson43b06862011-05-27 09:08:01 -0500355 if (c->c_filename_obj)
356 Py_DECREF(c->c_filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000358}
359
Guido van Rossum79f25d91997-04-29 20:08:16 +0000360static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 Py_ssize_t i, n;
364 PyObject *v, *k;
365 PyObject *dict = PyDict_New();
366 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 n = PyList_Size(list);
369 for (i = 0; i < n; i++) {
370 v = PyLong_FromLong(i);
371 if (!v) {
372 Py_DECREF(dict);
373 return NULL;
374 }
375 k = PyList_GET_ITEM(list, i);
376 k = PyTuple_Pack(2, k, k->ob_type);
377 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
378 Py_XDECREF(k);
379 Py_DECREF(v);
380 Py_DECREF(dict);
381 return NULL;
382 }
383 Py_DECREF(k);
384 Py_DECREF(v);
385 }
386 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387}
388
389/* Return new dict containing names from src that match scope(s).
390
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000391src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000393values are integers, starting at offset and increasing by one for
394each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395*/
396
397static PyObject *
398dictbytype(PyObject *src, int scope_type, int flag, int offset)
399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_ssize_t pos = 0, i = offset, scope;
401 PyObject *k, *v, *dest = PyDict_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 assert(offset >= 0);
404 if (dest == NULL)
405 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 while (PyDict_Next(src, &pos, &k, &v)) {
408 /* XXX this should probably be a macro in symtable.h */
409 long vi;
410 assert(PyLong_Check(v));
411 vi = PyLong_AS_LONG(v);
412 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (scope == scope_type || vi & flag) {
415 PyObject *tuple, *item = PyLong_FromLong(i);
416 if (item == NULL) {
417 Py_DECREF(dest);
418 return NULL;
419 }
420 i++;
421 tuple = PyTuple_Pack(2, k, k->ob_type);
422 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
423 Py_DECREF(item);
424 Py_DECREF(dest);
425 Py_XDECREF(tuple);
426 return NULL;
427 }
428 Py_DECREF(item);
429 Py_DECREF(tuple);
430 }
431 }
432 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000433}
434
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435static void
436compiler_unit_check(struct compiler_unit *u)
437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 basicblock *block;
439 for (block = u->u_blocks; block != NULL; block = block->b_list) {
440 assert((void *)block != (void *)0xcbcbcbcb);
441 assert((void *)block != (void *)0xfbfbfbfb);
442 assert((void *)block != (void *)0xdbdbdbdb);
443 if (block->b_instr != NULL) {
444 assert(block->b_ialloc > 0);
445 assert(block->b_iused > 0);
446 assert(block->b_ialloc >= block->b_iused);
447 }
448 else {
449 assert (block->b_iused == 0);
450 assert (block->b_ialloc == 0);
451 }
452 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453}
454
455static void
456compiler_unit_free(struct compiler_unit *u)
457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 compiler_unit_check(u);
461 b = u->u_blocks;
462 while (b != NULL) {
463 if (b->b_instr)
464 PyObject_Free((void *)b->b_instr);
465 next = b->b_list;
466 PyObject_Free((void *)b);
467 b = next;
468 }
469 Py_CLEAR(u->u_ste);
470 Py_CLEAR(u->u_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100471 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_CLEAR(u->u_consts);
473 Py_CLEAR(u->u_names);
474 Py_CLEAR(u->u_varnames);
475 Py_CLEAR(u->u_freevars);
476 Py_CLEAR(u->u_cellvars);
477 Py_CLEAR(u->u_private);
478 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000479}
480
481static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100482compiler_enter_scope(struct compiler *c, identifier name,
483 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
488 struct compiler_unit));
489 if (!u) {
490 PyErr_NoMemory();
491 return 0;
492 }
493 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100494 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 u->u_argcount = 0;
496 u->u_kwonlyargcount = 0;
497 u->u_ste = PySymtable_Lookup(c->c_st, key);
498 if (!u->u_ste) {
499 compiler_unit_free(u);
500 return 0;
501 }
502 Py_INCREF(name);
503 u->u_name = name;
504 u->u_varnames = list2dict(u->u_ste->ste_varnames);
505 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
506 if (!u->u_varnames || !u->u_cellvars) {
507 compiler_unit_free(u);
508 return 0;
509 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
512 PyDict_Size(u->u_cellvars));
513 if (!u->u_freevars) {
514 compiler_unit_free(u);
515 return 0;
516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 u->u_blocks = NULL;
519 u->u_nfblocks = 0;
520 u->u_firstlineno = lineno;
521 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000522 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 u->u_lineno_set = 0;
524 u->u_consts = PyDict_New();
525 if (!u->u_consts) {
526 compiler_unit_free(u);
527 return 0;
528 }
529 u->u_names = PyDict_New();
530 if (!u->u_names) {
531 compiler_unit_free(u);
532 return 0;
533 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* Push the old compiler_unit on the stack. */
538 if (c->u) {
539 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
540 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
541 Py_XDECREF(capsule);
542 compiler_unit_free(u);
543 return 0;
544 }
545 Py_DECREF(capsule);
546 u->u_private = c->u->u_private;
547 Py_XINCREF(u->u_private);
548 }
549 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 c->c_nestlevel++;
552 if (compiler_use_new_block(c) == NULL)
553 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556}
557
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000558static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559compiler_exit_scope(struct compiler *c)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 int n;
562 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 c->c_nestlevel--;
565 compiler_unit_free(c->u);
566 /* Restore c->u to the parent unit. */
567 n = PyList_GET_SIZE(c->c_stack) - 1;
568 if (n >= 0) {
569 capsule = PyList_GET_ITEM(c->c_stack, n);
570 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
571 assert(c->u);
572 /* we are deleting from a list so this really shouldn't fail */
573 if (PySequence_DelItem(c->c_stack, n) < 0)
574 Py_FatalError("compiler_exit_scope()");
575 compiler_unit_check(c->u);
576 }
577 else
578 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580}
581
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100582static PyObject *
583compiler_scope_qualname(struct compiler *c)
584{
585 Py_ssize_t stack_size, i;
586 _Py_static_string(dot, ".");
587 _Py_static_string(locals, "<locals>");
588 struct compiler_unit *u;
589 PyObject *capsule, *name, *seq, *dot_str, *locals_str;
590
591 u = c->u;
592 if (u->u_qualname != NULL) {
593 Py_INCREF(u->u_qualname);
594 return u->u_qualname;
595 }
596
597 seq = PyList_New(0);
598 if (seq == NULL)
599 return NULL;
600
601 stack_size = PyList_GET_SIZE(c->c_stack);
602 for (i = 0; i < stack_size; i++) {
603 capsule = PyList_GET_ITEM(c->c_stack, i);
604 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
605 assert(u);
606 if (u->u_scope_type == COMPILER_SCOPE_MODULE)
607 continue;
608 if (PyList_Append(seq, u->u_name))
609 goto _error;
610 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION) {
611 locals_str = _PyUnicode_FromId(&locals);
612 if (locals_str == NULL)
613 goto _error;
614 if (PyList_Append(seq, locals_str))
615 goto _error;
616 }
617 }
618 u = c->u;
619 if (PyList_Append(seq, u->u_name))
620 goto _error;
621 dot_str = _PyUnicode_FromId(&dot);
622 if (dot_str == NULL)
623 goto _error;
624 name = PyUnicode_Join(dot_str, seq);
625 Py_DECREF(seq);
626 u->u_qualname = name;
627 Py_XINCREF(name);
628 return name;
629
630_error:
631 Py_XDECREF(seq);
632 return NULL;
633}
634
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635/* Allocate a new block and return a pointer to it.
636 Returns NULL on error.
637*/
638
639static basicblock *
640compiler_new_block(struct compiler *c)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 basicblock *b;
643 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 u = c->u;
646 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
647 if (b == NULL) {
648 PyErr_NoMemory();
649 return NULL;
650 }
651 memset((void *)b, 0, sizeof(basicblock));
652 /* Extend the singly linked list of blocks with new block. */
653 b->b_list = u->u_blocks;
654 u->u_blocks = b;
655 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656}
657
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658static basicblock *
659compiler_use_new_block(struct compiler *c)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 basicblock *block = compiler_new_block(c);
662 if (block == NULL)
663 return NULL;
664 c->u->u_curblock = block;
665 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666}
667
668static basicblock *
669compiler_next_block(struct compiler *c)
670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 basicblock *block = compiler_new_block(c);
672 if (block == NULL)
673 return NULL;
674 c->u->u_curblock->b_next = block;
675 c->u->u_curblock = block;
676 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677}
678
679static basicblock *
680compiler_use_next_block(struct compiler *c, basicblock *block)
681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 assert(block != NULL);
683 c->u->u_curblock->b_next = block;
684 c->u->u_curblock = block;
685 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686}
687
688/* Returns the offset of the next instruction in the current block's
689 b_instr array. Resizes the b_instr as necessary.
690 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000691*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000692
693static int
694compiler_next_instr(struct compiler *c, basicblock *b)
695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 assert(b != NULL);
697 if (b->b_instr == NULL) {
698 b->b_instr = (struct instr *)PyObject_Malloc(
699 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
700 if (b->b_instr == NULL) {
701 PyErr_NoMemory();
702 return -1;
703 }
704 b->b_ialloc = DEFAULT_BLOCK_SIZE;
705 memset((char *)b->b_instr, 0,
706 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
707 }
708 else if (b->b_iused == b->b_ialloc) {
709 struct instr *tmp;
710 size_t oldsize, newsize;
711 oldsize = b->b_ialloc * sizeof(struct instr);
712 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (oldsize > (PY_SIZE_MAX >> 1)) {
715 PyErr_NoMemory();
716 return -1;
717 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (newsize == 0) {
720 PyErr_NoMemory();
721 return -1;
722 }
723 b->b_ialloc <<= 1;
724 tmp = (struct instr *)PyObject_Realloc(
725 (void *)b->b_instr, newsize);
726 if (tmp == NULL) {
727 PyErr_NoMemory();
728 return -1;
729 }
730 b->b_instr = tmp;
731 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
732 }
733 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734}
735
Christian Heimes2202f872008-02-06 14:31:34 +0000736/* Set the i_lineno member of the instruction at offset off if the
737 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000738 already been set. If it has been set, the call has no effect.
739
Christian Heimes2202f872008-02-06 14:31:34 +0000740 The line number is reset in the following cases:
741 - when entering a new scope
742 - on each statement
743 - on each expression that start a new line
744 - before the "except" clause
745 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000746*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000747
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000748static void
749compiler_set_lineno(struct compiler *c, int off)
750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 basicblock *b;
752 if (c->u->u_lineno_set)
753 return;
754 c->u->u_lineno_set = 1;
755 b = c->u->u_curblock;
756 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757}
758
759static int
760opcode_stack_effect(int opcode, int oparg)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 switch (opcode) {
763 case POP_TOP:
764 return -1;
765 case ROT_TWO:
766 case ROT_THREE:
767 return 0;
768 case DUP_TOP:
769 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000770 case DUP_TOP_TWO:
771 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 case UNARY_POSITIVE:
774 case UNARY_NEGATIVE:
775 case UNARY_NOT:
776 case UNARY_INVERT:
777 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 case SET_ADD:
780 case LIST_APPEND:
781 return -1;
782 case MAP_ADD:
783 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 case BINARY_POWER:
786 case BINARY_MULTIPLY:
787 case BINARY_MODULO:
788 case BINARY_ADD:
789 case BINARY_SUBTRACT:
790 case BINARY_SUBSCR:
791 case BINARY_FLOOR_DIVIDE:
792 case BINARY_TRUE_DIVIDE:
793 return -1;
794 case INPLACE_FLOOR_DIVIDE:
795 case INPLACE_TRUE_DIVIDE:
796 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 case INPLACE_ADD:
799 case INPLACE_SUBTRACT:
800 case INPLACE_MULTIPLY:
801 case INPLACE_MODULO:
802 return -1;
803 case STORE_SUBSCR:
804 return -3;
805 case STORE_MAP:
806 return -2;
807 case DELETE_SUBSCR:
808 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 case BINARY_LSHIFT:
811 case BINARY_RSHIFT:
812 case BINARY_AND:
813 case BINARY_XOR:
814 case BINARY_OR:
815 return -1;
816 case INPLACE_POWER:
817 return -1;
818 case GET_ITER:
819 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 case PRINT_EXPR:
822 return -1;
823 case LOAD_BUILD_CLASS:
824 return 1;
825 case INPLACE_LSHIFT:
826 case INPLACE_RSHIFT:
827 case INPLACE_AND:
828 case INPLACE_XOR:
829 case INPLACE_OR:
830 return -1;
831 case BREAK_LOOP:
832 return 0;
833 case SETUP_WITH:
834 return 7;
835 case WITH_CLEANUP:
836 return -1; /* XXX Sometimes more */
837 case STORE_LOCALS:
838 return -1;
839 case RETURN_VALUE:
840 return -1;
841 case IMPORT_STAR:
842 return -1;
843 case YIELD_VALUE:
844 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500845 case YIELD_FROM:
846 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 case POP_BLOCK:
848 return 0;
849 case POP_EXCEPT:
850 return 0; /* -3 except if bad bytecode */
851 case END_FINALLY:
852 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 case STORE_NAME:
855 return -1;
856 case DELETE_NAME:
857 return 0;
858 case UNPACK_SEQUENCE:
859 return oparg-1;
860 case UNPACK_EX:
861 return (oparg&0xFF) + (oparg>>8);
862 case FOR_ITER:
863 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 case STORE_ATTR:
866 return -2;
867 case DELETE_ATTR:
868 return -1;
869 case STORE_GLOBAL:
870 return -1;
871 case DELETE_GLOBAL:
872 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 case LOAD_CONST:
874 return 1;
875 case LOAD_NAME:
876 return 1;
877 case BUILD_TUPLE:
878 case BUILD_LIST:
879 case BUILD_SET:
880 return 1-oparg;
881 case BUILD_MAP:
882 return 1;
883 case LOAD_ATTR:
884 return 0;
885 case COMPARE_OP:
886 return -1;
887 case IMPORT_NAME:
888 return -1;
889 case IMPORT_FROM:
890 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case JUMP_FORWARD:
893 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
894 case JUMP_IF_FALSE_OR_POP: /* "" */
895 case JUMP_ABSOLUTE:
896 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case POP_JUMP_IF_FALSE:
899 case POP_JUMP_IF_TRUE:
900 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case LOAD_GLOBAL:
903 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 case CONTINUE_LOOP:
906 return 0;
907 case SETUP_LOOP:
908 return 0;
909 case SETUP_EXCEPT:
910 case SETUP_FINALLY:
911 return 6; /* can push 3 values for the new exception
912 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case LOAD_FAST:
915 return 1;
916 case STORE_FAST:
917 return -1;
918 case DELETE_FAST:
919 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case RAISE_VARARGS:
922 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000923#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 case CALL_FUNCTION:
925 return -NARGS(oparg);
926 case CALL_FUNCTION_VAR:
927 case CALL_FUNCTION_KW:
928 return -NARGS(oparg)-1;
929 case CALL_FUNCTION_VAR_KW:
930 return -NARGS(oparg)-2;
931 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100932 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100934 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000935#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case BUILD_SLICE:
937 if (oparg == 3)
938 return -2;
939 else
940 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case LOAD_CLOSURE:
943 return 1;
944 case LOAD_DEREF:
945 return 1;
946 case STORE_DEREF:
947 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000948 case DELETE_DEREF:
949 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 default:
951 fprintf(stderr, "opcode = %d\n", opcode);
952 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 }
955 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956}
957
958/* Add an opcode with no argument.
959 Returns 0 on failure, 1 on success.
960*/
961
962static int
963compiler_addop(struct compiler *c, int opcode)
964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 basicblock *b;
966 struct instr *i;
967 int off;
968 off = compiler_next_instr(c, c->u->u_curblock);
969 if (off < 0)
970 return 0;
971 b = c->u->u_curblock;
972 i = &b->b_instr[off];
973 i->i_opcode = opcode;
974 i->i_hasarg = 0;
975 if (opcode == RETURN_VALUE)
976 b->b_return = 1;
977 compiler_set_lineno(c, off);
978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979}
980
981static int
982compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyObject *t, *v;
985 Py_ssize_t arg;
986 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* necessary to make sure types aren't coerced (e.g., int and long) */
989 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
990 if (PyFloat_Check(o)) {
991 d = PyFloat_AS_DOUBLE(o);
992 /* all we need is to make the tuple different in either the 0.0
993 * or -0.0 case from all others, just to avoid the "coercion".
994 */
995 if (d == 0.0 && copysign(1.0, d) < 0.0)
996 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
997 else
998 t = PyTuple_Pack(2, o, o->ob_type);
999 }
1000 else if (PyComplex_Check(o)) {
1001 Py_complex z;
1002 int real_negzero, imag_negzero;
1003 /* For the complex case we must make complex(x, 0.)
1004 different from complex(x, -0.) and complex(0., y)
1005 different from complex(-0., y), for any x and y.
1006 All four complex zeros must be distinguished.*/
1007 z = PyComplex_AsCComplex(o);
1008 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1009 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1010 if (real_negzero && imag_negzero) {
1011 t = PyTuple_Pack(5, o, o->ob_type,
1012 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001013 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 else if (imag_negzero) {
1015 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001016 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 else if (real_negzero) {
1018 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1019 }
1020 else {
1021 t = PyTuple_Pack(2, o, o->ob_type);
1022 }
1023 }
1024 else {
1025 t = PyTuple_Pack(2, o, o->ob_type);
1026 }
1027 if (t == NULL)
1028 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 v = PyDict_GetItem(dict, t);
1031 if (!v) {
1032 if (PyErr_Occurred())
1033 return -1;
1034 arg = PyDict_Size(dict);
1035 v = PyLong_FromLong(arg);
1036 if (!v) {
1037 Py_DECREF(t);
1038 return -1;
1039 }
1040 if (PyDict_SetItem(dict, t, v) < 0) {
1041 Py_DECREF(t);
1042 Py_DECREF(v);
1043 return -1;
1044 }
1045 Py_DECREF(v);
1046 }
1047 else
1048 arg = PyLong_AsLong(v);
1049 Py_DECREF(t);
1050 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051}
1052
1053static int
1054compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056{
1057 int arg = compiler_add_o(c, dict, o);
1058 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001059 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060 return compiler_addop_i(c, opcode, arg);
1061}
1062
1063static int
1064compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066{
1067 int arg;
1068 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1069 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001070 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071 arg = compiler_add_o(c, dict, mangled);
1072 Py_DECREF(mangled);
1073 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001074 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075 return compiler_addop_i(c, opcode, arg);
1076}
1077
1078/* Add an opcode with an integer argument.
1079 Returns 0 on failure, 1 on success.
1080*/
1081
1082static int
1083compiler_addop_i(struct compiler *c, int opcode, int oparg)
1084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 struct instr *i;
1086 int off;
1087 off = compiler_next_instr(c, c->u->u_curblock);
1088 if (off < 0)
1089 return 0;
1090 i = &c->u->u_curblock->b_instr[off];
1091 i->i_opcode = opcode;
1092 i->i_oparg = oparg;
1093 i->i_hasarg = 1;
1094 compiler_set_lineno(c, off);
1095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096}
1097
1098static int
1099compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 struct instr *i;
1102 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 assert(b != NULL);
1105 off = compiler_next_instr(c, c->u->u_curblock);
1106 if (off < 0)
1107 return 0;
1108 i = &c->u->u_curblock->b_instr[off];
1109 i->i_opcode = opcode;
1110 i->i_target = b;
1111 i->i_hasarg = 1;
1112 if (absolute)
1113 i->i_jabs = 1;
1114 else
1115 i->i_jrel = 1;
1116 compiler_set_lineno(c, off);
1117 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118}
1119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1121 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122 it as the current block. NEXT_BLOCK() also creates an implicit jump
1123 from the current block to the new block.
1124*/
1125
Thomas Wouters89f507f2006-12-13 04:49:30 +00001126/* The returns inside these macros make it impossible to decref objects
1127 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128*/
1129
1130
1131#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (compiler_use_new_block((C)) == NULL) \
1133 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134}
1135
1136#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (compiler_next_block((C)) == NULL) \
1138 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139}
1140
1141#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (!compiler_addop((C), (OP))) \
1143 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144}
1145
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001146#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (!compiler_addop((C), (OP))) { \
1148 compiler_exit_scope(c); \
1149 return 0; \
1150 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001151}
1152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1155 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156}
1157
1158#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1160 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161}
1162
1163#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (!compiler_addop_i((C), (OP), (O))) \
1165 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166}
1167
1168#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (!compiler_addop_j((C), (OP), (O), 1)) \
1170 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171}
1172
1173#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (!compiler_addop_j((C), (OP), (O), 0)) \
1175 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176}
1177
1178/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1179 the ASDL name to synthesize the name of the C type and the visit function.
1180*/
1181
1182#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (!compiler_visit_ ## TYPE((C), (V))) \
1184 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185}
1186
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001187#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (!compiler_visit_ ## TYPE((C), (V))) { \
1189 compiler_exit_scope(c); \
1190 return 0; \
1191 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001192}
1193
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (!compiler_visit_slice((C), (V), (CTX))) \
1196 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197}
1198
1199#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 int _i; \
1201 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1202 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1203 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1204 if (!compiler_visit_ ## TYPE((C), elt)) \
1205 return 0; \
1206 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207}
1208
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001209#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 int _i; \
1211 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1212 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1213 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1214 if (!compiler_visit_ ## TYPE((C), elt)) { \
1215 compiler_exit_scope(c); \
1216 return 0; \
1217 } \
1218 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001219}
1220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221static int
1222compiler_isdocstring(stmt_ty s)
1223{
1224 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001225 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226 return s->v.Expr.value->kind == Str_kind;
1227}
1228
1229/* Compile a sequence of statements, checking for a docstring. */
1230
1231static int
1232compiler_body(struct compiler *c, asdl_seq *stmts)
1233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 int i = 0;
1235 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (!asdl_seq_LEN(stmts))
1238 return 1;
1239 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001240 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 /* don't generate docstrings if -OO */
1242 i = 1;
1243 VISIT(c, expr, st->v.Expr.value);
1244 if (!compiler_nameop(c, __doc__, Store))
1245 return 0;
1246 }
1247 for (; i < asdl_seq_LEN(stmts); i++)
1248 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1249 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252static PyCodeObject *
1253compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 PyCodeObject *co;
1256 int addNone = 1;
1257 static PyObject *module;
1258 if (!module) {
1259 module = PyUnicode_InternFromString("<module>");
1260 if (!module)
1261 return NULL;
1262 }
1263 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001264 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 return NULL;
1266 switch (mod->kind) {
1267 case Module_kind:
1268 if (!compiler_body(c, mod->v.Module.body)) {
1269 compiler_exit_scope(c);
1270 return 0;
1271 }
1272 break;
1273 case Interactive_kind:
1274 c->c_interactive = 1;
1275 VISIT_SEQ_IN_SCOPE(c, stmt,
1276 mod->v.Interactive.body);
1277 break;
1278 case Expression_kind:
1279 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1280 addNone = 0;
1281 break;
1282 case Suite_kind:
1283 PyErr_SetString(PyExc_SystemError,
1284 "suite should not be possible");
1285 return 0;
1286 default:
1287 PyErr_Format(PyExc_SystemError,
1288 "module kind %d should not be possible",
1289 mod->kind);
1290 return 0;
1291 }
1292 co = assemble(c, addNone);
1293 compiler_exit_scope(c);
1294 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001295}
1296
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297/* The test for LOCAL must come before the test for FREE in order to
1298 handle classes where name is both local and free. The local var is
1299 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001300*/
1301
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302static int
1303get_ref_type(struct compiler *c, PyObject *name)
1304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int scope = PyST_GetScope(c->u->u_ste, name);
1306 if (scope == 0) {
1307 char buf[350];
1308 PyOS_snprintf(buf, sizeof(buf),
1309 "unknown scope for %.100s in %.100s(%s) in %s\n"
1310 "symbols: %s\nlocals: %s\nglobals: %s",
1311 PyBytes_AS_STRING(name),
1312 PyBytes_AS_STRING(c->u->u_name),
1313 PyObject_REPR(c->u->u_ste->ste_id),
1314 c->c_filename,
1315 PyObject_REPR(c->u->u_ste->ste_symbols),
1316 PyObject_REPR(c->u->u_varnames),
1317 PyObject_REPR(c->u->u_names)
1318 );
1319 Py_FatalError(buf);
1320 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323}
1324
1325static int
1326compiler_lookup_arg(PyObject *dict, PyObject *name)
1327{
1328 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001329 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001331 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001333 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001335 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001336 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337}
1338
1339static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001340compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001343 if (qualname == NULL)
1344 qualname = co->co_name;
1345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (free == 0) {
1347 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001348 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 ADDOP_I(c, MAKE_FUNCTION, args);
1350 return 1;
1351 }
1352 for (i = 0; i < free; ++i) {
1353 /* Bypass com_addop_varname because it will generate
1354 LOAD_DEREF but LOAD_CLOSURE is needed.
1355 */
1356 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1357 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* Special case: If a class contains a method with a
1360 free variable that has the same name as a method,
1361 the name will be considered free *and* local in the
1362 class. It should be handled by the closure, as
1363 well as by the normal name loookup logic.
1364 */
1365 reftype = get_ref_type(c, name);
1366 if (reftype == CELL)
1367 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1368 else /* (reftype == FREE) */
1369 arg = compiler_lookup_arg(c->u->u_freevars, name);
1370 if (arg == -1) {
1371 fprintf(stderr,
1372 "lookup %s in %s %d %d\n"
1373 "freevars of %s: %s\n",
1374 PyObject_REPR(name),
1375 PyBytes_AS_STRING(c->u->u_name),
1376 reftype, arg,
1377 _PyUnicode_AsString(co->co_name),
1378 PyObject_REPR(co->co_freevars));
1379 Py_FatalError("compiler_make_closure()");
1380 }
1381 ADDOP_I(c, LOAD_CLOSURE, arg);
1382 }
1383 ADDOP_I(c, BUILD_TUPLE, free);
1384 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001385 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 ADDOP_I(c, MAKE_CLOSURE, args);
1387 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388}
1389
1390static int
1391compiler_decorators(struct compiler *c, asdl_seq* decos)
1392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (!decos)
1396 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1399 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1400 }
1401 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402}
1403
1404static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001405compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 int i, default_count = 0;
1409 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1410 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1411 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1412 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001413 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1414 if (!mangled)
1415 return -1;
1416 ADDOP_O(c, LOAD_CONST, mangled, consts);
1417 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!compiler_visit_expr(c, default_)) {
1419 return -1;
1420 }
1421 default_count++;
1422 }
1423 }
1424 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001425}
1426
1427static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001428compiler_visit_argannotation(struct compiler *c, identifier id,
1429 expr_ty annotation, PyObject *names)
1430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (annotation) {
1432 VISIT(c, expr, annotation);
1433 if (PyList_Append(names, id))
1434 return -1;
1435 }
1436 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001437}
1438
1439static int
1440compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1441 PyObject *names)
1442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 int i, error;
1444 for (i = 0; i < asdl_seq_LEN(args); i++) {
1445 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1446 error = compiler_visit_argannotation(
1447 c,
1448 arg->arg,
1449 arg->annotation,
1450 names);
1451 if (error)
1452 return error;
1453 }
1454 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001455}
1456
1457static int
1458compiler_visit_annotations(struct compiler *c, arguments_ty args,
1459 expr_ty returns)
1460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* Push arg annotations and a list of the argument names. Return the #
1462 of items pushed. The expressions are evaluated out-of-order wrt the
1463 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1466 */
1467 static identifier return_str;
1468 PyObject *names;
1469 int len;
1470 names = PyList_New(0);
1471 if (!names)
1472 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (compiler_visit_argannotations(c, args->args, names))
1475 goto error;
1476 if (args->varargannotation &&
1477 compiler_visit_argannotation(c, args->vararg,
1478 args->varargannotation, names))
1479 goto error;
1480 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1481 goto error;
1482 if (args->kwargannotation &&
1483 compiler_visit_argannotation(c, args->kwarg,
1484 args->kwargannotation, names))
1485 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (!return_str) {
1488 return_str = PyUnicode_InternFromString("return");
1489 if (!return_str)
1490 goto error;
1491 }
1492 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1493 goto error;
1494 }
1495
1496 len = PyList_GET_SIZE(names);
1497 if (len > 65534) {
1498 /* len must fit in 16 bits, and len is incremented below */
1499 PyErr_SetString(PyExc_SyntaxError,
1500 "too many annotations");
1501 goto error;
1502 }
1503 if (len) {
1504 /* convert names to a tuple and place on stack */
1505 PyObject *elt;
1506 int i;
1507 PyObject *s = PyTuple_New(len);
1508 if (!s)
1509 goto error;
1510 for (i = 0; i < len; i++) {
1511 elt = PyList_GET_ITEM(names, i);
1512 Py_INCREF(elt);
1513 PyTuple_SET_ITEM(s, i, elt);
1514 }
1515 ADDOP_O(c, LOAD_CONST, s, consts);
1516 Py_DECREF(s);
1517 len++; /* include the just-pushed tuple */
1518 }
1519 Py_DECREF(names);
1520 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001521
1522error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 Py_DECREF(names);
1524 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001525}
1526
1527static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528compiler_function(struct compiler *c, stmt_ty s)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001531 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 arguments_ty args = s->v.FunctionDef.args;
1533 expr_ty returns = s->v.FunctionDef.returns;
1534 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1535 stmt_ty st;
1536 int i, n, docstring, kw_default_count = 0, arglength;
1537 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 if (!compiler_decorators(c, decos))
1542 return 0;
1543 if (args->kwonlyargs) {
1544 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1545 args->kw_defaults);
1546 if (res < 0)
1547 return 0;
1548 kw_default_count = res;
1549 }
1550 if (args->defaults)
1551 VISIT_SEQ(c, expr, args->defaults);
1552 num_annotations = compiler_visit_annotations(c, args, returns);
1553 if (num_annotations < 0)
1554 return 0;
1555 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001556
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001557 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1558 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 s->lineno))
1560 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1563 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001564 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 first_const = st->v.Expr.value->v.Str.s;
1566 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1567 compiler_exit_scope(c);
1568 return 0;
1569 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 c->u->u_argcount = asdl_seq_LEN(args->args);
1572 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1573 n = asdl_seq_LEN(s->v.FunctionDef.body);
1574 /* if there was a docstring, we need to skip the first statement */
1575 for (i = docstring; i < n; i++) {
1576 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1577 VISIT_IN_SCOPE(c, stmt, st);
1578 }
1579 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001580 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001582 if (qualname == NULL || co == NULL) {
1583 Py_XDECREF(qualname);
1584 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001586 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 arglength = asdl_seq_LEN(args->defaults);
1589 arglength |= kw_default_count << 8;
1590 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001591 compiler_make_closure(c, co, arglength, qualname);
1592 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 /* decorators */
1596 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1597 ADDOP_I(c, CALL_FUNCTION, 1);
1598 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601}
1602
1603static int
1604compiler_class(struct compiler *c, stmt_ty s)
1605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyCodeObject *co;
1607 PyObject *str;
1608 int i;
1609 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 if (!compiler_decorators(c, decos))
1612 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* ultimately generate code for:
1615 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1616 where:
1617 <func> is a function/closure created from the class body;
1618 it has a single argument (__locals__) where the dict
1619 (or MutableSequence) representing the locals is passed
1620 <name> is the class name
1621 <bases> is the positional arguments and *varargs argument
1622 <keywords> is the keyword arguments and **kwds argument
1623 This borrows from compiler_call.
1624 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001627 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1628 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 return 0;
1630 /* this block represents what we do in the new scope */
1631 {
1632 /* use the class name for name mangling */
1633 Py_INCREF(s->v.ClassDef.name);
1634 Py_XDECREF(c->u->u_private);
1635 c->u->u_private = s->v.ClassDef.name;
1636 /* force it to have one mandatory argument */
1637 c->u->u_argcount = 1;
1638 /* load the first argument (__locals__) ... */
1639 ADDOP_I(c, LOAD_FAST, 0);
1640 /* ... and store it into f_locals */
1641 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1642 /* load (global) __name__ ... */
1643 str = PyUnicode_InternFromString("__name__");
1644 if (!str || !compiler_nameop(c, str, Load)) {
1645 Py_XDECREF(str);
1646 compiler_exit_scope(c);
1647 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 Py_DECREF(str);
1650 /* ... and store it as __module__ */
1651 str = PyUnicode_InternFromString("__module__");
1652 if (!str || !compiler_nameop(c, str, Store)) {
1653 Py_XDECREF(str);
1654 compiler_exit_scope(c);
1655 return 0;
1656 }
1657 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001658 /* store the __qualname__ */
1659 str = compiler_scope_qualname(c);
1660 if (!str) {
1661 compiler_exit_scope(c);
1662 return 0;
1663 }
1664 ADDOP_O(c, LOAD_CONST, str, consts);
1665 Py_DECREF(str);
1666 str = PyUnicode_InternFromString("__qualname__");
1667 if (!str || !compiler_nameop(c, str, Store)) {
1668 Py_XDECREF(str);
1669 compiler_exit_scope(c);
1670 return 0;
1671 }
1672 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 /* compile the body proper */
1674 if (!compiler_body(c, s->v.ClassDef.body)) {
1675 compiler_exit_scope(c);
1676 return 0;
1677 }
1678 /* return the (empty) __class__ cell */
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05001679 str = PyUnicode_InternFromString("@__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 if (str == NULL) {
1681 compiler_exit_scope(c);
1682 return 0;
1683 }
1684 i = compiler_lookup_arg(c->u->u_cellvars, str);
1685 Py_DECREF(str);
1686 if (i == -1) {
1687 /* This happens when nobody references the cell */
1688 PyErr_Clear();
1689 /* Return None */
1690 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1691 }
1692 else {
1693 /* Return the cell where to store __class__ */
1694 ADDOP_I(c, LOAD_CLOSURE, i);
1695 }
1696 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1697 /* create the code object */
1698 co = assemble(c, 1);
1699 }
1700 /* leave the new scope */
1701 compiler_exit_scope(c);
1702 if (co == NULL)
1703 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 /* 2. load the 'build_class' function */
1706 ADDOP(c, LOAD_BUILD_CLASS);
1707
1708 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001709 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 Py_DECREF(co);
1711
1712 /* 4. load class name */
1713 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1714
1715 /* 5. generate the rest of the code for the call */
1716 if (!compiler_call_helper(c, 2,
1717 s->v.ClassDef.bases,
1718 s->v.ClassDef.keywords,
1719 s->v.ClassDef.starargs,
1720 s->v.ClassDef.kwargs))
1721 return 0;
1722
1723 /* 6. apply decorators */
1724 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1725 ADDOP_I(c, CALL_FUNCTION, 1);
1726 }
1727
1728 /* 7. store into <name> */
1729 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1730 return 0;
1731 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732}
1733
1734static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001735compiler_ifexp(struct compiler *c, expr_ty e)
1736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 basicblock *end, *next;
1738
1739 assert(e->kind == IfExp_kind);
1740 end = compiler_new_block(c);
1741 if (end == NULL)
1742 return 0;
1743 next = compiler_new_block(c);
1744 if (next == NULL)
1745 return 0;
1746 VISIT(c, expr, e->v.IfExp.test);
1747 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1748 VISIT(c, expr, e->v.IfExp.body);
1749 ADDOP_JREL(c, JUMP_FORWARD, end);
1750 compiler_use_next_block(c, next);
1751 VISIT(c, expr, e->v.IfExp.orelse);
1752 compiler_use_next_block(c, end);
1753 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001754}
1755
1756static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757compiler_lambda(struct compiler *c, expr_ty e)
1758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001760 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 static identifier name;
1762 int kw_default_count = 0, arglength;
1763 arguments_ty args = e->v.Lambda.args;
1764 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (!name) {
1767 name = PyUnicode_InternFromString("<lambda>");
1768 if (!name)
1769 return 0;
1770 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 if (args->kwonlyargs) {
1773 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1774 args->kw_defaults);
1775 if (res < 0) return 0;
1776 kw_default_count = res;
1777 }
1778 if (args->defaults)
1779 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001780 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1781 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 /* Make None the first constant, so the lambda can't have a
1785 docstring. */
1786 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1787 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 c->u->u_argcount = asdl_seq_LEN(args->args);
1790 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1791 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1792 if (c->u->u_ste->ste_generator) {
1793 ADDOP_IN_SCOPE(c, POP_TOP);
1794 }
1795 else {
1796 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1797 }
1798 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001799 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001801 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 arglength = asdl_seq_LEN(args->defaults);
1805 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001806 compiler_make_closure(c, co, arglength, qualname);
1807 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 Py_DECREF(co);
1809
1810 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811}
1812
1813static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814compiler_if(struct compiler *c, stmt_ty s)
1815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 basicblock *end, *next;
1817 int constant;
1818 assert(s->kind == If_kind);
1819 end = compiler_new_block(c);
1820 if (end == NULL)
1821 return 0;
1822
Georg Brandl8334fd92010-12-04 10:26:46 +00001823 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 /* constant = 0: "if 0"
1825 * constant = 1: "if 1", "if 2", ...
1826 * constant = -1: rest */
1827 if (constant == 0) {
1828 if (s->v.If.orelse)
1829 VISIT_SEQ(c, stmt, s->v.If.orelse);
1830 } else if (constant == 1) {
1831 VISIT_SEQ(c, stmt, s->v.If.body);
1832 } else {
1833 if (s->v.If.orelse) {
1834 next = compiler_new_block(c);
1835 if (next == NULL)
1836 return 0;
1837 }
1838 else
1839 next = end;
1840 VISIT(c, expr, s->v.If.test);
1841 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1842 VISIT_SEQ(c, stmt, s->v.If.body);
1843 ADDOP_JREL(c, JUMP_FORWARD, end);
1844 if (s->v.If.orelse) {
1845 compiler_use_next_block(c, next);
1846 VISIT_SEQ(c, stmt, s->v.If.orelse);
1847 }
1848 }
1849 compiler_use_next_block(c, end);
1850 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851}
1852
1853static int
1854compiler_for(struct compiler *c, stmt_ty s)
1855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 start = compiler_new_block(c);
1859 cleanup = compiler_new_block(c);
1860 end = compiler_new_block(c);
1861 if (start == NULL || end == NULL || cleanup == NULL)
1862 return 0;
1863 ADDOP_JREL(c, SETUP_LOOP, end);
1864 if (!compiler_push_fblock(c, LOOP, start))
1865 return 0;
1866 VISIT(c, expr, s->v.For.iter);
1867 ADDOP(c, GET_ITER);
1868 compiler_use_next_block(c, start);
1869 ADDOP_JREL(c, FOR_ITER, cleanup);
1870 VISIT(c, expr, s->v.For.target);
1871 VISIT_SEQ(c, stmt, s->v.For.body);
1872 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1873 compiler_use_next_block(c, cleanup);
1874 ADDOP(c, POP_BLOCK);
1875 compiler_pop_fblock(c, LOOP, start);
1876 VISIT_SEQ(c, stmt, s->v.For.orelse);
1877 compiler_use_next_block(c, end);
1878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879}
1880
1881static int
1882compiler_while(struct compiler *c, stmt_ty s)
1883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001885 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (constant == 0) {
1888 if (s->v.While.orelse)
1889 VISIT_SEQ(c, stmt, s->v.While.orelse);
1890 return 1;
1891 }
1892 loop = compiler_new_block(c);
1893 end = compiler_new_block(c);
1894 if (constant == -1) {
1895 anchor = compiler_new_block(c);
1896 if (anchor == NULL)
1897 return 0;
1898 }
1899 if (loop == NULL || end == NULL)
1900 return 0;
1901 if (s->v.While.orelse) {
1902 orelse = compiler_new_block(c);
1903 if (orelse == NULL)
1904 return 0;
1905 }
1906 else
1907 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 ADDOP_JREL(c, SETUP_LOOP, end);
1910 compiler_use_next_block(c, loop);
1911 if (!compiler_push_fblock(c, LOOP, loop))
1912 return 0;
1913 if (constant == -1) {
1914 VISIT(c, expr, s->v.While.test);
1915 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1916 }
1917 VISIT_SEQ(c, stmt, s->v.While.body);
1918 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 /* XXX should the two POP instructions be in a separate block
1921 if there is no else clause ?
1922 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 if (constant == -1) {
1925 compiler_use_next_block(c, anchor);
1926 ADDOP(c, POP_BLOCK);
1927 }
1928 compiler_pop_fblock(c, LOOP, loop);
1929 if (orelse != NULL) /* what if orelse is just pass? */
1930 VISIT_SEQ(c, stmt, s->v.While.orelse);
1931 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001934}
1935
1936static int
1937compiler_continue(struct compiler *c)
1938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1940 static const char IN_FINALLY_ERROR_MSG[] =
1941 "'continue' not supported inside 'finally' clause";
1942 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (!c->u->u_nfblocks)
1945 return compiler_error(c, LOOP_ERROR_MSG);
1946 i = c->u->u_nfblocks - 1;
1947 switch (c->u->u_fblock[i].fb_type) {
1948 case LOOP:
1949 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1950 break;
1951 case EXCEPT:
1952 case FINALLY_TRY:
1953 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1954 /* Prevent continue anywhere under a finally
1955 even if hidden in a sub-try or except. */
1956 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1957 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1958 }
1959 if (i == -1)
1960 return compiler_error(c, LOOP_ERROR_MSG);
1961 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1962 break;
1963 case FINALLY_END:
1964 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968}
1969
1970/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971
1972 SETUP_FINALLY L
1973 <code for body>
1974 POP_BLOCK
1975 LOAD_CONST <None>
1976 L: <code for finalbody>
1977 END_FINALLY
1978
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979 The special instructions use the block stack. Each block
1980 stack entry contains the instruction that created it (here
1981 SETUP_FINALLY), the level of the value stack at the time the
1982 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 Pushes the current value stack level and the label
1986 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 Pops en entry from the block stack, and pops the value
1989 stack until its level is the same as indicated on the
1990 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 Pops a variable number of entries from the *value* stack
1993 and re-raises the exception they specify. The number of
1994 entries popped depends on the (pseudo) exception type.
1995
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996 The block stack is unwound when an exception is raised:
1997 when a SETUP_FINALLY entry is found, the exception is pushed
1998 onto the value stack (and the exception condition is cleared),
1999 and the interpreter jumps to the label gotten from the block
2000 stack.
2001*/
2002
2003static int
2004compiler_try_finally(struct compiler *c, stmt_ty s)
2005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 basicblock *body, *end;
2007 body = compiler_new_block(c);
2008 end = compiler_new_block(c);
2009 if (body == NULL || end == NULL)
2010 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 ADDOP_JREL(c, SETUP_FINALLY, end);
2013 compiler_use_next_block(c, body);
2014 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2015 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002016 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2017 if (!compiler_try_except(c, s))
2018 return 0;
2019 }
2020 else {
2021 VISIT_SEQ(c, stmt, s->v.Try.body);
2022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 ADDOP(c, POP_BLOCK);
2024 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2027 compiler_use_next_block(c, end);
2028 if (!compiler_push_fblock(c, FINALLY_END, end))
2029 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002030 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 ADDOP(c, END_FINALLY);
2032 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035}
2036
2037/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002038 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039 (The contents of the value stack is shown in [], with the top
2040 at the right; 'tb' is trace-back info, 'val' the exception's
2041 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042
2043 Value stack Label Instruction Argument
2044 [] SETUP_EXCEPT L1
2045 [] <code for S>
2046 [] POP_BLOCK
2047 [] JUMP_FORWARD L0
2048
2049 [tb, val, exc] L1: DUP )
2050 [tb, val, exc, exc] <evaluate E1> )
2051 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2052 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2053 [tb, val, exc] POP
2054 [tb, val] <assign to V1> (or POP if no V1)
2055 [tb] POP
2056 [] <code for S1>
2057 JUMP_FORWARD L0
2058
2059 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 .............................etc.......................
2061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2063
2064 [] L0: <next statement>
2065
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 Of course, parts are not generated if Vi or Ei is not present.
2067*/
2068static int
2069compiler_try_except(struct compiler *c, stmt_ty s)
2070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 basicblock *body, *orelse, *except, *end;
2072 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 body = compiler_new_block(c);
2075 except = compiler_new_block(c);
2076 orelse = compiler_new_block(c);
2077 end = compiler_new_block(c);
2078 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2079 return 0;
2080 ADDOP_JREL(c, SETUP_EXCEPT, except);
2081 compiler_use_next_block(c, body);
2082 if (!compiler_push_fblock(c, EXCEPT, body))
2083 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002084 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 ADDOP(c, POP_BLOCK);
2086 compiler_pop_fblock(c, EXCEPT, body);
2087 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002088 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 compiler_use_next_block(c, except);
2090 for (i = 0; i < n; i++) {
2091 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002092 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 if (!handler->v.ExceptHandler.type && i < n-1)
2094 return compiler_error(c, "default 'except:' must be last");
2095 c->u->u_lineno_set = 0;
2096 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002097 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 except = compiler_new_block(c);
2099 if (except == NULL)
2100 return 0;
2101 if (handler->v.ExceptHandler.type) {
2102 ADDOP(c, DUP_TOP);
2103 VISIT(c, expr, handler->v.ExceptHandler.type);
2104 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2105 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2106 }
2107 ADDOP(c, POP_TOP);
2108 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002109 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002110
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002111 cleanup_end = compiler_new_block(c);
2112 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002113 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002114 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002115
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002116 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2117 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002119 /*
2120 try:
2121 # body
2122 except type as name:
2123 try:
2124 # body
2125 finally:
2126 name = None
2127 del name
2128 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002130 /* second try: */
2131 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2132 compiler_use_next_block(c, cleanup_body);
2133 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2134 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002136 /* second # body */
2137 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2138 ADDOP(c, POP_BLOCK);
2139 ADDOP(c, POP_EXCEPT);
2140 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002142 /* finally: */
2143 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2144 compiler_use_next_block(c, cleanup_end);
2145 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2146 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002148 /* name = None */
2149 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2150 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002152 /* del name */
2153 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002155 ADDOP(c, END_FINALLY);
2156 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 }
2158 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002159 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002161 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002162 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002163 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164
Guido van Rossumb940e112007-01-10 16:19:56 +00002165 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002166 ADDOP(c, POP_TOP);
2167 compiler_use_next_block(c, cleanup_body);
2168 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2169 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002171 ADDOP(c, POP_EXCEPT);
2172 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 }
2174 ADDOP_JREL(c, JUMP_FORWARD, end);
2175 compiler_use_next_block(c, except);
2176 }
2177 ADDOP(c, END_FINALLY);
2178 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002179 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 compiler_use_next_block(c, end);
2181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182}
2183
2184static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002185compiler_try(struct compiler *c, stmt_ty s) {
2186 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2187 return compiler_try_finally(c, s);
2188 else
2189 return compiler_try_except(c, s);
2190}
2191
2192
2193static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194compiler_import_as(struct compiler *c, identifier name, identifier asname)
2195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* The IMPORT_NAME opcode was already generated. This function
2197 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 If there is a dot in name, we need to split it and emit a
2200 LOAD_ATTR for each name.
2201 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002202 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2203 PyUnicode_GET_LENGTH(name), 1);
2204 if (dot == -2)
2205 return -1;
2206 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208 Py_ssize_t pos = dot + 1;
2209 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002211 dot = PyUnicode_FindChar(name, '.', pos,
2212 PyUnicode_GET_LENGTH(name), 1);
2213 if (dot == -2)
2214 return -1;
2215 attr = PyUnicode_Substring(name, pos,
2216 (dot != -1) ? dot :
2217 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 if (!attr)
2219 return -1;
2220 ADDOP_O(c, LOAD_ATTR, attr, names);
2221 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 }
2224 }
2225 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226}
2227
2228static int
2229compiler_import(struct compiler *c, stmt_ty s)
2230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* The Import node stores a module name like a.b.c as a single
2232 string. This is convenient for all cases except
2233 import a.b.c as d
2234 where we need to parse that string to extract the individual
2235 module names.
2236 XXX Perhaps change the representation to make this case simpler?
2237 */
2238 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 for (i = 0; i < n; i++) {
2241 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2242 int r;
2243 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 level = PyLong_FromLong(0);
2246 if (level == NULL)
2247 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 ADDOP_O(c, LOAD_CONST, level, consts);
2250 Py_DECREF(level);
2251 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2252 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (alias->asname) {
2255 r = compiler_import_as(c, alias->name, alias->asname);
2256 if (!r)
2257 return r;
2258 }
2259 else {
2260 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 Py_ssize_t dot = PyUnicode_FindChar(
2262 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2263 if (dot != -1)
2264 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 Py_DECREF(tmp);
2268 }
2269 if (!r)
2270 return r;
2271 }
2272 }
2273 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274}
2275
2276static int
2277compiler_from_import(struct compiler *c, stmt_ty s)
2278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 PyObject *names = PyTuple_New(n);
2282 PyObject *level;
2283 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (!empty_string) {
2286 empty_string = PyUnicode_FromString("");
2287 if (!empty_string)
2288 return 0;
2289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (!names)
2292 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 level = PyLong_FromLong(s->v.ImportFrom.level);
2295 if (!level) {
2296 Py_DECREF(names);
2297 return 0;
2298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* build up the names */
2301 for (i = 0; i < n; i++) {
2302 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2303 Py_INCREF(alias->name);
2304 PyTuple_SET_ITEM(names, i, alias->name);
2305 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2308 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2309 Py_DECREF(level);
2310 Py_DECREF(names);
2311 return compiler_error(c, "from __future__ imports must occur "
2312 "at the beginning of the file");
2313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 ADDOP_O(c, LOAD_CONST, level, consts);
2316 Py_DECREF(level);
2317 ADDOP_O(c, LOAD_CONST, names, consts);
2318 Py_DECREF(names);
2319 if (s->v.ImportFrom.module) {
2320 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2321 }
2322 else {
2323 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2324 }
2325 for (i = 0; i < n; i++) {
2326 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2327 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002329 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 assert(n == 1);
2331 ADDOP(c, IMPORT_STAR);
2332 return 1;
2333 }
2334
2335 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2336 store_name = alias->name;
2337 if (alias->asname)
2338 store_name = alias->asname;
2339
2340 if (!compiler_nameop(c, store_name, Store)) {
2341 Py_DECREF(names);
2342 return 0;
2343 }
2344 }
2345 /* remove imported module */
2346 ADDOP(c, POP_TOP);
2347 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348}
2349
2350static int
2351compiler_assert(struct compiler *c, stmt_ty s)
2352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 static PyObject *assertion_error = NULL;
2354 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355
Georg Brandl8334fd92010-12-04 10:26:46 +00002356 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 return 1;
2358 if (assertion_error == NULL) {
2359 assertion_error = PyUnicode_InternFromString("AssertionError");
2360 if (assertion_error == NULL)
2361 return 0;
2362 }
2363 if (s->v.Assert.test->kind == Tuple_kind &&
2364 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2365 const char* msg =
2366 "assertion is always true, perhaps remove parentheses?";
2367 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2368 c->u->u_lineno, NULL, NULL) == -1)
2369 return 0;
2370 }
2371 VISIT(c, expr, s->v.Assert.test);
2372 end = compiler_new_block(c);
2373 if (end == NULL)
2374 return 0;
2375 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2376 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2377 if (s->v.Assert.msg) {
2378 VISIT(c, expr, s->v.Assert.msg);
2379 ADDOP_I(c, CALL_FUNCTION, 1);
2380 }
2381 ADDOP_I(c, RAISE_VARARGS, 1);
2382 compiler_use_next_block(c, end);
2383 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384}
2385
2386static int
2387compiler_visit_stmt(struct compiler *c, stmt_ty s)
2388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Always assign a lineno to the next instruction for a stmt. */
2392 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002393 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 switch (s->kind) {
2397 case FunctionDef_kind:
2398 return compiler_function(c, s);
2399 case ClassDef_kind:
2400 return compiler_class(c, s);
2401 case Return_kind:
2402 if (c->u->u_ste->ste_type != FunctionBlock)
2403 return compiler_error(c, "'return' outside function");
2404 if (s->v.Return.value) {
2405 VISIT(c, expr, s->v.Return.value);
2406 }
2407 else
2408 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2409 ADDOP(c, RETURN_VALUE);
2410 break;
2411 case Delete_kind:
2412 VISIT_SEQ(c, expr, s->v.Delete.targets)
2413 break;
2414 case Assign_kind:
2415 n = asdl_seq_LEN(s->v.Assign.targets);
2416 VISIT(c, expr, s->v.Assign.value);
2417 for (i = 0; i < n; i++) {
2418 if (i < n - 1)
2419 ADDOP(c, DUP_TOP);
2420 VISIT(c, expr,
2421 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2422 }
2423 break;
2424 case AugAssign_kind:
2425 return compiler_augassign(c, s);
2426 case For_kind:
2427 return compiler_for(c, s);
2428 case While_kind:
2429 return compiler_while(c, s);
2430 case If_kind:
2431 return compiler_if(c, s);
2432 case Raise_kind:
2433 n = 0;
2434 if (s->v.Raise.exc) {
2435 VISIT(c, expr, s->v.Raise.exc);
2436 n++;
2437 if (s->v.Raise.cause) {
2438 VISIT(c, expr, s->v.Raise.cause);
2439 n++;
2440 }
2441 }
2442 ADDOP_I(c, RAISE_VARARGS, n);
2443 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002444 case Try_kind:
2445 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 case Assert_kind:
2447 return compiler_assert(c, s);
2448 case Import_kind:
2449 return compiler_import(c, s);
2450 case ImportFrom_kind:
2451 return compiler_from_import(c, s);
2452 case Global_kind:
2453 case Nonlocal_kind:
2454 break;
2455 case Expr_kind:
2456 if (c->c_interactive && c->c_nestlevel <= 1) {
2457 VISIT(c, expr, s->v.Expr.value);
2458 ADDOP(c, PRINT_EXPR);
2459 }
2460 else if (s->v.Expr.value->kind != Str_kind &&
2461 s->v.Expr.value->kind != Num_kind) {
2462 VISIT(c, expr, s->v.Expr.value);
2463 ADDOP(c, POP_TOP);
2464 }
2465 break;
2466 case Pass_kind:
2467 break;
2468 case Break_kind:
2469 if (!compiler_in_loop(c))
2470 return compiler_error(c, "'break' outside loop");
2471 ADDOP(c, BREAK_LOOP);
2472 break;
2473 case Continue_kind:
2474 return compiler_continue(c);
2475 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002476 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 }
2478 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479}
2480
2481static int
2482unaryop(unaryop_ty op)
2483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 switch (op) {
2485 case Invert:
2486 return UNARY_INVERT;
2487 case Not:
2488 return UNARY_NOT;
2489 case UAdd:
2490 return UNARY_POSITIVE;
2491 case USub:
2492 return UNARY_NEGATIVE;
2493 default:
2494 PyErr_Format(PyExc_SystemError,
2495 "unary op %d should not be possible", op);
2496 return 0;
2497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498}
2499
2500static int
2501binop(struct compiler *c, operator_ty op)
2502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 switch (op) {
2504 case Add:
2505 return BINARY_ADD;
2506 case Sub:
2507 return BINARY_SUBTRACT;
2508 case Mult:
2509 return BINARY_MULTIPLY;
2510 case Div:
2511 return BINARY_TRUE_DIVIDE;
2512 case Mod:
2513 return BINARY_MODULO;
2514 case Pow:
2515 return BINARY_POWER;
2516 case LShift:
2517 return BINARY_LSHIFT;
2518 case RShift:
2519 return BINARY_RSHIFT;
2520 case BitOr:
2521 return BINARY_OR;
2522 case BitXor:
2523 return BINARY_XOR;
2524 case BitAnd:
2525 return BINARY_AND;
2526 case FloorDiv:
2527 return BINARY_FLOOR_DIVIDE;
2528 default:
2529 PyErr_Format(PyExc_SystemError,
2530 "binary op %d should not be possible", op);
2531 return 0;
2532 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533}
2534
2535static int
2536cmpop(cmpop_ty op)
2537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 switch (op) {
2539 case Eq:
2540 return PyCmp_EQ;
2541 case NotEq:
2542 return PyCmp_NE;
2543 case Lt:
2544 return PyCmp_LT;
2545 case LtE:
2546 return PyCmp_LE;
2547 case Gt:
2548 return PyCmp_GT;
2549 case GtE:
2550 return PyCmp_GE;
2551 case Is:
2552 return PyCmp_IS;
2553 case IsNot:
2554 return PyCmp_IS_NOT;
2555 case In:
2556 return PyCmp_IN;
2557 case NotIn:
2558 return PyCmp_NOT_IN;
2559 default:
2560 return PyCmp_BAD;
2561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562}
2563
2564static int
2565inplace_binop(struct compiler *c, operator_ty op)
2566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 switch (op) {
2568 case Add:
2569 return INPLACE_ADD;
2570 case Sub:
2571 return INPLACE_SUBTRACT;
2572 case Mult:
2573 return INPLACE_MULTIPLY;
2574 case Div:
2575 return INPLACE_TRUE_DIVIDE;
2576 case Mod:
2577 return INPLACE_MODULO;
2578 case Pow:
2579 return INPLACE_POWER;
2580 case LShift:
2581 return INPLACE_LSHIFT;
2582 case RShift:
2583 return INPLACE_RSHIFT;
2584 case BitOr:
2585 return INPLACE_OR;
2586 case BitXor:
2587 return INPLACE_XOR;
2588 case BitAnd:
2589 return INPLACE_AND;
2590 case FloorDiv:
2591 return INPLACE_FLOOR_DIVIDE;
2592 default:
2593 PyErr_Format(PyExc_SystemError,
2594 "inplace binary op %d should not be possible", op);
2595 return 0;
2596 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597}
2598
2599static int
2600compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 int op, scope, arg;
2603 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 PyObject *dict = c->u->u_names;
2606 PyObject *mangled;
2607 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 mangled = _Py_Mangle(c->u->u_private, name);
2610 if (!mangled)
2611 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 op = 0;
2614 optype = OP_NAME;
2615 scope = PyST_GetScope(c->u->u_ste, mangled);
2616 switch (scope) {
2617 case FREE:
2618 dict = c->u->u_freevars;
2619 optype = OP_DEREF;
2620 break;
2621 case CELL:
2622 dict = c->u->u_cellvars;
2623 optype = OP_DEREF;
2624 break;
2625 case LOCAL:
2626 if (c->u->u_ste->ste_type == FunctionBlock)
2627 optype = OP_FAST;
2628 break;
2629 case GLOBAL_IMPLICIT:
2630 if (c->u->u_ste->ste_type == FunctionBlock &&
2631 !c->u->u_ste->ste_unoptimized)
2632 optype = OP_GLOBAL;
2633 break;
2634 case GLOBAL_EXPLICIT:
2635 optype = OP_GLOBAL;
2636 break;
2637 default:
2638 /* scope can be 0 */
2639 break;
2640 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002643 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 switch (optype) {
2646 case OP_DEREF:
2647 switch (ctx) {
2648 case Load: op = LOAD_DEREF; break;
2649 case Store: op = STORE_DEREF; break;
2650 case AugLoad:
2651 case AugStore:
2652 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002653 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 case Param:
2655 default:
2656 PyErr_SetString(PyExc_SystemError,
2657 "param invalid for deref variable");
2658 return 0;
2659 }
2660 break;
2661 case OP_FAST:
2662 switch (ctx) {
2663 case Load: op = LOAD_FAST; break;
2664 case Store: op = STORE_FAST; break;
2665 case Del: op = DELETE_FAST; break;
2666 case AugLoad:
2667 case AugStore:
2668 break;
2669 case Param:
2670 default:
2671 PyErr_SetString(PyExc_SystemError,
2672 "param invalid for local variable");
2673 return 0;
2674 }
2675 ADDOP_O(c, op, mangled, varnames);
2676 Py_DECREF(mangled);
2677 return 1;
2678 case OP_GLOBAL:
2679 switch (ctx) {
2680 case Load: op = LOAD_GLOBAL; break;
2681 case Store: op = STORE_GLOBAL; break;
2682 case Del: op = DELETE_GLOBAL; break;
2683 case AugLoad:
2684 case AugStore:
2685 break;
2686 case Param:
2687 default:
2688 PyErr_SetString(PyExc_SystemError,
2689 "param invalid for global variable");
2690 return 0;
2691 }
2692 break;
2693 case OP_NAME:
2694 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002695 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 case Store: op = STORE_NAME; break;
2697 case Del: op = DELETE_NAME; break;
2698 case AugLoad:
2699 case AugStore:
2700 break;
2701 case Param:
2702 default:
2703 PyErr_SetString(PyExc_SystemError,
2704 "param invalid for name variable");
2705 return 0;
2706 }
2707 break;
2708 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 assert(op);
2711 arg = compiler_add_o(c, dict, mangled);
2712 Py_DECREF(mangled);
2713 if (arg < 0)
2714 return 0;
2715 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716}
2717
2718static int
2719compiler_boolop(struct compiler *c, expr_ty e)
2720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 basicblock *end;
2722 int jumpi, i, n;
2723 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 assert(e->kind == BoolOp_kind);
2726 if (e->v.BoolOp.op == And)
2727 jumpi = JUMP_IF_FALSE_OR_POP;
2728 else
2729 jumpi = JUMP_IF_TRUE_OR_POP;
2730 end = compiler_new_block(c);
2731 if (end == NULL)
2732 return 0;
2733 s = e->v.BoolOp.values;
2734 n = asdl_seq_LEN(s) - 1;
2735 assert(n >= 0);
2736 for (i = 0; i < n; ++i) {
2737 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2738 ADDOP_JABS(c, jumpi, end);
2739 }
2740 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2741 compiler_use_next_block(c, end);
2742 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743}
2744
2745static int
2746compiler_list(struct compiler *c, expr_ty e)
2747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 int n = asdl_seq_LEN(e->v.List.elts);
2749 if (e->v.List.ctx == Store) {
2750 int i, seen_star = 0;
2751 for (i = 0; i < n; i++) {
2752 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2753 if (elt->kind == Starred_kind && !seen_star) {
2754 if ((i >= (1 << 8)) ||
2755 (n-i-1 >= (INT_MAX >> 8)))
2756 return compiler_error(c,
2757 "too many expressions in "
2758 "star-unpacking assignment");
2759 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2760 seen_star = 1;
2761 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2762 } else if (elt->kind == Starred_kind) {
2763 return compiler_error(c,
2764 "two starred expressions in assignment");
2765 }
2766 }
2767 if (!seen_star) {
2768 ADDOP_I(c, UNPACK_SEQUENCE, n);
2769 }
2770 }
2771 VISIT_SEQ(c, expr, e->v.List.elts);
2772 if (e->v.List.ctx == Load) {
2773 ADDOP_I(c, BUILD_LIST, n);
2774 }
2775 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776}
2777
2778static int
2779compiler_tuple(struct compiler *c, expr_ty e)
2780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 int n = asdl_seq_LEN(e->v.Tuple.elts);
2782 if (e->v.Tuple.ctx == Store) {
2783 int i, seen_star = 0;
2784 for (i = 0; i < n; i++) {
2785 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2786 if (elt->kind == Starred_kind && !seen_star) {
2787 if ((i >= (1 << 8)) ||
2788 (n-i-1 >= (INT_MAX >> 8)))
2789 return compiler_error(c,
2790 "too many expressions in "
2791 "star-unpacking assignment");
2792 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2793 seen_star = 1;
2794 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2795 } else if (elt->kind == Starred_kind) {
2796 return compiler_error(c,
2797 "two starred expressions in assignment");
2798 }
2799 }
2800 if (!seen_star) {
2801 ADDOP_I(c, UNPACK_SEQUENCE, n);
2802 }
2803 }
2804 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2805 if (e->v.Tuple.ctx == Load) {
2806 ADDOP_I(c, BUILD_TUPLE, n);
2807 }
2808 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809}
2810
2811static int
2812compiler_compare(struct compiler *c, expr_ty e)
2813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 int i, n;
2815 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2818 VISIT(c, expr, e->v.Compare.left);
2819 n = asdl_seq_LEN(e->v.Compare.ops);
2820 assert(n > 0);
2821 if (n > 1) {
2822 cleanup = compiler_new_block(c);
2823 if (cleanup == NULL)
2824 return 0;
2825 VISIT(c, expr,
2826 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2827 }
2828 for (i = 1; i < n; i++) {
2829 ADDOP(c, DUP_TOP);
2830 ADDOP(c, ROT_THREE);
2831 ADDOP_I(c, COMPARE_OP,
2832 cmpop((cmpop_ty)(asdl_seq_GET(
2833 e->v.Compare.ops, i - 1))));
2834 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2835 NEXT_BLOCK(c);
2836 if (i < (n - 1))
2837 VISIT(c, expr,
2838 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2839 }
2840 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2841 ADDOP_I(c, COMPARE_OP,
2842 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2843 if (n > 1) {
2844 basicblock *end = compiler_new_block(c);
2845 if (end == NULL)
2846 return 0;
2847 ADDOP_JREL(c, JUMP_FORWARD, end);
2848 compiler_use_next_block(c, cleanup);
2849 ADDOP(c, ROT_TWO);
2850 ADDOP(c, POP_TOP);
2851 compiler_use_next_block(c, end);
2852 }
2853 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854}
2855
2856static int
2857compiler_call(struct compiler *c, expr_ty e)
2858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 VISIT(c, expr, e->v.Call.func);
2860 return compiler_call_helper(c, 0,
2861 e->v.Call.args,
2862 e->v.Call.keywords,
2863 e->v.Call.starargs,
2864 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002865}
2866
2867/* shared code between compiler_call and compiler_class */
2868static int
2869compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 int n, /* Args already pushed */
2871 asdl_seq *args,
2872 asdl_seq *keywords,
2873 expr_ty starargs,
2874 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 n += asdl_seq_LEN(args);
2879 VISIT_SEQ(c, expr, args);
2880 if (keywords) {
2881 VISIT_SEQ(c, keyword, keywords);
2882 n |= asdl_seq_LEN(keywords) << 8;
2883 }
2884 if (starargs) {
2885 VISIT(c, expr, starargs);
2886 code |= 1;
2887 }
2888 if (kwargs) {
2889 VISIT(c, expr, kwargs);
2890 code |= 2;
2891 }
2892 switch (code) {
2893 case 0:
2894 ADDOP_I(c, CALL_FUNCTION, n);
2895 break;
2896 case 1:
2897 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2898 break;
2899 case 2:
2900 ADDOP_I(c, CALL_FUNCTION_KW, n);
2901 break;
2902 case 3:
2903 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2904 break;
2905 }
2906 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907}
2908
Nick Coghlan650f0d02007-04-15 12:05:43 +00002909
2910/* List and set comprehensions and generator expressions work by creating a
2911 nested function to perform the actual iteration. This means that the
2912 iteration variables don't leak into the current scope.
2913 The defined function is called immediately following its definition, with the
2914 result of that call being the result of the expression.
2915 The LC/SC version returns the populated container, while the GE version is
2916 flagged in symtable.c as a generator, so it returns the generator object
2917 when the function is called.
2918 This code *knows* that the loop cannot contain break, continue, or return,
2919 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2920
2921 Possible cleanups:
2922 - iterate over the generator sequence instead of using recursion
2923*/
2924
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926compiler_comprehension_generator(struct compiler *c,
2927 asdl_seq *generators, int gen_index,
2928 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 /* generate code for the iterator, then each of the ifs,
2931 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 comprehension_ty gen;
2934 basicblock *start, *anchor, *skip, *if_cleanup;
2935 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 start = compiler_new_block(c);
2938 skip = compiler_new_block(c);
2939 if_cleanup = compiler_new_block(c);
2940 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2943 anchor == NULL)
2944 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 if (gen_index == 0) {
2949 /* Receive outermost iter as an implicit argument */
2950 c->u->u_argcount = 1;
2951 ADDOP_I(c, LOAD_FAST, 0);
2952 }
2953 else {
2954 /* Sub-iter - calculate on the fly */
2955 VISIT(c, expr, gen->iter);
2956 ADDOP(c, GET_ITER);
2957 }
2958 compiler_use_next_block(c, start);
2959 ADDOP_JREL(c, FOR_ITER, anchor);
2960 NEXT_BLOCK(c);
2961 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 /* XXX this needs to be cleaned up...a lot! */
2964 n = asdl_seq_LEN(gen->ifs);
2965 for (i = 0; i < n; i++) {
2966 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2967 VISIT(c, expr, e);
2968 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2969 NEXT_BLOCK(c);
2970 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 if (++gen_index < asdl_seq_LEN(generators))
2973 if (!compiler_comprehension_generator(c,
2974 generators, gen_index,
2975 elt, val, type))
2976 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 /* only append after the last for generator */
2979 if (gen_index >= asdl_seq_LEN(generators)) {
2980 /* comprehension specific code */
2981 switch (type) {
2982 case COMP_GENEXP:
2983 VISIT(c, expr, elt);
2984 ADDOP(c, YIELD_VALUE);
2985 ADDOP(c, POP_TOP);
2986 break;
2987 case COMP_LISTCOMP:
2988 VISIT(c, expr, elt);
2989 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2990 break;
2991 case COMP_SETCOMP:
2992 VISIT(c, expr, elt);
2993 ADDOP_I(c, SET_ADD, gen_index + 1);
2994 break;
2995 case COMP_DICTCOMP:
2996 /* With 'd[k] = v', v is evaluated before k, so we do
2997 the same. */
2998 VISIT(c, expr, val);
2999 VISIT(c, expr, elt);
3000 ADDOP_I(c, MAP_ADD, gen_index + 1);
3001 break;
3002 default:
3003 return 0;
3004 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 compiler_use_next_block(c, skip);
3007 }
3008 compiler_use_next_block(c, if_cleanup);
3009 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3010 compiler_use_next_block(c, anchor);
3011
3012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013}
3014
3015static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003016compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 PyCodeObject *co = NULL;
3020 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003021 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 outermost_iter = ((comprehension_ty)
3024 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003025
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003026 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3027 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 if (type != COMP_GENEXP) {
3031 int op;
3032 switch (type) {
3033 case COMP_LISTCOMP:
3034 op = BUILD_LIST;
3035 break;
3036 case COMP_SETCOMP:
3037 op = BUILD_SET;
3038 break;
3039 case COMP_DICTCOMP:
3040 op = BUILD_MAP;
3041 break;
3042 default:
3043 PyErr_Format(PyExc_SystemError,
3044 "unknown comprehension type %d", type);
3045 goto error_in_scope;
3046 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 ADDOP_I(c, op, 0);
3049 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (!compiler_comprehension_generator(c, generators, 0, elt,
3052 val, type))
3053 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 if (type != COMP_GENEXP) {
3056 ADDOP(c, RETURN_VALUE);
3057 }
3058
3059 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003060 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003062 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 goto error;
3064
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003065 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003067 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 Py_DECREF(co);
3069
3070 VISIT(c, expr, outermost_iter);
3071 ADDOP(c, GET_ITER);
3072 ADDOP_I(c, CALL_FUNCTION, 1);
3073 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003074error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003076error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003077 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 Py_XDECREF(co);
3079 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003080}
3081
3082static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083compiler_genexp(struct compiler *c, expr_ty e)
3084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 static identifier name;
3086 if (!name) {
3087 name = PyUnicode_FromString("<genexpr>");
3088 if (!name)
3089 return 0;
3090 }
3091 assert(e->kind == GeneratorExp_kind);
3092 return compiler_comprehension(c, e, COMP_GENEXP, name,
3093 e->v.GeneratorExp.generators,
3094 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095}
3096
3097static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003098compiler_listcomp(struct compiler *c, expr_ty e)
3099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 static identifier name;
3101 if (!name) {
3102 name = PyUnicode_FromString("<listcomp>");
3103 if (!name)
3104 return 0;
3105 }
3106 assert(e->kind == ListComp_kind);
3107 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3108 e->v.ListComp.generators,
3109 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003110}
3111
3112static int
3113compiler_setcomp(struct compiler *c, expr_ty e)
3114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 static identifier name;
3116 if (!name) {
3117 name = PyUnicode_FromString("<setcomp>");
3118 if (!name)
3119 return 0;
3120 }
3121 assert(e->kind == SetComp_kind);
3122 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3123 e->v.SetComp.generators,
3124 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003125}
3126
3127
3128static int
3129compiler_dictcomp(struct compiler *c, expr_ty e)
3130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 static identifier name;
3132 if (!name) {
3133 name = PyUnicode_FromString("<dictcomp>");
3134 if (!name)
3135 return 0;
3136 }
3137 assert(e->kind == DictComp_kind);
3138 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3139 e->v.DictComp.generators,
3140 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003141}
3142
3143
3144static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145compiler_visit_keyword(struct compiler *c, keyword_ty k)
3146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3148 VISIT(c, expr, k->value);
3149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150}
3151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003153 whether they are true or false.
3154
3155 Return values: 1 for true, 0 for false, -1 for non-constant.
3156 */
3157
3158static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003159expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 char *id;
3162 switch (e->kind) {
3163 case Ellipsis_kind:
3164 return 1;
3165 case Num_kind:
3166 return PyObject_IsTrue(e->v.Num.n);
3167 case Str_kind:
3168 return PyObject_IsTrue(e->v.Str.s);
3169 case Name_kind:
3170 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003171 id = PyUnicode_AsUTF8(e->v.Name.id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 if (strcmp(id, "True") == 0) return 1;
3173 if (strcmp(id, "False") == 0) return 0;
3174 if (strcmp(id, "None") == 0) return 0;
3175 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003176 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 /* fall through */
3178 default:
3179 return -1;
3180 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181}
3182
Guido van Rossumc2e20742006-02-27 22:32:47 +00003183/*
3184 Implements the with statement from PEP 343.
3185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003187
3188 with EXPR as VAR:
3189 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190
Guido van Rossumc2e20742006-02-27 22:32:47 +00003191 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192
Thomas Wouters477c8d52006-05-27 19:21:47 +00003193 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003194 exit = context.__exit__ # not calling it
3195 value = context.__enter__()
3196 try:
3197 VAR = value # if VAR present in the syntax
3198 BLOCK
3199 finally:
3200 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003202 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003204 exit(*exc)
3205 */
3206static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003207compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003208{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003209 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003210 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003211
3212 assert(s->kind == With_kind);
3213
Guido van Rossumc2e20742006-02-27 22:32:47 +00003214 block = compiler_new_block(c);
3215 finally = compiler_new_block(c);
3216 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003217 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003218
Thomas Wouters477c8d52006-05-27 19:21:47 +00003219 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003220 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003221 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003222
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003223 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003224 compiler_use_next_block(c, block);
3225 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003226 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003227 }
3228
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003229 if (item->optional_vars) {
3230 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003231 }
3232 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003234 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003235 }
3236
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003237 pos++;
3238 if (pos == asdl_seq_LEN(s->v.With.items))
3239 /* BLOCK code */
3240 VISIT_SEQ(c, stmt, s->v.With.body)
3241 else if (!compiler_with(c, s, pos))
3242 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003243
3244 /* End of try block; start the finally block */
3245 ADDOP(c, POP_BLOCK);
3246 compiler_pop_fblock(c, FINALLY_TRY, block);
3247
3248 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3249 compiler_use_next_block(c, finally);
3250 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003251 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003252
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003253 /* Finally block starts; context.__exit__ is on the stack under
3254 the exception or return information. Just issue our magic
3255 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003256 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003257
3258 /* Finally block ends. */
3259 ADDOP(c, END_FINALLY);
3260 compiler_pop_fblock(c, FINALLY_END, finally);
3261 return 1;
3262}
3263
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264static int
3265compiler_visit_expr(struct compiler *c, expr_ty e)
3266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 /* If expr e has a different line number than the last expr/stmt,
3270 set a new line number for the next instruction.
3271 */
3272 if (e->lineno > c->u->u_lineno) {
3273 c->u->u_lineno = e->lineno;
3274 c->u->u_lineno_set = 0;
3275 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003276 /* Updating the column offset is always harmless. */
3277 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 switch (e->kind) {
3279 case BoolOp_kind:
3280 return compiler_boolop(c, e);
3281 case BinOp_kind:
3282 VISIT(c, expr, e->v.BinOp.left);
3283 VISIT(c, expr, e->v.BinOp.right);
3284 ADDOP(c, binop(c, e->v.BinOp.op));
3285 break;
3286 case UnaryOp_kind:
3287 VISIT(c, expr, e->v.UnaryOp.operand);
3288 ADDOP(c, unaryop(e->v.UnaryOp.op));
3289 break;
3290 case Lambda_kind:
3291 return compiler_lambda(c, e);
3292 case IfExp_kind:
3293 return compiler_ifexp(c, e);
3294 case Dict_kind:
3295 n = asdl_seq_LEN(e->v.Dict.values);
3296 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3297 for (i = 0; i < n; i++) {
3298 VISIT(c, expr,
3299 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3300 VISIT(c, expr,
3301 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3302 ADDOP(c, STORE_MAP);
3303 }
3304 break;
3305 case Set_kind:
3306 n = asdl_seq_LEN(e->v.Set.elts);
3307 VISIT_SEQ(c, expr, e->v.Set.elts);
3308 ADDOP_I(c, BUILD_SET, n);
3309 break;
3310 case GeneratorExp_kind:
3311 return compiler_genexp(c, e);
3312 case ListComp_kind:
3313 return compiler_listcomp(c, e);
3314 case SetComp_kind:
3315 return compiler_setcomp(c, e);
3316 case DictComp_kind:
3317 return compiler_dictcomp(c, e);
3318 case Yield_kind:
Benjamin Peterson527c6222012-01-14 08:58:23 -05003319 case YieldFrom_kind: {
3320 expr_ty value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 if (c->u->u_ste->ste_type != FunctionBlock)
3322 return compiler_error(c, "'yield' outside function");
Benjamin Peterson527c6222012-01-14 08:58:23 -05003323 value = (e->kind == YieldFrom_kind) ? e->v.YieldFrom.value : e->v.Yield.value;
3324 if (value) {
3325 VISIT(c, expr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 }
3327 else {
3328 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3329 }
Benjamin Peterson527c6222012-01-14 08:58:23 -05003330 if (e->kind == YieldFrom_kind) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05003331 ADDOP(c, GET_ITER);
3332 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Nick Coghlan1f7ce622012-01-13 21:43:40 +10003333 ADDOP(c, YIELD_FROM);
3334 }
3335 else {
3336 ADDOP(c, YIELD_VALUE);
3337 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 break;
Benjamin Peterson527c6222012-01-14 08:58:23 -05003339 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 case Compare_kind:
3341 return compiler_compare(c, e);
3342 case Call_kind:
3343 return compiler_call(c, e);
3344 case Num_kind:
3345 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3346 break;
3347 case Str_kind:
3348 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3349 break;
3350 case Bytes_kind:
3351 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3352 break;
3353 case Ellipsis_kind:
3354 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3355 break;
3356 /* The following exprs can be assignment targets. */
3357 case Attribute_kind:
3358 if (e->v.Attribute.ctx != AugStore)
3359 VISIT(c, expr, e->v.Attribute.value);
3360 switch (e->v.Attribute.ctx) {
3361 case AugLoad:
3362 ADDOP(c, DUP_TOP);
3363 /* Fall through to load */
3364 case Load:
3365 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3366 break;
3367 case AugStore:
3368 ADDOP(c, ROT_TWO);
3369 /* Fall through to save */
3370 case Store:
3371 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3372 break;
3373 case Del:
3374 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3375 break;
3376 case Param:
3377 default:
3378 PyErr_SetString(PyExc_SystemError,
3379 "param invalid in attribute expression");
3380 return 0;
3381 }
3382 break;
3383 case Subscript_kind:
3384 switch (e->v.Subscript.ctx) {
3385 case AugLoad:
3386 VISIT(c, expr, e->v.Subscript.value);
3387 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3388 break;
3389 case Load:
3390 VISIT(c, expr, e->v.Subscript.value);
3391 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3392 break;
3393 case AugStore:
3394 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3395 break;
3396 case Store:
3397 VISIT(c, expr, e->v.Subscript.value);
3398 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3399 break;
3400 case Del:
3401 VISIT(c, expr, e->v.Subscript.value);
3402 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3403 break;
3404 case Param:
3405 default:
3406 PyErr_SetString(PyExc_SystemError,
3407 "param invalid in subscript expression");
3408 return 0;
3409 }
3410 break;
3411 case Starred_kind:
3412 switch (e->v.Starred.ctx) {
3413 case Store:
3414 /* In all legitimate cases, the Starred node was already replaced
3415 * by compiler_list/compiler_tuple. XXX: is that okay? */
3416 return compiler_error(c,
3417 "starred assignment target must be in a list or tuple");
3418 default:
3419 return compiler_error(c,
3420 "can use starred expression only as assignment target");
3421 }
3422 break;
3423 case Name_kind:
3424 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3425 /* child nodes of List and Tuple will have expr_context set */
3426 case List_kind:
3427 return compiler_list(c, e);
3428 case Tuple_kind:
3429 return compiler_tuple(c, e);
3430 }
3431 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432}
3433
3434static int
3435compiler_augassign(struct compiler *c, stmt_ty s)
3436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 expr_ty e = s->v.AugAssign.target;
3438 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 switch (e->kind) {
3443 case Attribute_kind:
3444 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3445 AugLoad, e->lineno, e->col_offset, c->c_arena);
3446 if (auge == NULL)
3447 return 0;
3448 VISIT(c, expr, auge);
3449 VISIT(c, expr, s->v.AugAssign.value);
3450 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3451 auge->v.Attribute.ctx = AugStore;
3452 VISIT(c, expr, auge);
3453 break;
3454 case Subscript_kind:
3455 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3456 AugLoad, e->lineno, e->col_offset, c->c_arena);
3457 if (auge == NULL)
3458 return 0;
3459 VISIT(c, expr, auge);
3460 VISIT(c, expr, s->v.AugAssign.value);
3461 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3462 auge->v.Subscript.ctx = AugStore;
3463 VISIT(c, expr, auge);
3464 break;
3465 case Name_kind:
3466 if (!compiler_nameop(c, e->v.Name.id, Load))
3467 return 0;
3468 VISIT(c, expr, s->v.AugAssign.value);
3469 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3470 return compiler_nameop(c, e->v.Name.id, Store);
3471 default:
3472 PyErr_Format(PyExc_SystemError,
3473 "invalid node type (%d) for augmented assignment",
3474 e->kind);
3475 return 0;
3476 }
3477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478}
3479
3480static int
3481compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 struct fblockinfo *f;
3484 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3485 PyErr_SetString(PyExc_SystemError,
3486 "too many statically nested blocks");
3487 return 0;
3488 }
3489 f = &c->u->u_fblock[c->u->u_nfblocks++];
3490 f->fb_type = t;
3491 f->fb_block = b;
3492 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493}
3494
3495static void
3496compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 struct compiler_unit *u = c->u;
3499 assert(u->u_nfblocks > 0);
3500 u->u_nfblocks--;
3501 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3502 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503}
3504
Thomas Wouters89f507f2006-12-13 04:49:30 +00003505static int
3506compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 int i;
3508 struct compiler_unit *u = c->u;
3509 for (i = 0; i < u->u_nfblocks; ++i) {
3510 if (u->u_fblock[i].fb_type == LOOP)
3511 return 1;
3512 }
3513 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003514}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515/* Raises a SyntaxError and returns 0.
3516 If something goes wrong, a different exception may be raised.
3517*/
3518
3519static int
3520compiler_error(struct compiler *c, const char *errstr)
3521{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003522 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3526 if (!loc) {
3527 Py_INCREF(Py_None);
3528 loc = Py_None;
3529 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003530 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003531 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 if (!u)
3533 goto exit;
3534 v = Py_BuildValue("(zO)", errstr, u);
3535 if (!v)
3536 goto exit;
3537 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 Py_DECREF(loc);
3540 Py_XDECREF(u);
3541 Py_XDECREF(v);
3542 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543}
3544
3545static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546compiler_handle_subscr(struct compiler *c, const char *kind,
3547 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 /* XXX this code is duplicated */
3552 switch (ctx) {
3553 case AugLoad: /* fall through to Load */
3554 case Load: op = BINARY_SUBSCR; break;
3555 case AugStore:/* fall through to Store */
3556 case Store: op = STORE_SUBSCR; break;
3557 case Del: op = DELETE_SUBSCR; break;
3558 case Param:
3559 PyErr_Format(PyExc_SystemError,
3560 "invalid %s kind %d in subscript\n",
3561 kind, ctx);
3562 return 0;
3563 }
3564 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003565 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 }
3567 else if (ctx == AugStore) {
3568 ADDOP(c, ROT_THREE);
3569 }
3570 ADDOP(c, op);
3571 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572}
3573
3574static int
3575compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 int n = 2;
3578 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 /* only handles the cases where BUILD_SLICE is emitted */
3581 if (s->v.Slice.lower) {
3582 VISIT(c, expr, s->v.Slice.lower);
3583 }
3584 else {
3585 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3586 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 if (s->v.Slice.upper) {
3589 VISIT(c, expr, s->v.Slice.upper);
3590 }
3591 else {
3592 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3593 }
3594
3595 if (s->v.Slice.step) {
3596 n++;
3597 VISIT(c, expr, s->v.Slice.step);
3598 }
3599 ADDOP_I(c, BUILD_SLICE, n);
3600 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601}
3602
3603static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3605 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 switch (s->kind) {
3608 case Slice_kind:
3609 return compiler_slice(c, s, ctx);
3610 case Index_kind:
3611 VISIT(c, expr, s->v.Index.value);
3612 break;
3613 case ExtSlice_kind:
3614 default:
3615 PyErr_SetString(PyExc_SystemError,
3616 "extended slice invalid in nested slice");
3617 return 0;
3618 }
3619 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620}
3621
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622static int
3623compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 char * kindname = NULL;
3626 switch (s->kind) {
3627 case Index_kind:
3628 kindname = "index";
3629 if (ctx != AugStore) {
3630 VISIT(c, expr, s->v.Index.value);
3631 }
3632 break;
3633 case Slice_kind:
3634 kindname = "slice";
3635 if (ctx != AugStore) {
3636 if (!compiler_slice(c, s, ctx))
3637 return 0;
3638 }
3639 break;
3640 case ExtSlice_kind:
3641 kindname = "extended slice";
3642 if (ctx != AugStore) {
3643 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3644 for (i = 0; i < n; i++) {
3645 slice_ty sub = (slice_ty)asdl_seq_GET(
3646 s->v.ExtSlice.dims, i);
3647 if (!compiler_visit_nested_slice(c, sub, ctx))
3648 return 0;
3649 }
3650 ADDOP_I(c, BUILD_TUPLE, n);
3651 }
3652 break;
3653 default:
3654 PyErr_Format(PyExc_SystemError,
3655 "invalid subscript kind %d", s->kind);
3656 return 0;
3657 }
3658 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659}
3660
Thomas Wouters89f507f2006-12-13 04:49:30 +00003661/* End of the compiler section, beginning of the assembler section */
3662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663/* do depth-first search of basic block graph, starting with block.
3664 post records the block indices in post-order.
3665
3666 XXX must handle implicit jumps from one block to next
3667*/
3668
Thomas Wouters89f507f2006-12-13 04:49:30 +00003669struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 PyObject *a_bytecode; /* string containing bytecode */
3671 int a_offset; /* offset into bytecode */
3672 int a_nblocks; /* number of reachable blocks */
3673 basicblock **a_postorder; /* list of blocks in dfs postorder */
3674 PyObject *a_lnotab; /* string containing lnotab */
3675 int a_lnotab_off; /* offset into lnotab */
3676 int a_lineno; /* last lineno of emitted instruction */
3677 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003678};
3679
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680static void
3681dfs(struct compiler *c, basicblock *b, struct assembler *a)
3682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 int i;
3684 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 if (b->b_seen)
3687 return;
3688 b->b_seen = 1;
3689 if (b->b_next != NULL)
3690 dfs(c, b->b_next, a);
3691 for (i = 0; i < b->b_iused; i++) {
3692 instr = &b->b_instr[i];
3693 if (instr->i_jrel || instr->i_jabs)
3694 dfs(c, instr->i_target, a);
3695 }
3696 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003697}
3698
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003699static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 int i, target_depth;
3703 struct instr *instr;
3704 if (b->b_seen || b->b_startdepth >= depth)
3705 return maxdepth;
3706 b->b_seen = 1;
3707 b->b_startdepth = depth;
3708 for (i = 0; i < b->b_iused; i++) {
3709 instr = &b->b_instr[i];
3710 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3711 if (depth > maxdepth)
3712 maxdepth = depth;
3713 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3714 if (instr->i_jrel || instr->i_jabs) {
3715 target_depth = depth;
3716 if (instr->i_opcode == FOR_ITER) {
3717 target_depth = depth-2;
3718 } else if (instr->i_opcode == SETUP_FINALLY ||
3719 instr->i_opcode == SETUP_EXCEPT) {
3720 target_depth = depth+3;
3721 if (target_depth > maxdepth)
3722 maxdepth = target_depth;
3723 }
3724 maxdepth = stackdepth_walk(c, instr->i_target,
3725 target_depth, maxdepth);
3726 if (instr->i_opcode == JUMP_ABSOLUTE ||
3727 instr->i_opcode == JUMP_FORWARD) {
3728 goto out; /* remaining code is dead */
3729 }
3730 }
3731 }
3732 if (b->b_next)
3733 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 b->b_seen = 0;
3736 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003737}
3738
3739/* Find the flow path that needs the largest stack. We assume that
3740 * cycles in the flow graph have no net effect on the stack depth.
3741 */
3742static int
3743stackdepth(struct compiler *c)
3744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 basicblock *b, *entryblock;
3746 entryblock = NULL;
3747 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3748 b->b_seen = 0;
3749 b->b_startdepth = INT_MIN;
3750 entryblock = b;
3751 }
3752 if (!entryblock)
3753 return 0;
3754 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755}
3756
3757static int
3758assemble_init(struct assembler *a, int nblocks, int firstlineno)
3759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 memset(a, 0, sizeof(struct assembler));
3761 a->a_lineno = firstlineno;
3762 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3763 if (!a->a_bytecode)
3764 return 0;
3765 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3766 if (!a->a_lnotab)
3767 return 0;
3768 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3769 PyErr_NoMemory();
3770 return 0;
3771 }
3772 a->a_postorder = (basicblock **)PyObject_Malloc(
3773 sizeof(basicblock *) * nblocks);
3774 if (!a->a_postorder) {
3775 PyErr_NoMemory();
3776 return 0;
3777 }
3778 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779}
3780
3781static void
3782assemble_free(struct assembler *a)
3783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 Py_XDECREF(a->a_bytecode);
3785 Py_XDECREF(a->a_lnotab);
3786 if (a->a_postorder)
3787 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788}
3789
3790/* Return the size of a basic block in bytes. */
3791
3792static int
3793instrsize(struct instr *instr)
3794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 if (!instr->i_hasarg)
3796 return 1; /* 1 byte for the opcode*/
3797 if (instr->i_oparg > 0xffff)
3798 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3799 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800}
3801
3802static int
3803blocksize(basicblock *b)
3804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 int i;
3806 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 for (i = 0; i < b->b_iused; i++)
3809 size += instrsize(&b->b_instr[i]);
3810 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003811}
3812
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003813/* Appends a pair to the end of the line number table, a_lnotab, representing
3814 the instruction's bytecode offset and line number. See
3815 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003816
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003817static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 int d_bytecode, d_lineno;
3821 int len;
3822 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 d_bytecode = a->a_offset - a->a_lineno_off;
3825 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 assert(d_bytecode >= 0);
3828 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 if(d_bytecode == 0 && d_lineno == 0)
3831 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 if (d_bytecode > 255) {
3834 int j, nbytes, ncodes = d_bytecode / 255;
3835 nbytes = a->a_lnotab_off + 2 * ncodes;
3836 len = PyBytes_GET_SIZE(a->a_lnotab);
3837 if (nbytes >= len) {
3838 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3839 len = nbytes;
3840 else if (len <= INT_MAX / 2)
3841 len *= 2;
3842 else {
3843 PyErr_NoMemory();
3844 return 0;
3845 }
3846 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3847 return 0;
3848 }
3849 lnotab = (unsigned char *)
3850 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3851 for (j = 0; j < ncodes; j++) {
3852 *lnotab++ = 255;
3853 *lnotab++ = 0;
3854 }
3855 d_bytecode -= ncodes * 255;
3856 a->a_lnotab_off += ncodes * 2;
3857 }
3858 assert(d_bytecode <= 255);
3859 if (d_lineno > 255) {
3860 int j, nbytes, ncodes = d_lineno / 255;
3861 nbytes = a->a_lnotab_off + 2 * ncodes;
3862 len = PyBytes_GET_SIZE(a->a_lnotab);
3863 if (nbytes >= len) {
3864 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3865 len = nbytes;
3866 else if (len <= INT_MAX / 2)
3867 len *= 2;
3868 else {
3869 PyErr_NoMemory();
3870 return 0;
3871 }
3872 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3873 return 0;
3874 }
3875 lnotab = (unsigned char *)
3876 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3877 *lnotab++ = d_bytecode;
3878 *lnotab++ = 255;
3879 d_bytecode = 0;
3880 for (j = 1; j < ncodes; j++) {
3881 *lnotab++ = 0;
3882 *lnotab++ = 255;
3883 }
3884 d_lineno -= ncodes * 255;
3885 a->a_lnotab_off += ncodes * 2;
3886 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 len = PyBytes_GET_SIZE(a->a_lnotab);
3889 if (a->a_lnotab_off + 2 >= len) {
3890 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3891 return 0;
3892 }
3893 lnotab = (unsigned char *)
3894 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 a->a_lnotab_off += 2;
3897 if (d_bytecode) {
3898 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003899 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 }
3901 else { /* First line of a block; def stmt, etc. */
3902 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003903 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 }
3905 a->a_lineno = i->i_lineno;
3906 a->a_lineno_off = a->a_offset;
3907 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003908}
3909
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910/* assemble_emit()
3911 Extend the bytecode with a new instruction.
3912 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003913*/
3914
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003915static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 int size, arg = 0, ext = 0;
3919 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3920 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 size = instrsize(i);
3923 if (i->i_hasarg) {
3924 arg = i->i_oparg;
3925 ext = arg >> 16;
3926 }
3927 if (i->i_lineno && !assemble_lnotab(a, i))
3928 return 0;
3929 if (a->a_offset + size >= len) {
3930 if (len > PY_SSIZE_T_MAX / 2)
3931 return 0;
3932 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3933 return 0;
3934 }
3935 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3936 a->a_offset += size;
3937 if (size == 6) {
3938 assert(i->i_hasarg);
3939 *code++ = (char)EXTENDED_ARG;
3940 *code++ = ext & 0xff;
3941 *code++ = ext >> 8;
3942 arg &= 0xffff;
3943 }
3944 *code++ = i->i_opcode;
3945 if (i->i_hasarg) {
3946 assert(size == 3 || size == 6);
3947 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003948 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 }
3950 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003951}
3952
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003953static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003954assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 basicblock *b;
3957 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3958 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 /* Compute the size of each block and fixup jump args.
3961 Replace block pointer with position in bytecode. */
3962 do {
3963 totsize = 0;
3964 for (i = a->a_nblocks - 1; i >= 0; i--) {
3965 b = a->a_postorder[i];
3966 bsize = blocksize(b);
3967 b->b_offset = totsize;
3968 totsize += bsize;
3969 }
3970 last_extended_arg_count = extended_arg_count;
3971 extended_arg_count = 0;
3972 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3973 bsize = b->b_offset;
3974 for (i = 0; i < b->b_iused; i++) {
3975 struct instr *instr = &b->b_instr[i];
3976 /* Relative jumps are computed relative to
3977 the instruction pointer after fetching
3978 the jump instruction.
3979 */
3980 bsize += instrsize(instr);
3981 if (instr->i_jabs)
3982 instr->i_oparg = instr->i_target->b_offset;
3983 else if (instr->i_jrel) {
3984 int delta = instr->i_target->b_offset - bsize;
3985 instr->i_oparg = delta;
3986 }
3987 else
3988 continue;
3989 if (instr->i_oparg > 0xffff)
3990 extended_arg_count++;
3991 }
3992 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 /* XXX: This is an awful hack that could hurt performance, but
3995 on the bright side it should work until we come up
3996 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 The issue is that in the first loop blocksize() is called
3999 which calls instrsize() which requires i_oparg be set
4000 appropriately. There is a bootstrap problem because
4001 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 So we loop until we stop seeing new EXTENDED_ARGs.
4004 The only EXTENDED_ARGs that could be popping up are
4005 ones in jump instructions. So this should converge
4006 fairly quickly.
4007 */
4008 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004009}
4010
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004011static PyObject *
4012dict_keys_inorder(PyObject *dict, int offset)
4013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 PyObject *tuple, *k, *v;
4015 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 tuple = PyTuple_New(size);
4018 if (tuple == NULL)
4019 return NULL;
4020 while (PyDict_Next(dict, &pos, &k, &v)) {
4021 i = PyLong_AS_LONG(v);
4022 /* The keys of the dictionary are tuples. (see compiler_add_o)
4023 The object we want is always first, though. */
4024 k = PyTuple_GET_ITEM(k, 0);
4025 Py_INCREF(k);
4026 assert((i - offset) < size);
4027 assert((i - offset) >= 0);
4028 PyTuple_SET_ITEM(tuple, i - offset, k);
4029 }
4030 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004031}
4032
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004033static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004034compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 PySTEntryObject *ste = c->u->u_ste;
4037 int flags = 0, n;
4038 if (ste->ste_type != ModuleBlock)
4039 flags |= CO_NEWLOCALS;
4040 if (ste->ste_type == FunctionBlock) {
4041 if (!ste->ste_unoptimized)
4042 flags |= CO_OPTIMIZED;
4043 if (ste->ste_nested)
4044 flags |= CO_NESTED;
4045 if (ste->ste_generator)
4046 flags |= CO_GENERATOR;
4047 if (ste->ste_varargs)
4048 flags |= CO_VARARGS;
4049 if (ste->ste_varkeywords)
4050 flags |= CO_VARKEYWORDS;
4051 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 /* (Only) inherit compilerflags in PyCF_MASK */
4054 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 n = PyDict_Size(c->u->u_freevars);
4057 if (n < 0)
4058 return -1;
4059 if (n == 0) {
4060 n = PyDict_Size(c->u->u_cellvars);
4061 if (n < 0)
4062 return -1;
4063 if (n == 0) {
4064 flags |= CO_NOFREE;
4065 }
4066 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004069}
4070
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004071static PyCodeObject *
4072makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 PyObject *tmp;
4075 PyCodeObject *co = NULL;
4076 PyObject *consts = NULL;
4077 PyObject *names = NULL;
4078 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 PyObject *name = NULL;
4080 PyObject *freevars = NULL;
4081 PyObject *cellvars = NULL;
4082 PyObject *bytecode = NULL;
4083 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 tmp = dict_keys_inorder(c->u->u_consts, 0);
4086 if (!tmp)
4087 goto error;
4088 consts = PySequence_List(tmp); /* optimize_code requires a list */
4089 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 names = dict_keys_inorder(c->u->u_names, 0);
4092 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4093 if (!consts || !names || !varnames)
4094 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4097 if (!cellvars)
4098 goto error;
4099 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4100 if (!freevars)
4101 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 nlocals = PyDict_Size(c->u->u_varnames);
4103 flags = compute_code_flags(c);
4104 if (flags < 0)
4105 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4108 if (!bytecode)
4109 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4112 if (!tmp)
4113 goto error;
4114 Py_DECREF(consts);
4115 consts = tmp;
4116
4117 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4118 nlocals, stackdepth(c), flags,
4119 bytecode, consts, names, varnames,
4120 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004121 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 c->u->u_firstlineno,
4123 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 Py_XDECREF(consts);
4126 Py_XDECREF(names);
4127 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 Py_XDECREF(name);
4129 Py_XDECREF(freevars);
4130 Py_XDECREF(cellvars);
4131 Py_XDECREF(bytecode);
4132 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004133}
4134
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004135
4136/* For debugging purposes only */
4137#if 0
4138static void
4139dump_instr(const struct instr *i)
4140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 const char *jrel = i->i_jrel ? "jrel " : "";
4142 const char *jabs = i->i_jabs ? "jabs " : "";
4143 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 *arg = '\0';
4146 if (i->i_hasarg)
4147 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4150 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004151}
4152
4153static void
4154dump_basicblock(const basicblock *b)
4155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 const char *seen = b->b_seen ? "seen " : "";
4157 const char *b_return = b->b_return ? "return " : "";
4158 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4159 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4160 if (b->b_instr) {
4161 int i;
4162 for (i = 0; i < b->b_iused; i++) {
4163 fprintf(stderr, " [%02d] ", i);
4164 dump_instr(b->b_instr + i);
4165 }
4166 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004167}
4168#endif
4169
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170static PyCodeObject *
4171assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 basicblock *b, *entryblock;
4174 struct assembler a;
4175 int i, j, nblocks;
4176 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 /* Make sure every block that falls off the end returns None.
4179 XXX NEXT_BLOCK() isn't quite right, because if the last
4180 block ends with a jump or return b_next shouldn't set.
4181 */
4182 if (!c->u->u_curblock->b_return) {
4183 NEXT_BLOCK(c);
4184 if (addNone)
4185 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4186 ADDOP(c, RETURN_VALUE);
4187 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 nblocks = 0;
4190 entryblock = NULL;
4191 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4192 nblocks++;
4193 entryblock = b;
4194 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 /* Set firstlineno if it wasn't explicitly set. */
4197 if (!c->u->u_firstlineno) {
4198 if (entryblock && entryblock->b_instr)
4199 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4200 else
4201 c->u->u_firstlineno = 1;
4202 }
4203 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4204 goto error;
4205 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 /* Can't modify the bytecode after computing jump offsets. */
4208 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 /* Emit code in reverse postorder from dfs. */
4211 for (i = a.a_nblocks - 1; i >= 0; i--) {
4212 b = a.a_postorder[i];
4213 for (j = 0; j < b->b_iused; j++)
4214 if (!assemble_emit(&a, &b->b_instr[j]))
4215 goto error;
4216 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4219 goto error;
4220 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4221 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004224 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 assemble_free(&a);
4226 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004227}
Georg Brandl8334fd92010-12-04 10:26:46 +00004228
4229#undef PyAST_Compile
4230PyAPI_FUNC(PyCodeObject *)
4231PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4232 PyArena *arena)
4233{
4234 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4235}
4236
4237