blob: 79d1d2167028b26064660ed1d6b62cb102e9f794 [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 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200266 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000267}
268
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000269static int
270compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 c->c_stack = PyList_New(0);
275 if (!c->c_stack)
276 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279}
280
281PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +0000282PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
283 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 struct compiler c;
286 PyCodeObject *co = NULL;
287 PyCompilerFlags local_flags;
288 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 if (!__doc__) {
291 __doc__ = PyUnicode_InternFromString("__doc__");
292 if (!__doc__)
293 return NULL;
294 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (!compiler_init(&c))
297 return NULL;
298 c.c_filename = filename;
Benjamin Peterson43b06862011-05-27 09:08:01 -0500299 c.c_filename_obj = PyUnicode_DecodeFSDefault(filename);
300 if (!c.c_filename_obj)
301 goto finally;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 c.c_arena = arena;
303 c.c_future = PyFuture_FromAST(mod, filename);
304 if (c.c_future == NULL)
305 goto finally;
306 if (!flags) {
307 local_flags.cf_flags = 0;
308 flags = &local_flags;
309 }
310 merged = c.c_future->ff_features | flags->cf_flags;
311 c.c_future->ff_features = merged;
312 flags->cf_flags = merged;
313 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000314 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 c.c_st = PySymtable_Build(mod, filename, c.c_future);
318 if (c.c_st == NULL) {
319 if (!PyErr_Occurred())
320 PyErr_SetString(PyExc_SystemError, "no symtable");
321 goto finally;
322 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325
Thomas Wouters1175c432006-02-27 22:49:54 +0000326 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 compiler_free(&c);
328 assert(co || PyErr_Occurred());
329 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000330}
331
332PyCodeObject *
333PyNode_Compile(struct _node *n, const char *filename)
334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyCodeObject *co = NULL;
336 mod_ty mod;
337 PyArena *arena = PyArena_New();
338 if (!arena)
339 return NULL;
340 mod = PyAST_FromNode(n, NULL, filename, arena);
341 if (mod)
342 co = PyAST_Compile(mod, filename, NULL, arena);
343 PyArena_Free(arena);
344 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000345}
346
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000347static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (c->c_st)
351 PySymtable_Free(c->c_st);
352 if (c->c_future)
353 PyObject_Free(c->c_future);
Benjamin Peterson43b06862011-05-27 09:08:01 -0500354 if (c->c_filename_obj)
355 Py_DECREF(c->c_filename_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000357}
358
Guido van Rossum79f25d91997-04-29 20:08:16 +0000359static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 Py_ssize_t i, n;
363 PyObject *v, *k;
364 PyObject *dict = PyDict_New();
365 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 n = PyList_Size(list);
368 for (i = 0; i < n; i++) {
369 v = PyLong_FromLong(i);
370 if (!v) {
371 Py_DECREF(dict);
372 return NULL;
373 }
374 k = PyList_GET_ITEM(list, i);
375 k = PyTuple_Pack(2, k, k->ob_type);
376 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
377 Py_XDECREF(k);
378 Py_DECREF(v);
379 Py_DECREF(dict);
380 return NULL;
381 }
382 Py_DECREF(k);
383 Py_DECREF(v);
384 }
385 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000386}
387
388/* Return new dict containing names from src that match scope(s).
389
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000390src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000392values are integers, starting at offset and increasing by one for
393each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394*/
395
396static PyObject *
397dictbytype(PyObject *src, int scope_type, int flag, int offset)
398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 Py_ssize_t pos = 0, i = offset, scope;
400 PyObject *k, *v, *dest = PyDict_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 assert(offset >= 0);
403 if (dest == NULL)
404 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 while (PyDict_Next(src, &pos, &k, &v)) {
407 /* XXX this should probably be a macro in symtable.h */
408 long vi;
409 assert(PyLong_Check(v));
410 vi = PyLong_AS_LONG(v);
411 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (scope == scope_type || vi & flag) {
414 PyObject *tuple, *item = PyLong_FromLong(i);
415 if (item == NULL) {
416 Py_DECREF(dest);
417 return NULL;
418 }
419 i++;
420 tuple = PyTuple_Pack(2, k, k->ob_type);
421 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
422 Py_DECREF(item);
423 Py_DECREF(dest);
424 Py_XDECREF(tuple);
425 return NULL;
426 }
427 Py_DECREF(item);
428 Py_DECREF(tuple);
429 }
430 }
431 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000432}
433
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000434static void
435compiler_unit_check(struct compiler_unit *u)
436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 basicblock *block;
438 for (block = u->u_blocks; block != NULL; block = block->b_list) {
439 assert((void *)block != (void *)0xcbcbcbcb);
440 assert((void *)block != (void *)0xfbfbfbfb);
441 assert((void *)block != (void *)0xdbdbdbdb);
442 if (block->b_instr != NULL) {
443 assert(block->b_ialloc > 0);
444 assert(block->b_iused > 0);
445 assert(block->b_ialloc >= block->b_iused);
446 }
447 else {
448 assert (block->b_iused == 0);
449 assert (block->b_ialloc == 0);
450 }
451 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452}
453
454static void
455compiler_unit_free(struct compiler_unit *u)
456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 compiler_unit_check(u);
460 b = u->u_blocks;
461 while (b != NULL) {
462 if (b->b_instr)
463 PyObject_Free((void *)b->b_instr);
464 next = b->b_list;
465 PyObject_Free((void *)b);
466 b = next;
467 }
468 Py_CLEAR(u->u_ste);
469 Py_CLEAR(u->u_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100470 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_CLEAR(u->u_consts);
472 Py_CLEAR(u->u_names);
473 Py_CLEAR(u->u_varnames);
474 Py_CLEAR(u->u_freevars);
475 Py_CLEAR(u->u_cellvars);
476 Py_CLEAR(u->u_private);
477 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478}
479
480static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100481compiler_enter_scope(struct compiler *c, identifier name,
482 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
487 struct compiler_unit));
488 if (!u) {
489 PyErr_NoMemory();
490 return 0;
491 }
492 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100493 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 u->u_argcount = 0;
495 u->u_kwonlyargcount = 0;
496 u->u_ste = PySymtable_Lookup(c->c_st, key);
497 if (!u->u_ste) {
498 compiler_unit_free(u);
499 return 0;
500 }
501 Py_INCREF(name);
502 u->u_name = name;
503 u->u_varnames = list2dict(u->u_ste->ste_varnames);
504 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
505 if (!u->u_varnames || !u->u_cellvars) {
506 compiler_unit_free(u);
507 return 0;
508 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
511 PyDict_Size(u->u_cellvars));
512 if (!u->u_freevars) {
513 compiler_unit_free(u);
514 return 0;
515 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 u->u_blocks = NULL;
518 u->u_nfblocks = 0;
519 u->u_firstlineno = lineno;
520 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000521 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 u->u_lineno_set = 0;
523 u->u_consts = PyDict_New();
524 if (!u->u_consts) {
525 compiler_unit_free(u);
526 return 0;
527 }
528 u->u_names = PyDict_New();
529 if (!u->u_names) {
530 compiler_unit_free(u);
531 return 0;
532 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Push the old compiler_unit on the stack. */
537 if (c->u) {
538 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
539 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
540 Py_XDECREF(capsule);
541 compiler_unit_free(u);
542 return 0;
543 }
544 Py_DECREF(capsule);
545 u->u_private = c->u->u_private;
546 Py_XINCREF(u->u_private);
547 }
548 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 c->c_nestlevel++;
551 if (compiler_use_new_block(c) == NULL)
552 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555}
556
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000557static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000558compiler_exit_scope(struct compiler *c)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 int n;
561 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 c->c_nestlevel--;
564 compiler_unit_free(c->u);
565 /* Restore c->u to the parent unit. */
566 n = PyList_GET_SIZE(c->c_stack) - 1;
567 if (n >= 0) {
568 capsule = PyList_GET_ITEM(c->c_stack, n);
569 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
570 assert(c->u);
571 /* we are deleting from a list so this really shouldn't fail */
572 if (PySequence_DelItem(c->c_stack, n) < 0)
573 Py_FatalError("compiler_exit_scope()");
574 compiler_unit_check(c->u);
575 }
576 else
577 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579}
580
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100581static PyObject *
582compiler_scope_qualname(struct compiler *c)
583{
584 Py_ssize_t stack_size, i;
585 _Py_static_string(dot, ".");
586 _Py_static_string(locals, "<locals>");
587 struct compiler_unit *u;
588 PyObject *capsule, *name, *seq, *dot_str, *locals_str;
589
590 u = c->u;
591 if (u->u_qualname != NULL) {
592 Py_INCREF(u->u_qualname);
593 return u->u_qualname;
594 }
595
596 seq = PyList_New(0);
597 if (seq == NULL)
598 return NULL;
599
600 stack_size = PyList_GET_SIZE(c->c_stack);
601 for (i = 0; i < stack_size; i++) {
602 capsule = PyList_GET_ITEM(c->c_stack, i);
603 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
604 assert(u);
605 if (u->u_scope_type == COMPILER_SCOPE_MODULE)
606 continue;
607 if (PyList_Append(seq, u->u_name))
608 goto _error;
609 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION) {
610 locals_str = _PyUnicode_FromId(&locals);
611 if (locals_str == NULL)
612 goto _error;
613 if (PyList_Append(seq, locals_str))
614 goto _error;
615 }
616 }
617 u = c->u;
618 if (PyList_Append(seq, u->u_name))
619 goto _error;
620 dot_str = _PyUnicode_FromId(&dot);
621 if (dot_str == NULL)
622 goto _error;
623 name = PyUnicode_Join(dot_str, seq);
624 Py_DECREF(seq);
625 u->u_qualname = name;
626 Py_XINCREF(name);
627 return name;
628
629_error:
630 Py_XDECREF(seq);
631 return NULL;
632}
633
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634/* Allocate a new block and return a pointer to it.
635 Returns NULL on error.
636*/
637
638static basicblock *
639compiler_new_block(struct compiler *c)
640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 basicblock *b;
642 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 u = c->u;
645 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
646 if (b == NULL) {
647 PyErr_NoMemory();
648 return NULL;
649 }
650 memset((void *)b, 0, sizeof(basicblock));
651 /* Extend the singly linked list of blocks with new block. */
652 b->b_list = u->u_blocks;
653 u->u_blocks = b;
654 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655}
656
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657static basicblock *
658compiler_use_new_block(struct compiler *c)
659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 basicblock *block = compiler_new_block(c);
661 if (block == NULL)
662 return NULL;
663 c->u->u_curblock = block;
664 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000665}
666
667static basicblock *
668compiler_next_block(struct compiler *c)
669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 basicblock *block = compiler_new_block(c);
671 if (block == NULL)
672 return NULL;
673 c->u->u_curblock->b_next = block;
674 c->u->u_curblock = block;
675 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
678static basicblock *
679compiler_use_next_block(struct compiler *c, basicblock *block)
680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 assert(block != NULL);
682 c->u->u_curblock->b_next = block;
683 c->u->u_curblock = block;
684 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000685}
686
687/* Returns the offset of the next instruction in the current block's
688 b_instr array. Resizes the b_instr as necessary.
689 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000690*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000691
692static int
693compiler_next_instr(struct compiler *c, basicblock *b)
694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 assert(b != NULL);
696 if (b->b_instr == NULL) {
697 b->b_instr = (struct instr *)PyObject_Malloc(
698 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
699 if (b->b_instr == NULL) {
700 PyErr_NoMemory();
701 return -1;
702 }
703 b->b_ialloc = DEFAULT_BLOCK_SIZE;
704 memset((char *)b->b_instr, 0,
705 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
706 }
707 else if (b->b_iused == b->b_ialloc) {
708 struct instr *tmp;
709 size_t oldsize, newsize;
710 oldsize = b->b_ialloc * sizeof(struct instr);
711 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (oldsize > (PY_SIZE_MAX >> 1)) {
714 PyErr_NoMemory();
715 return -1;
716 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (newsize == 0) {
719 PyErr_NoMemory();
720 return -1;
721 }
722 b->b_ialloc <<= 1;
723 tmp = (struct instr *)PyObject_Realloc(
724 (void *)b->b_instr, newsize);
725 if (tmp == NULL) {
726 PyErr_NoMemory();
727 return -1;
728 }
729 b->b_instr = tmp;
730 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
731 }
732 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733}
734
Christian Heimes2202f872008-02-06 14:31:34 +0000735/* Set the i_lineno member of the instruction at offset off if the
736 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000737 already been set. If it has been set, the call has no effect.
738
Christian Heimes2202f872008-02-06 14:31:34 +0000739 The line number is reset in the following cases:
740 - when entering a new scope
741 - on each statement
742 - on each expression that start a new line
743 - before the "except" clause
744 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000745*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000746
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747static void
748compiler_set_lineno(struct compiler *c, int off)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 basicblock *b;
751 if (c->u->u_lineno_set)
752 return;
753 c->u->u_lineno_set = 1;
754 b = c->u->u_curblock;
755 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756}
757
758static int
759opcode_stack_effect(int opcode, int oparg)
760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 switch (opcode) {
762 case POP_TOP:
763 return -1;
764 case ROT_TWO:
765 case ROT_THREE:
766 return 0;
767 case DUP_TOP:
768 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000769 case DUP_TOP_TWO:
770 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 case UNARY_POSITIVE:
773 case UNARY_NEGATIVE:
774 case UNARY_NOT:
775 case UNARY_INVERT:
776 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 case SET_ADD:
779 case LIST_APPEND:
780 return -1;
781 case MAP_ADD:
782 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 case BINARY_POWER:
785 case BINARY_MULTIPLY:
786 case BINARY_MODULO:
787 case BINARY_ADD:
788 case BINARY_SUBTRACT:
789 case BINARY_SUBSCR:
790 case BINARY_FLOOR_DIVIDE:
791 case BINARY_TRUE_DIVIDE:
792 return -1;
793 case INPLACE_FLOOR_DIVIDE:
794 case INPLACE_TRUE_DIVIDE:
795 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 case INPLACE_ADD:
798 case INPLACE_SUBTRACT:
799 case INPLACE_MULTIPLY:
800 case INPLACE_MODULO:
801 return -1;
802 case STORE_SUBSCR:
803 return -3;
804 case STORE_MAP:
805 return -2;
806 case DELETE_SUBSCR:
807 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 case BINARY_LSHIFT:
810 case BINARY_RSHIFT:
811 case BINARY_AND:
812 case BINARY_XOR:
813 case BINARY_OR:
814 return -1;
815 case INPLACE_POWER:
816 return -1;
817 case GET_ITER:
818 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 case PRINT_EXPR:
821 return -1;
822 case LOAD_BUILD_CLASS:
823 return 1;
824 case INPLACE_LSHIFT:
825 case INPLACE_RSHIFT:
826 case INPLACE_AND:
827 case INPLACE_XOR:
828 case INPLACE_OR:
829 return -1;
830 case BREAK_LOOP:
831 return 0;
832 case SETUP_WITH:
833 return 7;
834 case WITH_CLEANUP:
835 return -1; /* XXX Sometimes more */
836 case STORE_LOCALS:
837 return -1;
838 case RETURN_VALUE:
839 return -1;
840 case IMPORT_STAR:
841 return -1;
842 case YIELD_VALUE:
843 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500844 case YIELD_FROM:
845 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 case POP_BLOCK:
847 return 0;
848 case POP_EXCEPT:
849 return 0; /* -3 except if bad bytecode */
850 case END_FINALLY:
851 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 case STORE_NAME:
854 return -1;
855 case DELETE_NAME:
856 return 0;
857 case UNPACK_SEQUENCE:
858 return oparg-1;
859 case UNPACK_EX:
860 return (oparg&0xFF) + (oparg>>8);
861 case FOR_ITER:
862 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 case STORE_ATTR:
865 return -2;
866 case DELETE_ATTR:
867 return -1;
868 case STORE_GLOBAL:
869 return -1;
870 case DELETE_GLOBAL:
871 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 case LOAD_CONST:
873 return 1;
874 case LOAD_NAME:
875 return 1;
876 case BUILD_TUPLE:
877 case BUILD_LIST:
878 case BUILD_SET:
879 return 1-oparg;
880 case BUILD_MAP:
881 return 1;
882 case LOAD_ATTR:
883 return 0;
884 case COMPARE_OP:
885 return -1;
886 case IMPORT_NAME:
887 return -1;
888 case IMPORT_FROM:
889 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 case JUMP_FORWARD:
892 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
893 case JUMP_IF_FALSE_OR_POP: /* "" */
894 case JUMP_ABSOLUTE:
895 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 case POP_JUMP_IF_FALSE:
898 case POP_JUMP_IF_TRUE:
899 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case LOAD_GLOBAL:
902 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case CONTINUE_LOOP:
905 return 0;
906 case SETUP_LOOP:
907 return 0;
908 case SETUP_EXCEPT:
909 case SETUP_FINALLY:
910 return 6; /* can push 3 values for the new exception
911 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 case LOAD_FAST:
914 return 1;
915 case STORE_FAST:
916 return -1;
917 case DELETE_FAST:
918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case RAISE_VARARGS:
921 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000922#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 case CALL_FUNCTION:
924 return -NARGS(oparg);
925 case CALL_FUNCTION_VAR:
926 case CALL_FUNCTION_KW:
927 return -NARGS(oparg)-1;
928 case CALL_FUNCTION_VAR_KW:
929 return -NARGS(oparg)-2;
930 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100931 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100933 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000934#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 case BUILD_SLICE:
936 if (oparg == 3)
937 return -2;
938 else
939 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case LOAD_CLOSURE:
942 return 1;
943 case LOAD_DEREF:
944 return 1;
945 case STORE_DEREF:
946 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000947 case DELETE_DEREF:
948 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 default:
950 fprintf(stderr, "opcode = %d\n", opcode);
951 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 }
954 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000955}
956
957/* Add an opcode with no argument.
958 Returns 0 on failure, 1 on success.
959*/
960
961static int
962compiler_addop(struct compiler *c, int opcode)
963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 basicblock *b;
965 struct instr *i;
966 int off;
967 off = compiler_next_instr(c, c->u->u_curblock);
968 if (off < 0)
969 return 0;
970 b = c->u->u_curblock;
971 i = &b->b_instr[off];
972 i->i_opcode = opcode;
973 i->i_hasarg = 0;
974 if (opcode == RETURN_VALUE)
975 b->b_return = 1;
976 compiler_set_lineno(c, off);
977 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978}
979
980static int
981compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *t, *v;
984 Py_ssize_t arg;
985 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 /* necessary to make sure types aren't coerced (e.g., int and long) */
988 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
989 if (PyFloat_Check(o)) {
990 d = PyFloat_AS_DOUBLE(o);
991 /* all we need is to make the tuple different in either the 0.0
992 * or -0.0 case from all others, just to avoid the "coercion".
993 */
994 if (d == 0.0 && copysign(1.0, d) < 0.0)
995 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
996 else
997 t = PyTuple_Pack(2, o, o->ob_type);
998 }
999 else if (PyComplex_Check(o)) {
1000 Py_complex z;
1001 int real_negzero, imag_negzero;
1002 /* For the complex case we must make complex(x, 0.)
1003 different from complex(x, -0.) and complex(0., y)
1004 different from complex(-0., y), for any x and y.
1005 All four complex zeros must be distinguished.*/
1006 z = PyComplex_AsCComplex(o);
1007 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1008 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1009 if (real_negzero && imag_negzero) {
1010 t = PyTuple_Pack(5, o, o->ob_type,
1011 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001012 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 else if (imag_negzero) {
1014 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 else if (real_negzero) {
1017 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1018 }
1019 else {
1020 t = PyTuple_Pack(2, o, o->ob_type);
1021 }
1022 }
1023 else {
1024 t = PyTuple_Pack(2, o, o->ob_type);
1025 }
1026 if (t == NULL)
1027 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 v = PyDict_GetItem(dict, t);
1030 if (!v) {
1031 if (PyErr_Occurred())
1032 return -1;
1033 arg = PyDict_Size(dict);
1034 v = PyLong_FromLong(arg);
1035 if (!v) {
1036 Py_DECREF(t);
1037 return -1;
1038 }
1039 if (PyDict_SetItem(dict, t, v) < 0) {
1040 Py_DECREF(t);
1041 Py_DECREF(v);
1042 return -1;
1043 }
1044 Py_DECREF(v);
1045 }
1046 else
1047 arg = PyLong_AsLong(v);
1048 Py_DECREF(t);
1049 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050}
1051
1052static int
1053compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001055{
1056 int arg = compiler_add_o(c, dict, o);
1057 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001058 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059 return compiler_addop_i(c, opcode, arg);
1060}
1061
1062static int
1063compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065{
1066 int arg;
1067 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1068 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001069 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070 arg = compiler_add_o(c, dict, mangled);
1071 Py_DECREF(mangled);
1072 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001073 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074 return compiler_addop_i(c, opcode, arg);
1075}
1076
1077/* Add an opcode with an integer argument.
1078 Returns 0 on failure, 1 on success.
1079*/
1080
1081static int
1082compiler_addop_i(struct compiler *c, int opcode, int oparg)
1083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 struct instr *i;
1085 int off;
1086 off = compiler_next_instr(c, c->u->u_curblock);
1087 if (off < 0)
1088 return 0;
1089 i = &c->u->u_curblock->b_instr[off];
1090 i->i_opcode = opcode;
1091 i->i_oparg = oparg;
1092 i->i_hasarg = 1;
1093 compiler_set_lineno(c, off);
1094 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095}
1096
1097static int
1098compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 struct instr *i;
1101 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 assert(b != NULL);
1104 off = compiler_next_instr(c, c->u->u_curblock);
1105 if (off < 0)
1106 return 0;
1107 i = &c->u->u_curblock->b_instr[off];
1108 i->i_opcode = opcode;
1109 i->i_target = b;
1110 i->i_hasarg = 1;
1111 if (absolute)
1112 i->i_jabs = 1;
1113 else
1114 i->i_jrel = 1;
1115 compiler_set_lineno(c, off);
1116 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117}
1118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1120 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121 it as the current block. NEXT_BLOCK() also creates an implicit jump
1122 from the current block to the new block.
1123*/
1124
Thomas Wouters89f507f2006-12-13 04:49:30 +00001125/* The returns inside these macros make it impossible to decref objects
1126 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127*/
1128
1129
1130#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (compiler_use_new_block((C)) == NULL) \
1132 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133}
1134
1135#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (compiler_next_block((C)) == NULL) \
1137 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138}
1139
1140#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (!compiler_addop((C), (OP))) \
1142 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143}
1144
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001145#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (!compiler_addop((C), (OP))) { \
1147 compiler_exit_scope(c); \
1148 return 0; \
1149 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001150}
1151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1154 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155}
1156
1157#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1159 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160}
1161
1162#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (!compiler_addop_i((C), (OP), (O))) \
1164 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165}
1166
1167#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (!compiler_addop_j((C), (OP), (O), 1)) \
1169 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170}
1171
1172#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (!compiler_addop_j((C), (OP), (O), 0)) \
1174 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175}
1176
1177/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1178 the ASDL name to synthesize the name of the C type and the visit function.
1179*/
1180
1181#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (!compiler_visit_ ## TYPE((C), (V))) \
1183 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184}
1185
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001186#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (!compiler_visit_ ## TYPE((C), (V))) { \
1188 compiler_exit_scope(c); \
1189 return 0; \
1190 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001191}
1192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (!compiler_visit_slice((C), (V), (CTX))) \
1195 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196}
1197
1198#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 int _i; \
1200 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1201 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1202 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1203 if (!compiler_visit_ ## TYPE((C), elt)) \
1204 return 0; \
1205 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206}
1207
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001208#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 int _i; \
1210 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1211 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1212 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1213 if (!compiler_visit_ ## TYPE((C), elt)) { \
1214 compiler_exit_scope(c); \
1215 return 0; \
1216 } \
1217 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001218}
1219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220static int
1221compiler_isdocstring(stmt_ty s)
1222{
1223 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001224 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225 return s->v.Expr.value->kind == Str_kind;
1226}
1227
1228/* Compile a sequence of statements, checking for a docstring. */
1229
1230static int
1231compiler_body(struct compiler *c, asdl_seq *stmts)
1232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 int i = 0;
1234 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 if (!asdl_seq_LEN(stmts))
1237 return 1;
1238 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001239 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* don't generate docstrings if -OO */
1241 i = 1;
1242 VISIT(c, expr, st->v.Expr.value);
1243 if (!compiler_nameop(c, __doc__, Store))
1244 return 0;
1245 }
1246 for (; i < asdl_seq_LEN(stmts); i++)
1247 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1248 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
1251static PyCodeObject *
1252compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyCodeObject *co;
1255 int addNone = 1;
1256 static PyObject *module;
1257 if (!module) {
1258 module = PyUnicode_InternFromString("<module>");
1259 if (!module)
1260 return NULL;
1261 }
1262 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001263 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 return NULL;
1265 switch (mod->kind) {
1266 case Module_kind:
1267 if (!compiler_body(c, mod->v.Module.body)) {
1268 compiler_exit_scope(c);
1269 return 0;
1270 }
1271 break;
1272 case Interactive_kind:
1273 c->c_interactive = 1;
1274 VISIT_SEQ_IN_SCOPE(c, stmt,
1275 mod->v.Interactive.body);
1276 break;
1277 case Expression_kind:
1278 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1279 addNone = 0;
1280 break;
1281 case Suite_kind:
1282 PyErr_SetString(PyExc_SystemError,
1283 "suite should not be possible");
1284 return 0;
1285 default:
1286 PyErr_Format(PyExc_SystemError,
1287 "module kind %d should not be possible",
1288 mod->kind);
1289 return 0;
1290 }
1291 co = assemble(c, addNone);
1292 compiler_exit_scope(c);
1293 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001294}
1295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296/* The test for LOCAL must come before the test for FREE in order to
1297 handle classes where name is both local and free. The local var is
1298 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001299*/
1300
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301static int
1302get_ref_type(struct compiler *c, PyObject *name)
1303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 int scope = PyST_GetScope(c->u->u_ste, name);
1305 if (scope == 0) {
1306 char buf[350];
1307 PyOS_snprintf(buf, sizeof(buf),
1308 "unknown scope for %.100s in %.100s(%s) in %s\n"
1309 "symbols: %s\nlocals: %s\nglobals: %s",
1310 PyBytes_AS_STRING(name),
1311 PyBytes_AS_STRING(c->u->u_name),
1312 PyObject_REPR(c->u->u_ste->ste_id),
1313 c->c_filename,
1314 PyObject_REPR(c->u->u_ste->ste_symbols),
1315 PyObject_REPR(c->u->u_varnames),
1316 PyObject_REPR(c->u->u_names)
1317 );
1318 Py_FatalError(buf);
1319 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324static int
1325compiler_lookup_arg(PyObject *dict, PyObject *name)
1326{
1327 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001328 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001329 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001330 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001332 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001334 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001335 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336}
1337
1338static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001339compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001342 if (qualname == NULL)
1343 qualname = co->co_name;
1344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (free == 0) {
1346 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001347 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 ADDOP_I(c, MAKE_FUNCTION, args);
1349 return 1;
1350 }
1351 for (i = 0; i < free; ++i) {
1352 /* Bypass com_addop_varname because it will generate
1353 LOAD_DEREF but LOAD_CLOSURE is needed.
1354 */
1355 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1356 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* Special case: If a class contains a method with a
1359 free variable that has the same name as a method,
1360 the name will be considered free *and* local in the
1361 class. It should be handled by the closure, as
1362 well as by the normal name loookup logic.
1363 */
1364 reftype = get_ref_type(c, name);
1365 if (reftype == CELL)
1366 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1367 else /* (reftype == FREE) */
1368 arg = compiler_lookup_arg(c->u->u_freevars, name);
1369 if (arg == -1) {
1370 fprintf(stderr,
1371 "lookup %s in %s %d %d\n"
1372 "freevars of %s: %s\n",
1373 PyObject_REPR(name),
1374 PyBytes_AS_STRING(c->u->u_name),
1375 reftype, arg,
1376 _PyUnicode_AsString(co->co_name),
1377 PyObject_REPR(co->co_freevars));
1378 Py_FatalError("compiler_make_closure()");
1379 }
1380 ADDOP_I(c, LOAD_CLOSURE, arg);
1381 }
1382 ADDOP_I(c, BUILD_TUPLE, free);
1383 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001384 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 ADDOP_I(c, MAKE_CLOSURE, args);
1386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387}
1388
1389static int
1390compiler_decorators(struct compiler *c, asdl_seq* decos)
1391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (!decos)
1395 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1398 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1399 }
1400 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401}
1402
1403static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001404compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 int i, default_count = 0;
1408 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1409 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1410 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1411 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001412 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1413 if (!mangled)
1414 return -1;
1415 ADDOP_O(c, LOAD_CONST, mangled, consts);
1416 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (!compiler_visit_expr(c, default_)) {
1418 return -1;
1419 }
1420 default_count++;
1421 }
1422 }
1423 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001424}
1425
1426static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001427compiler_visit_argannotation(struct compiler *c, identifier id,
1428 expr_ty annotation, PyObject *names)
1429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (annotation) {
1431 VISIT(c, expr, annotation);
1432 if (PyList_Append(names, id))
1433 return -1;
1434 }
1435 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001436}
1437
1438static int
1439compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1440 PyObject *names)
1441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 int i, error;
1443 for (i = 0; i < asdl_seq_LEN(args); i++) {
1444 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1445 error = compiler_visit_argannotation(
1446 c,
1447 arg->arg,
1448 arg->annotation,
1449 names);
1450 if (error)
1451 return error;
1452 }
1453 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001454}
1455
1456static int
1457compiler_visit_annotations(struct compiler *c, arguments_ty args,
1458 expr_ty returns)
1459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 /* Push arg annotations and a list of the argument names. Return the #
1461 of items pushed. The expressions are evaluated out-of-order wrt the
1462 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1465 */
1466 static identifier return_str;
1467 PyObject *names;
1468 int len;
1469 names = PyList_New(0);
1470 if (!names)
1471 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (compiler_visit_argannotations(c, args->args, names))
1474 goto error;
1475 if (args->varargannotation &&
1476 compiler_visit_argannotation(c, args->vararg,
1477 args->varargannotation, names))
1478 goto error;
1479 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1480 goto error;
1481 if (args->kwargannotation &&
1482 compiler_visit_argannotation(c, args->kwarg,
1483 args->kwargannotation, names))
1484 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!return_str) {
1487 return_str = PyUnicode_InternFromString("return");
1488 if (!return_str)
1489 goto error;
1490 }
1491 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1492 goto error;
1493 }
1494
1495 len = PyList_GET_SIZE(names);
1496 if (len > 65534) {
1497 /* len must fit in 16 bits, and len is incremented below */
1498 PyErr_SetString(PyExc_SyntaxError,
1499 "too many annotations");
1500 goto error;
1501 }
1502 if (len) {
1503 /* convert names to a tuple and place on stack */
1504 PyObject *elt;
1505 int i;
1506 PyObject *s = PyTuple_New(len);
1507 if (!s)
1508 goto error;
1509 for (i = 0; i < len; i++) {
1510 elt = PyList_GET_ITEM(names, i);
1511 Py_INCREF(elt);
1512 PyTuple_SET_ITEM(s, i, elt);
1513 }
1514 ADDOP_O(c, LOAD_CONST, s, consts);
1515 Py_DECREF(s);
1516 len++; /* include the just-pushed tuple */
1517 }
1518 Py_DECREF(names);
1519 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001520
1521error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_DECREF(names);
1523 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001524}
1525
1526static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527compiler_function(struct compiler *c, stmt_ty s)
1528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001530 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 arguments_ty args = s->v.FunctionDef.args;
1532 expr_ty returns = s->v.FunctionDef.returns;
1533 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1534 stmt_ty st;
1535 int i, n, docstring, kw_default_count = 0, arglength;
1536 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 if (!compiler_decorators(c, decos))
1541 return 0;
1542 if (args->kwonlyargs) {
1543 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1544 args->kw_defaults);
1545 if (res < 0)
1546 return 0;
1547 kw_default_count = res;
1548 }
1549 if (args->defaults)
1550 VISIT_SEQ(c, expr, args->defaults);
1551 num_annotations = compiler_visit_annotations(c, args, returns);
1552 if (num_annotations < 0)
1553 return 0;
1554 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001555
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001556 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1557 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 s->lineno))
1559 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1562 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001563 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 first_const = st->v.Expr.value->v.Str.s;
1565 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1566 compiler_exit_scope(c);
1567 return 0;
1568 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 c->u->u_argcount = asdl_seq_LEN(args->args);
1571 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1572 n = asdl_seq_LEN(s->v.FunctionDef.body);
1573 /* if there was a docstring, we need to skip the first statement */
1574 for (i = docstring; i < n; i++) {
1575 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1576 VISIT_IN_SCOPE(c, stmt, st);
1577 }
1578 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001579 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001581 if (qualname == NULL || co == NULL) {
1582 Py_XDECREF(qualname);
1583 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001585 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 arglength = asdl_seq_LEN(args->defaults);
1588 arglength |= kw_default_count << 8;
1589 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001590 compiler_make_closure(c, co, arglength, qualname);
1591 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 /* decorators */
1595 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1596 ADDOP_I(c, CALL_FUNCTION, 1);
1597 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001600}
1601
1602static int
1603compiler_class(struct compiler *c, stmt_ty s)
1604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyCodeObject *co;
1606 PyObject *str;
1607 int i;
1608 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (!compiler_decorators(c, decos))
1611 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* ultimately generate code for:
1614 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1615 where:
1616 <func> is a function/closure created from the class body;
1617 it has a single argument (__locals__) where the dict
1618 (or MutableSequence) representing the locals is passed
1619 <name> is the class name
1620 <bases> is the positional arguments and *varargs argument
1621 <keywords> is the keyword arguments and **kwds argument
1622 This borrows from compiler_call.
1623 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001626 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1627 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 return 0;
1629 /* this block represents what we do in the new scope */
1630 {
1631 /* use the class name for name mangling */
1632 Py_INCREF(s->v.ClassDef.name);
1633 Py_XDECREF(c->u->u_private);
1634 c->u->u_private = s->v.ClassDef.name;
1635 /* force it to have one mandatory argument */
1636 c->u->u_argcount = 1;
1637 /* load the first argument (__locals__) ... */
1638 ADDOP_I(c, LOAD_FAST, 0);
1639 /* ... and store it into f_locals */
1640 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1641 /* load (global) __name__ ... */
1642 str = PyUnicode_InternFromString("__name__");
1643 if (!str || !compiler_nameop(c, str, Load)) {
1644 Py_XDECREF(str);
1645 compiler_exit_scope(c);
1646 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 Py_DECREF(str);
1649 /* ... and store it as __module__ */
1650 str = PyUnicode_InternFromString("__module__");
1651 if (!str || !compiler_nameop(c, str, Store)) {
1652 Py_XDECREF(str);
1653 compiler_exit_scope(c);
1654 return 0;
1655 }
1656 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001657 /* store the __qualname__ */
1658 str = compiler_scope_qualname(c);
1659 if (!str) {
1660 compiler_exit_scope(c);
1661 return 0;
1662 }
1663 ADDOP_O(c, LOAD_CONST, str, consts);
1664 Py_DECREF(str);
1665 str = PyUnicode_InternFromString("__qualname__");
1666 if (!str || !compiler_nameop(c, str, Store)) {
1667 Py_XDECREF(str);
1668 compiler_exit_scope(c);
1669 return 0;
1670 }
1671 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 /* compile the body proper */
1673 if (!compiler_body(c, s->v.ClassDef.body)) {
1674 compiler_exit_scope(c);
1675 return 0;
1676 }
1677 /* return the (empty) __class__ cell */
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05001678 str = PyUnicode_InternFromString("@__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (str == NULL) {
1680 compiler_exit_scope(c);
1681 return 0;
1682 }
1683 i = compiler_lookup_arg(c->u->u_cellvars, str);
1684 Py_DECREF(str);
1685 if (i == -1) {
1686 /* This happens when nobody references the cell */
1687 PyErr_Clear();
1688 /* Return None */
1689 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1690 }
1691 else {
1692 /* Return the cell where to store __class__ */
1693 ADDOP_I(c, LOAD_CLOSURE, i);
1694 }
1695 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1696 /* create the code object */
1697 co = assemble(c, 1);
1698 }
1699 /* leave the new scope */
1700 compiler_exit_scope(c);
1701 if (co == NULL)
1702 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 /* 2. load the 'build_class' function */
1705 ADDOP(c, LOAD_BUILD_CLASS);
1706
1707 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001708 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 Py_DECREF(co);
1710
1711 /* 4. load class name */
1712 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1713
1714 /* 5. generate the rest of the code for the call */
1715 if (!compiler_call_helper(c, 2,
1716 s->v.ClassDef.bases,
1717 s->v.ClassDef.keywords,
1718 s->v.ClassDef.starargs,
1719 s->v.ClassDef.kwargs))
1720 return 0;
1721
1722 /* 6. apply decorators */
1723 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1724 ADDOP_I(c, CALL_FUNCTION, 1);
1725 }
1726
1727 /* 7. store into <name> */
1728 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1729 return 0;
1730 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001731}
1732
1733static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001734compiler_ifexp(struct compiler *c, expr_ty e)
1735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 basicblock *end, *next;
1737
1738 assert(e->kind == IfExp_kind);
1739 end = compiler_new_block(c);
1740 if (end == NULL)
1741 return 0;
1742 next = compiler_new_block(c);
1743 if (next == NULL)
1744 return 0;
1745 VISIT(c, expr, e->v.IfExp.test);
1746 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1747 VISIT(c, expr, e->v.IfExp.body);
1748 ADDOP_JREL(c, JUMP_FORWARD, end);
1749 compiler_use_next_block(c, next);
1750 VISIT(c, expr, e->v.IfExp.orelse);
1751 compiler_use_next_block(c, end);
1752 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001753}
1754
1755static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001756compiler_lambda(struct compiler *c, expr_ty e)
1757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001759 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 static identifier name;
1761 int kw_default_count = 0, arglength;
1762 arguments_ty args = e->v.Lambda.args;
1763 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (!name) {
1766 name = PyUnicode_InternFromString("<lambda>");
1767 if (!name)
1768 return 0;
1769 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (args->kwonlyargs) {
1772 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1773 args->kw_defaults);
1774 if (res < 0) return 0;
1775 kw_default_count = res;
1776 }
1777 if (args->defaults)
1778 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001779 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1780 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 /* Make None the first constant, so the lambda can't have a
1784 docstring. */
1785 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1786 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 c->u->u_argcount = asdl_seq_LEN(args->args);
1789 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1790 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1791 if (c->u->u_ste->ste_generator) {
1792 ADDOP_IN_SCOPE(c, POP_TOP);
1793 }
1794 else {
1795 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1796 }
1797 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001798 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001800 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 arglength = asdl_seq_LEN(args->defaults);
1804 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001805 compiler_make_closure(c, co, arglength, qualname);
1806 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 Py_DECREF(co);
1808
1809 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810}
1811
1812static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813compiler_if(struct compiler *c, stmt_ty s)
1814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 basicblock *end, *next;
1816 int constant;
1817 assert(s->kind == If_kind);
1818 end = compiler_new_block(c);
1819 if (end == NULL)
1820 return 0;
1821
Georg Brandl8334fd92010-12-04 10:26:46 +00001822 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 /* constant = 0: "if 0"
1824 * constant = 1: "if 1", "if 2", ...
1825 * constant = -1: rest */
1826 if (constant == 0) {
1827 if (s->v.If.orelse)
1828 VISIT_SEQ(c, stmt, s->v.If.orelse);
1829 } else if (constant == 1) {
1830 VISIT_SEQ(c, stmt, s->v.If.body);
1831 } else {
1832 if (s->v.If.orelse) {
1833 next = compiler_new_block(c);
1834 if (next == NULL)
1835 return 0;
1836 }
1837 else
1838 next = end;
1839 VISIT(c, expr, s->v.If.test);
1840 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1841 VISIT_SEQ(c, stmt, s->v.If.body);
1842 ADDOP_JREL(c, JUMP_FORWARD, end);
1843 if (s->v.If.orelse) {
1844 compiler_use_next_block(c, next);
1845 VISIT_SEQ(c, stmt, s->v.If.orelse);
1846 }
1847 }
1848 compiler_use_next_block(c, end);
1849 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850}
1851
1852static int
1853compiler_for(struct compiler *c, stmt_ty s)
1854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 start = compiler_new_block(c);
1858 cleanup = compiler_new_block(c);
1859 end = compiler_new_block(c);
1860 if (start == NULL || end == NULL || cleanup == NULL)
1861 return 0;
1862 ADDOP_JREL(c, SETUP_LOOP, end);
1863 if (!compiler_push_fblock(c, LOOP, start))
1864 return 0;
1865 VISIT(c, expr, s->v.For.iter);
1866 ADDOP(c, GET_ITER);
1867 compiler_use_next_block(c, start);
1868 ADDOP_JREL(c, FOR_ITER, cleanup);
1869 VISIT(c, expr, s->v.For.target);
1870 VISIT_SEQ(c, stmt, s->v.For.body);
1871 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1872 compiler_use_next_block(c, cleanup);
1873 ADDOP(c, POP_BLOCK);
1874 compiler_pop_fblock(c, LOOP, start);
1875 VISIT_SEQ(c, stmt, s->v.For.orelse);
1876 compiler_use_next_block(c, end);
1877 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878}
1879
1880static int
1881compiler_while(struct compiler *c, stmt_ty s)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001884 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (constant == 0) {
1887 if (s->v.While.orelse)
1888 VISIT_SEQ(c, stmt, s->v.While.orelse);
1889 return 1;
1890 }
1891 loop = compiler_new_block(c);
1892 end = compiler_new_block(c);
1893 if (constant == -1) {
1894 anchor = compiler_new_block(c);
1895 if (anchor == NULL)
1896 return 0;
1897 }
1898 if (loop == NULL || end == NULL)
1899 return 0;
1900 if (s->v.While.orelse) {
1901 orelse = compiler_new_block(c);
1902 if (orelse == NULL)
1903 return 0;
1904 }
1905 else
1906 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 ADDOP_JREL(c, SETUP_LOOP, end);
1909 compiler_use_next_block(c, loop);
1910 if (!compiler_push_fblock(c, LOOP, loop))
1911 return 0;
1912 if (constant == -1) {
1913 VISIT(c, expr, s->v.While.test);
1914 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1915 }
1916 VISIT_SEQ(c, stmt, s->v.While.body);
1917 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 /* XXX should the two POP instructions be in a separate block
1920 if there is no else clause ?
1921 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (constant == -1) {
1924 compiler_use_next_block(c, anchor);
1925 ADDOP(c, POP_BLOCK);
1926 }
1927 compiler_pop_fblock(c, LOOP, loop);
1928 if (orelse != NULL) /* what if orelse is just pass? */
1929 VISIT_SEQ(c, stmt, s->v.While.orelse);
1930 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933}
1934
1935static int
1936compiler_continue(struct compiler *c)
1937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1939 static const char IN_FINALLY_ERROR_MSG[] =
1940 "'continue' not supported inside 'finally' clause";
1941 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (!c->u->u_nfblocks)
1944 return compiler_error(c, LOOP_ERROR_MSG);
1945 i = c->u->u_nfblocks - 1;
1946 switch (c->u->u_fblock[i].fb_type) {
1947 case LOOP:
1948 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1949 break;
1950 case EXCEPT:
1951 case FINALLY_TRY:
1952 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1953 /* Prevent continue anywhere under a finally
1954 even if hidden in a sub-try or except. */
1955 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1956 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1957 }
1958 if (i == -1)
1959 return compiler_error(c, LOOP_ERROR_MSG);
1960 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1961 break;
1962 case FINALLY_END:
1963 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1964 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967}
1968
1969/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970
1971 SETUP_FINALLY L
1972 <code for body>
1973 POP_BLOCK
1974 LOAD_CONST <None>
1975 L: <code for finalbody>
1976 END_FINALLY
1977
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978 The special instructions use the block stack. Each block
1979 stack entry contains the instruction that created it (here
1980 SETUP_FINALLY), the level of the value stack at the time the
1981 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001983 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Pushes the current value stack level and the label
1985 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 Pops en entry from the block stack, and pops the value
1988 stack until its level is the same as indicated on the
1989 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 Pops a variable number of entries from the *value* stack
1992 and re-raises the exception they specify. The number of
1993 entries popped depends on the (pseudo) exception type.
1994
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995 The block stack is unwound when an exception is raised:
1996 when a SETUP_FINALLY entry is found, the exception is pushed
1997 onto the value stack (and the exception condition is cleared),
1998 and the interpreter jumps to the label gotten from the block
1999 stack.
2000*/
2001
2002static int
2003compiler_try_finally(struct compiler *c, stmt_ty s)
2004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 basicblock *body, *end;
2006 body = compiler_new_block(c);
2007 end = compiler_new_block(c);
2008 if (body == NULL || end == NULL)
2009 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 ADDOP_JREL(c, SETUP_FINALLY, end);
2012 compiler_use_next_block(c, body);
2013 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2014 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002015 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2016 if (!compiler_try_except(c, s))
2017 return 0;
2018 }
2019 else {
2020 VISIT_SEQ(c, stmt, s->v.Try.body);
2021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 ADDOP(c, POP_BLOCK);
2023 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2026 compiler_use_next_block(c, end);
2027 if (!compiler_push_fblock(c, FINALLY_END, end))
2028 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002029 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 ADDOP(c, END_FINALLY);
2031 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034}
2035
2036/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002037 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 (The contents of the value stack is shown in [], with the top
2039 at the right; 'tb' is trace-back info, 'val' the exception's
2040 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041
2042 Value stack Label Instruction Argument
2043 [] SETUP_EXCEPT L1
2044 [] <code for S>
2045 [] POP_BLOCK
2046 [] JUMP_FORWARD L0
2047
2048 [tb, val, exc] L1: DUP )
2049 [tb, val, exc, exc] <evaluate E1> )
2050 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2051 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2052 [tb, val, exc] POP
2053 [tb, val] <assign to V1> (or POP if no V1)
2054 [tb] POP
2055 [] <code for S1>
2056 JUMP_FORWARD L0
2057
2058 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 .............................etc.......................
2060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2062
2063 [] L0: <next statement>
2064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 Of course, parts are not generated if Vi or Ei is not present.
2066*/
2067static int
2068compiler_try_except(struct compiler *c, stmt_ty s)
2069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 basicblock *body, *orelse, *except, *end;
2071 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 body = compiler_new_block(c);
2074 except = compiler_new_block(c);
2075 orelse = compiler_new_block(c);
2076 end = compiler_new_block(c);
2077 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2078 return 0;
2079 ADDOP_JREL(c, SETUP_EXCEPT, except);
2080 compiler_use_next_block(c, body);
2081 if (!compiler_push_fblock(c, EXCEPT, body))
2082 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002083 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 ADDOP(c, POP_BLOCK);
2085 compiler_pop_fblock(c, EXCEPT, body);
2086 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002087 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 compiler_use_next_block(c, except);
2089 for (i = 0; i < n; i++) {
2090 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002091 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (!handler->v.ExceptHandler.type && i < n-1)
2093 return compiler_error(c, "default 'except:' must be last");
2094 c->u->u_lineno_set = 0;
2095 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002096 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 except = compiler_new_block(c);
2098 if (except == NULL)
2099 return 0;
2100 if (handler->v.ExceptHandler.type) {
2101 ADDOP(c, DUP_TOP);
2102 VISIT(c, expr, handler->v.ExceptHandler.type);
2103 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2104 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2105 }
2106 ADDOP(c, POP_TOP);
2107 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002108 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002109
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002110 cleanup_end = compiler_new_block(c);
2111 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002112 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002113 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002114
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002115 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2116 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002118 /*
2119 try:
2120 # body
2121 except type as name:
2122 try:
2123 # body
2124 finally:
2125 name = None
2126 del name
2127 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002129 /* second try: */
2130 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2131 compiler_use_next_block(c, cleanup_body);
2132 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2133 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002135 /* second # body */
2136 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2137 ADDOP(c, POP_BLOCK);
2138 ADDOP(c, POP_EXCEPT);
2139 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002141 /* finally: */
2142 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2143 compiler_use_next_block(c, cleanup_end);
2144 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2145 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002147 /* name = None */
2148 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2149 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002151 /* del name */
2152 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002154 ADDOP(c, END_FINALLY);
2155 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 }
2157 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002158 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002160 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002161 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002162 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163
Guido van Rossumb940e112007-01-10 16:19:56 +00002164 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002165 ADDOP(c, POP_TOP);
2166 compiler_use_next_block(c, cleanup_body);
2167 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2168 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002170 ADDOP(c, POP_EXCEPT);
2171 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 }
2173 ADDOP_JREL(c, JUMP_FORWARD, end);
2174 compiler_use_next_block(c, except);
2175 }
2176 ADDOP(c, END_FINALLY);
2177 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002178 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 compiler_use_next_block(c, end);
2180 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002181}
2182
2183static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002184compiler_try(struct compiler *c, stmt_ty s) {
2185 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2186 return compiler_try_finally(c, s);
2187 else
2188 return compiler_try_except(c, s);
2189}
2190
2191
2192static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193compiler_import_as(struct compiler *c, identifier name, identifier asname)
2194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 /* The IMPORT_NAME opcode was already generated. This function
2196 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 If there is a dot in name, we need to split it and emit a
2199 LOAD_ATTR for each name.
2200 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2202 PyUnicode_GET_LENGTH(name), 1);
2203 if (dot == -2)
2204 return -1;
2205 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002207 Py_ssize_t pos = dot + 1;
2208 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002210 dot = PyUnicode_FindChar(name, '.', pos,
2211 PyUnicode_GET_LENGTH(name), 1);
2212 if (dot == -2)
2213 return -1;
2214 attr = PyUnicode_Substring(name, pos,
2215 (dot != -1) ? dot :
2216 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 if (!attr)
2218 return -1;
2219 ADDOP_O(c, LOAD_ATTR, attr, names);
2220 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 }
2223 }
2224 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225}
2226
2227static int
2228compiler_import(struct compiler *c, stmt_ty s)
2229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 /* The Import node stores a module name like a.b.c as a single
2231 string. This is convenient for all cases except
2232 import a.b.c as d
2233 where we need to parse that string to extract the individual
2234 module names.
2235 XXX Perhaps change the representation to make this case simpler?
2236 */
2237 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 for (i = 0; i < n; i++) {
2240 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2241 int r;
2242 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 level = PyLong_FromLong(0);
2245 if (level == NULL)
2246 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 ADDOP_O(c, LOAD_CONST, level, consts);
2249 Py_DECREF(level);
2250 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2251 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if (alias->asname) {
2254 r = compiler_import_as(c, alias->name, alias->asname);
2255 if (!r)
2256 return r;
2257 }
2258 else {
2259 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260 Py_ssize_t dot = PyUnicode_FindChar(
2261 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2262 if (dot != -1)
2263 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002265 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 Py_DECREF(tmp);
2267 }
2268 if (!r)
2269 return r;
2270 }
2271 }
2272 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273}
2274
2275static int
2276compiler_from_import(struct compiler *c, stmt_ty s)
2277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 PyObject *names = PyTuple_New(n);
2281 PyObject *level;
2282 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 if (!empty_string) {
2285 empty_string = PyUnicode_FromString("");
2286 if (!empty_string)
2287 return 0;
2288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 if (!names)
2291 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 level = PyLong_FromLong(s->v.ImportFrom.level);
2294 if (!level) {
2295 Py_DECREF(names);
2296 return 0;
2297 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* build up the names */
2300 for (i = 0; i < n; i++) {
2301 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2302 Py_INCREF(alias->name);
2303 PyTuple_SET_ITEM(names, i, alias->name);
2304 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2307 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2308 Py_DECREF(level);
2309 Py_DECREF(names);
2310 return compiler_error(c, "from __future__ imports must occur "
2311 "at the beginning of the file");
2312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 ADDOP_O(c, LOAD_CONST, level, consts);
2315 Py_DECREF(level);
2316 ADDOP_O(c, LOAD_CONST, names, consts);
2317 Py_DECREF(names);
2318 if (s->v.ImportFrom.module) {
2319 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2320 }
2321 else {
2322 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2323 }
2324 for (i = 0; i < n; i++) {
2325 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2326 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002328 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 assert(n == 1);
2330 ADDOP(c, IMPORT_STAR);
2331 return 1;
2332 }
2333
2334 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2335 store_name = alias->name;
2336 if (alias->asname)
2337 store_name = alias->asname;
2338
2339 if (!compiler_nameop(c, store_name, Store)) {
2340 Py_DECREF(names);
2341 return 0;
2342 }
2343 }
2344 /* remove imported module */
2345 ADDOP(c, POP_TOP);
2346 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347}
2348
2349static int
2350compiler_assert(struct compiler *c, stmt_ty s)
2351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 static PyObject *assertion_error = NULL;
2353 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354
Georg Brandl8334fd92010-12-04 10:26:46 +00002355 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return 1;
2357 if (assertion_error == NULL) {
2358 assertion_error = PyUnicode_InternFromString("AssertionError");
2359 if (assertion_error == NULL)
2360 return 0;
2361 }
2362 if (s->v.Assert.test->kind == Tuple_kind &&
2363 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2364 const char* msg =
2365 "assertion is always true, perhaps remove parentheses?";
2366 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2367 c->u->u_lineno, NULL, NULL) == -1)
2368 return 0;
2369 }
2370 VISIT(c, expr, s->v.Assert.test);
2371 end = compiler_new_block(c);
2372 if (end == NULL)
2373 return 0;
2374 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2375 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2376 if (s->v.Assert.msg) {
2377 VISIT(c, expr, s->v.Assert.msg);
2378 ADDOP_I(c, CALL_FUNCTION, 1);
2379 }
2380 ADDOP_I(c, RAISE_VARARGS, 1);
2381 compiler_use_next_block(c, end);
2382 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383}
2384
2385static int
2386compiler_visit_stmt(struct compiler *c, stmt_ty s)
2387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* Always assign a lineno to the next instruction for a stmt. */
2391 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002392 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 switch (s->kind) {
2396 case FunctionDef_kind:
2397 return compiler_function(c, s);
2398 case ClassDef_kind:
2399 return compiler_class(c, s);
2400 case Return_kind:
2401 if (c->u->u_ste->ste_type != FunctionBlock)
2402 return compiler_error(c, "'return' outside function");
2403 if (s->v.Return.value) {
2404 VISIT(c, expr, s->v.Return.value);
2405 }
2406 else
2407 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2408 ADDOP(c, RETURN_VALUE);
2409 break;
2410 case Delete_kind:
2411 VISIT_SEQ(c, expr, s->v.Delete.targets)
2412 break;
2413 case Assign_kind:
2414 n = asdl_seq_LEN(s->v.Assign.targets);
2415 VISIT(c, expr, s->v.Assign.value);
2416 for (i = 0; i < n; i++) {
2417 if (i < n - 1)
2418 ADDOP(c, DUP_TOP);
2419 VISIT(c, expr,
2420 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2421 }
2422 break;
2423 case AugAssign_kind:
2424 return compiler_augassign(c, s);
2425 case For_kind:
2426 return compiler_for(c, s);
2427 case While_kind:
2428 return compiler_while(c, s);
2429 case If_kind:
2430 return compiler_if(c, s);
2431 case Raise_kind:
2432 n = 0;
2433 if (s->v.Raise.exc) {
2434 VISIT(c, expr, s->v.Raise.exc);
2435 n++;
2436 if (s->v.Raise.cause) {
2437 VISIT(c, expr, s->v.Raise.cause);
2438 n++;
2439 }
2440 }
2441 ADDOP_I(c, RAISE_VARARGS, n);
2442 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002443 case Try_kind:
2444 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 case Assert_kind:
2446 return compiler_assert(c, s);
2447 case Import_kind:
2448 return compiler_import(c, s);
2449 case ImportFrom_kind:
2450 return compiler_from_import(c, s);
2451 case Global_kind:
2452 case Nonlocal_kind:
2453 break;
2454 case Expr_kind:
2455 if (c->c_interactive && c->c_nestlevel <= 1) {
2456 VISIT(c, expr, s->v.Expr.value);
2457 ADDOP(c, PRINT_EXPR);
2458 }
2459 else if (s->v.Expr.value->kind != Str_kind &&
2460 s->v.Expr.value->kind != Num_kind) {
2461 VISIT(c, expr, s->v.Expr.value);
2462 ADDOP(c, POP_TOP);
2463 }
2464 break;
2465 case Pass_kind:
2466 break;
2467 case Break_kind:
2468 if (!compiler_in_loop(c))
2469 return compiler_error(c, "'break' outside loop");
2470 ADDOP(c, BREAK_LOOP);
2471 break;
2472 case Continue_kind:
2473 return compiler_continue(c);
2474 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002475 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 }
2477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478}
2479
2480static int
2481unaryop(unaryop_ty op)
2482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 switch (op) {
2484 case Invert:
2485 return UNARY_INVERT;
2486 case Not:
2487 return UNARY_NOT;
2488 case UAdd:
2489 return UNARY_POSITIVE;
2490 case USub:
2491 return UNARY_NEGATIVE;
2492 default:
2493 PyErr_Format(PyExc_SystemError,
2494 "unary op %d should not be possible", op);
2495 return 0;
2496 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497}
2498
2499static int
2500binop(struct compiler *c, operator_ty op)
2501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 switch (op) {
2503 case Add:
2504 return BINARY_ADD;
2505 case Sub:
2506 return BINARY_SUBTRACT;
2507 case Mult:
2508 return BINARY_MULTIPLY;
2509 case Div:
2510 return BINARY_TRUE_DIVIDE;
2511 case Mod:
2512 return BINARY_MODULO;
2513 case Pow:
2514 return BINARY_POWER;
2515 case LShift:
2516 return BINARY_LSHIFT;
2517 case RShift:
2518 return BINARY_RSHIFT;
2519 case BitOr:
2520 return BINARY_OR;
2521 case BitXor:
2522 return BINARY_XOR;
2523 case BitAnd:
2524 return BINARY_AND;
2525 case FloorDiv:
2526 return BINARY_FLOOR_DIVIDE;
2527 default:
2528 PyErr_Format(PyExc_SystemError,
2529 "binary op %d should not be possible", op);
2530 return 0;
2531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532}
2533
2534static int
2535cmpop(cmpop_ty op)
2536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 switch (op) {
2538 case Eq:
2539 return PyCmp_EQ;
2540 case NotEq:
2541 return PyCmp_NE;
2542 case Lt:
2543 return PyCmp_LT;
2544 case LtE:
2545 return PyCmp_LE;
2546 case Gt:
2547 return PyCmp_GT;
2548 case GtE:
2549 return PyCmp_GE;
2550 case Is:
2551 return PyCmp_IS;
2552 case IsNot:
2553 return PyCmp_IS_NOT;
2554 case In:
2555 return PyCmp_IN;
2556 case NotIn:
2557 return PyCmp_NOT_IN;
2558 default:
2559 return PyCmp_BAD;
2560 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561}
2562
2563static int
2564inplace_binop(struct compiler *c, operator_ty op)
2565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 switch (op) {
2567 case Add:
2568 return INPLACE_ADD;
2569 case Sub:
2570 return INPLACE_SUBTRACT;
2571 case Mult:
2572 return INPLACE_MULTIPLY;
2573 case Div:
2574 return INPLACE_TRUE_DIVIDE;
2575 case Mod:
2576 return INPLACE_MODULO;
2577 case Pow:
2578 return INPLACE_POWER;
2579 case LShift:
2580 return INPLACE_LSHIFT;
2581 case RShift:
2582 return INPLACE_RSHIFT;
2583 case BitOr:
2584 return INPLACE_OR;
2585 case BitXor:
2586 return INPLACE_XOR;
2587 case BitAnd:
2588 return INPLACE_AND;
2589 case FloorDiv:
2590 return INPLACE_FLOOR_DIVIDE;
2591 default:
2592 PyErr_Format(PyExc_SystemError,
2593 "inplace binary op %d should not be possible", op);
2594 return 0;
2595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596}
2597
2598static int
2599compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 int op, scope, arg;
2602 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 PyObject *dict = c->u->u_names;
2605 PyObject *mangled;
2606 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 mangled = _Py_Mangle(c->u->u_private, name);
2609 if (!mangled)
2610 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 op = 0;
2613 optype = OP_NAME;
2614 scope = PyST_GetScope(c->u->u_ste, mangled);
2615 switch (scope) {
2616 case FREE:
2617 dict = c->u->u_freevars;
2618 optype = OP_DEREF;
2619 break;
2620 case CELL:
2621 dict = c->u->u_cellvars;
2622 optype = OP_DEREF;
2623 break;
2624 case LOCAL:
2625 if (c->u->u_ste->ste_type == FunctionBlock)
2626 optype = OP_FAST;
2627 break;
2628 case GLOBAL_IMPLICIT:
2629 if (c->u->u_ste->ste_type == FunctionBlock &&
2630 !c->u->u_ste->ste_unoptimized)
2631 optype = OP_GLOBAL;
2632 break;
2633 case GLOBAL_EXPLICIT:
2634 optype = OP_GLOBAL;
2635 break;
2636 default:
2637 /* scope can be 0 */
2638 break;
2639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 switch (optype) {
2645 case OP_DEREF:
2646 switch (ctx) {
2647 case Load: op = LOAD_DEREF; break;
2648 case Store: op = STORE_DEREF; break;
2649 case AugLoad:
2650 case AugStore:
2651 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002652 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 case Param:
2654 default:
2655 PyErr_SetString(PyExc_SystemError,
2656 "param invalid for deref variable");
2657 return 0;
2658 }
2659 break;
2660 case OP_FAST:
2661 switch (ctx) {
2662 case Load: op = LOAD_FAST; break;
2663 case Store: op = STORE_FAST; break;
2664 case Del: op = DELETE_FAST; break;
2665 case AugLoad:
2666 case AugStore:
2667 break;
2668 case Param:
2669 default:
2670 PyErr_SetString(PyExc_SystemError,
2671 "param invalid for local variable");
2672 return 0;
2673 }
2674 ADDOP_O(c, op, mangled, varnames);
2675 Py_DECREF(mangled);
2676 return 1;
2677 case OP_GLOBAL:
2678 switch (ctx) {
2679 case Load: op = LOAD_GLOBAL; break;
2680 case Store: op = STORE_GLOBAL; break;
2681 case Del: op = DELETE_GLOBAL; break;
2682 case AugLoad:
2683 case AugStore:
2684 break;
2685 case Param:
2686 default:
2687 PyErr_SetString(PyExc_SystemError,
2688 "param invalid for global variable");
2689 return 0;
2690 }
2691 break;
2692 case OP_NAME:
2693 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002694 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 case Store: op = STORE_NAME; break;
2696 case Del: op = DELETE_NAME; break;
2697 case AugLoad:
2698 case AugStore:
2699 break;
2700 case Param:
2701 default:
2702 PyErr_SetString(PyExc_SystemError,
2703 "param invalid for name variable");
2704 return 0;
2705 }
2706 break;
2707 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 assert(op);
2710 arg = compiler_add_o(c, dict, mangled);
2711 Py_DECREF(mangled);
2712 if (arg < 0)
2713 return 0;
2714 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715}
2716
2717static int
2718compiler_boolop(struct compiler *c, expr_ty e)
2719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 basicblock *end;
2721 int jumpi, i, n;
2722 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 assert(e->kind == BoolOp_kind);
2725 if (e->v.BoolOp.op == And)
2726 jumpi = JUMP_IF_FALSE_OR_POP;
2727 else
2728 jumpi = JUMP_IF_TRUE_OR_POP;
2729 end = compiler_new_block(c);
2730 if (end == NULL)
2731 return 0;
2732 s = e->v.BoolOp.values;
2733 n = asdl_seq_LEN(s) - 1;
2734 assert(n >= 0);
2735 for (i = 0; i < n; ++i) {
2736 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2737 ADDOP_JABS(c, jumpi, end);
2738 }
2739 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2740 compiler_use_next_block(c, end);
2741 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742}
2743
2744static int
2745compiler_list(struct compiler *c, expr_ty e)
2746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 int n = asdl_seq_LEN(e->v.List.elts);
2748 if (e->v.List.ctx == Store) {
2749 int i, seen_star = 0;
2750 for (i = 0; i < n; i++) {
2751 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2752 if (elt->kind == Starred_kind && !seen_star) {
2753 if ((i >= (1 << 8)) ||
2754 (n-i-1 >= (INT_MAX >> 8)))
2755 return compiler_error(c,
2756 "too many expressions in "
2757 "star-unpacking assignment");
2758 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2759 seen_star = 1;
2760 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2761 } else if (elt->kind == Starred_kind) {
2762 return compiler_error(c,
2763 "two starred expressions in assignment");
2764 }
2765 }
2766 if (!seen_star) {
2767 ADDOP_I(c, UNPACK_SEQUENCE, n);
2768 }
2769 }
2770 VISIT_SEQ(c, expr, e->v.List.elts);
2771 if (e->v.List.ctx == Load) {
2772 ADDOP_I(c, BUILD_LIST, n);
2773 }
2774 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775}
2776
2777static int
2778compiler_tuple(struct compiler *c, expr_ty e)
2779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 int n = asdl_seq_LEN(e->v.Tuple.elts);
2781 if (e->v.Tuple.ctx == Store) {
2782 int i, seen_star = 0;
2783 for (i = 0; i < n; i++) {
2784 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2785 if (elt->kind == Starred_kind && !seen_star) {
2786 if ((i >= (1 << 8)) ||
2787 (n-i-1 >= (INT_MAX >> 8)))
2788 return compiler_error(c,
2789 "too many expressions in "
2790 "star-unpacking assignment");
2791 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2792 seen_star = 1;
2793 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2794 } else if (elt->kind == Starred_kind) {
2795 return compiler_error(c,
2796 "two starred expressions in assignment");
2797 }
2798 }
2799 if (!seen_star) {
2800 ADDOP_I(c, UNPACK_SEQUENCE, n);
2801 }
2802 }
2803 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2804 if (e->v.Tuple.ctx == Load) {
2805 ADDOP_I(c, BUILD_TUPLE, n);
2806 }
2807 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002808}
2809
2810static int
2811compiler_compare(struct compiler *c, expr_ty e)
2812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 int i, n;
2814 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2817 VISIT(c, expr, e->v.Compare.left);
2818 n = asdl_seq_LEN(e->v.Compare.ops);
2819 assert(n > 0);
2820 if (n > 1) {
2821 cleanup = compiler_new_block(c);
2822 if (cleanup == NULL)
2823 return 0;
2824 VISIT(c, expr,
2825 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2826 }
2827 for (i = 1; i < n; i++) {
2828 ADDOP(c, DUP_TOP);
2829 ADDOP(c, ROT_THREE);
2830 ADDOP_I(c, COMPARE_OP,
2831 cmpop((cmpop_ty)(asdl_seq_GET(
2832 e->v.Compare.ops, i - 1))));
2833 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2834 NEXT_BLOCK(c);
2835 if (i < (n - 1))
2836 VISIT(c, expr,
2837 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2838 }
2839 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2840 ADDOP_I(c, COMPARE_OP,
2841 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2842 if (n > 1) {
2843 basicblock *end = compiler_new_block(c);
2844 if (end == NULL)
2845 return 0;
2846 ADDOP_JREL(c, JUMP_FORWARD, end);
2847 compiler_use_next_block(c, cleanup);
2848 ADDOP(c, ROT_TWO);
2849 ADDOP(c, POP_TOP);
2850 compiler_use_next_block(c, end);
2851 }
2852 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853}
2854
2855static int
2856compiler_call(struct compiler *c, expr_ty e)
2857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 VISIT(c, expr, e->v.Call.func);
2859 return compiler_call_helper(c, 0,
2860 e->v.Call.args,
2861 e->v.Call.keywords,
2862 e->v.Call.starargs,
2863 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002864}
2865
2866/* shared code between compiler_call and compiler_class */
2867static int
2868compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 int n, /* Args already pushed */
2870 asdl_seq *args,
2871 asdl_seq *keywords,
2872 expr_ty starargs,
2873 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 n += asdl_seq_LEN(args);
2878 VISIT_SEQ(c, expr, args);
2879 if (keywords) {
2880 VISIT_SEQ(c, keyword, keywords);
2881 n |= asdl_seq_LEN(keywords) << 8;
2882 }
2883 if (starargs) {
2884 VISIT(c, expr, starargs);
2885 code |= 1;
2886 }
2887 if (kwargs) {
2888 VISIT(c, expr, kwargs);
2889 code |= 2;
2890 }
2891 switch (code) {
2892 case 0:
2893 ADDOP_I(c, CALL_FUNCTION, n);
2894 break;
2895 case 1:
2896 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2897 break;
2898 case 2:
2899 ADDOP_I(c, CALL_FUNCTION_KW, n);
2900 break;
2901 case 3:
2902 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2903 break;
2904 }
2905 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906}
2907
Nick Coghlan650f0d02007-04-15 12:05:43 +00002908
2909/* List and set comprehensions and generator expressions work by creating a
2910 nested function to perform the actual iteration. This means that the
2911 iteration variables don't leak into the current scope.
2912 The defined function is called immediately following its definition, with the
2913 result of that call being the result of the expression.
2914 The LC/SC version returns the populated container, while the GE version is
2915 flagged in symtable.c as a generator, so it returns the generator object
2916 when the function is called.
2917 This code *knows* that the loop cannot contain break, continue, or return,
2918 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2919
2920 Possible cleanups:
2921 - iterate over the generator sequence instead of using recursion
2922*/
2923
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925compiler_comprehension_generator(struct compiler *c,
2926 asdl_seq *generators, int gen_index,
2927 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 /* generate code for the iterator, then each of the ifs,
2930 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 comprehension_ty gen;
2933 basicblock *start, *anchor, *skip, *if_cleanup;
2934 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 start = compiler_new_block(c);
2937 skip = compiler_new_block(c);
2938 if_cleanup = compiler_new_block(c);
2939 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2942 anchor == NULL)
2943 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 if (gen_index == 0) {
2948 /* Receive outermost iter as an implicit argument */
2949 c->u->u_argcount = 1;
2950 ADDOP_I(c, LOAD_FAST, 0);
2951 }
2952 else {
2953 /* Sub-iter - calculate on the fly */
2954 VISIT(c, expr, gen->iter);
2955 ADDOP(c, GET_ITER);
2956 }
2957 compiler_use_next_block(c, start);
2958 ADDOP_JREL(c, FOR_ITER, anchor);
2959 NEXT_BLOCK(c);
2960 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 /* XXX this needs to be cleaned up...a lot! */
2963 n = asdl_seq_LEN(gen->ifs);
2964 for (i = 0; i < n; i++) {
2965 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2966 VISIT(c, expr, e);
2967 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2968 NEXT_BLOCK(c);
2969 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 if (++gen_index < asdl_seq_LEN(generators))
2972 if (!compiler_comprehension_generator(c,
2973 generators, gen_index,
2974 elt, val, type))
2975 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 /* only append after the last for generator */
2978 if (gen_index >= asdl_seq_LEN(generators)) {
2979 /* comprehension specific code */
2980 switch (type) {
2981 case COMP_GENEXP:
2982 VISIT(c, expr, elt);
2983 ADDOP(c, YIELD_VALUE);
2984 ADDOP(c, POP_TOP);
2985 break;
2986 case COMP_LISTCOMP:
2987 VISIT(c, expr, elt);
2988 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2989 break;
2990 case COMP_SETCOMP:
2991 VISIT(c, expr, elt);
2992 ADDOP_I(c, SET_ADD, gen_index + 1);
2993 break;
2994 case COMP_DICTCOMP:
2995 /* With 'd[k] = v', v is evaluated before k, so we do
2996 the same. */
2997 VISIT(c, expr, val);
2998 VISIT(c, expr, elt);
2999 ADDOP_I(c, MAP_ADD, gen_index + 1);
3000 break;
3001 default:
3002 return 0;
3003 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 compiler_use_next_block(c, skip);
3006 }
3007 compiler_use_next_block(c, if_cleanup);
3008 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3009 compiler_use_next_block(c, anchor);
3010
3011 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012}
3013
3014static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003015compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 PyCodeObject *co = NULL;
3019 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003020 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 outermost_iter = ((comprehension_ty)
3023 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003024
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003025 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3026 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 if (type != COMP_GENEXP) {
3030 int op;
3031 switch (type) {
3032 case COMP_LISTCOMP:
3033 op = BUILD_LIST;
3034 break;
3035 case COMP_SETCOMP:
3036 op = BUILD_SET;
3037 break;
3038 case COMP_DICTCOMP:
3039 op = BUILD_MAP;
3040 break;
3041 default:
3042 PyErr_Format(PyExc_SystemError,
3043 "unknown comprehension type %d", type);
3044 goto error_in_scope;
3045 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 ADDOP_I(c, op, 0);
3048 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 if (!compiler_comprehension_generator(c, generators, 0, elt,
3051 val, type))
3052 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 if (type != COMP_GENEXP) {
3055 ADDOP(c, RETURN_VALUE);
3056 }
3057
3058 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003059 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003061 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 goto error;
3063
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003064 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003066 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 Py_DECREF(co);
3068
3069 VISIT(c, expr, outermost_iter);
3070 ADDOP(c, GET_ITER);
3071 ADDOP_I(c, CALL_FUNCTION, 1);
3072 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003073error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003075error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003076 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 Py_XDECREF(co);
3078 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003079}
3080
3081static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082compiler_genexp(struct compiler *c, expr_ty e)
3083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 static identifier name;
3085 if (!name) {
3086 name = PyUnicode_FromString("<genexpr>");
3087 if (!name)
3088 return 0;
3089 }
3090 assert(e->kind == GeneratorExp_kind);
3091 return compiler_comprehension(c, e, COMP_GENEXP, name,
3092 e->v.GeneratorExp.generators,
3093 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094}
3095
3096static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003097compiler_listcomp(struct compiler *c, expr_ty e)
3098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 static identifier name;
3100 if (!name) {
3101 name = PyUnicode_FromString("<listcomp>");
3102 if (!name)
3103 return 0;
3104 }
3105 assert(e->kind == ListComp_kind);
3106 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3107 e->v.ListComp.generators,
3108 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003109}
3110
3111static int
3112compiler_setcomp(struct compiler *c, expr_ty e)
3113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 static identifier name;
3115 if (!name) {
3116 name = PyUnicode_FromString("<setcomp>");
3117 if (!name)
3118 return 0;
3119 }
3120 assert(e->kind == SetComp_kind);
3121 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3122 e->v.SetComp.generators,
3123 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003124}
3125
3126
3127static int
3128compiler_dictcomp(struct compiler *c, expr_ty e)
3129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 static identifier name;
3131 if (!name) {
3132 name = PyUnicode_FromString("<dictcomp>");
3133 if (!name)
3134 return 0;
3135 }
3136 assert(e->kind == DictComp_kind);
3137 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3138 e->v.DictComp.generators,
3139 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003140}
3141
3142
3143static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144compiler_visit_keyword(struct compiler *c, keyword_ty k)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3147 VISIT(c, expr, k->value);
3148 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149}
3150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152 whether they are true or false.
3153
3154 Return values: 1 for true, 0 for false, -1 for non-constant.
3155 */
3156
3157static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003158expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 char *id;
3161 switch (e->kind) {
3162 case Ellipsis_kind:
3163 return 1;
3164 case Num_kind:
3165 return PyObject_IsTrue(e->v.Num.n);
3166 case Str_kind:
3167 return PyObject_IsTrue(e->v.Str.s);
3168 case Name_kind:
3169 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003170 id = PyUnicode_AsUTF8(e->v.Name.id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 if (strcmp(id, "True") == 0) return 1;
3172 if (strcmp(id, "False") == 0) return 0;
3173 if (strcmp(id, "None") == 0) return 0;
3174 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003175 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 /* fall through */
3177 default:
3178 return -1;
3179 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180}
3181
Guido van Rossumc2e20742006-02-27 22:32:47 +00003182/*
3183 Implements the with statement from PEP 343.
3184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003186
3187 with EXPR as VAR:
3188 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189
Guido van Rossumc2e20742006-02-27 22:32:47 +00003190 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191
Thomas Wouters477c8d52006-05-27 19:21:47 +00003192 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003193 exit = context.__exit__ # not calling it
3194 value = context.__enter__()
3195 try:
3196 VAR = value # if VAR present in the syntax
3197 BLOCK
3198 finally:
3199 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003201 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003203 exit(*exc)
3204 */
3205static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003206compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003207{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003208 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003209 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003210
3211 assert(s->kind == With_kind);
3212
Guido van Rossumc2e20742006-02-27 22:32:47 +00003213 block = compiler_new_block(c);
3214 finally = compiler_new_block(c);
3215 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003216 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003217
Thomas Wouters477c8d52006-05-27 19:21:47 +00003218 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003219 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003220 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003221
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003222 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003223 compiler_use_next_block(c, block);
3224 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003225 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003226 }
3227
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003228 if (item->optional_vars) {
3229 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003230 }
3231 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003233 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003234 }
3235
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003236 pos++;
3237 if (pos == asdl_seq_LEN(s->v.With.items))
3238 /* BLOCK code */
3239 VISIT_SEQ(c, stmt, s->v.With.body)
3240 else if (!compiler_with(c, s, pos))
3241 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003242
3243 /* End of try block; start the finally block */
3244 ADDOP(c, POP_BLOCK);
3245 compiler_pop_fblock(c, FINALLY_TRY, block);
3246
3247 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3248 compiler_use_next_block(c, finally);
3249 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003250 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003251
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003252 /* Finally block starts; context.__exit__ is on the stack under
3253 the exception or return information. Just issue our magic
3254 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003255 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003256
3257 /* Finally block ends. */
3258 ADDOP(c, END_FINALLY);
3259 compiler_pop_fblock(c, FINALLY_END, finally);
3260 return 1;
3261}
3262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263static int
3264compiler_visit_expr(struct compiler *c, expr_ty e)
3265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 /* If expr e has a different line number than the last expr/stmt,
3269 set a new line number for the next instruction.
3270 */
3271 if (e->lineno > c->u->u_lineno) {
3272 c->u->u_lineno = e->lineno;
3273 c->u->u_lineno_set = 0;
3274 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003275 /* Updating the column offset is always harmless. */
3276 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 switch (e->kind) {
3278 case BoolOp_kind:
3279 return compiler_boolop(c, e);
3280 case BinOp_kind:
3281 VISIT(c, expr, e->v.BinOp.left);
3282 VISIT(c, expr, e->v.BinOp.right);
3283 ADDOP(c, binop(c, e->v.BinOp.op));
3284 break;
3285 case UnaryOp_kind:
3286 VISIT(c, expr, e->v.UnaryOp.operand);
3287 ADDOP(c, unaryop(e->v.UnaryOp.op));
3288 break;
3289 case Lambda_kind:
3290 return compiler_lambda(c, e);
3291 case IfExp_kind:
3292 return compiler_ifexp(c, e);
3293 case Dict_kind:
3294 n = asdl_seq_LEN(e->v.Dict.values);
3295 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3296 for (i = 0; i < n; i++) {
3297 VISIT(c, expr,
3298 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3299 VISIT(c, expr,
3300 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3301 ADDOP(c, STORE_MAP);
3302 }
3303 break;
3304 case Set_kind:
3305 n = asdl_seq_LEN(e->v.Set.elts);
3306 VISIT_SEQ(c, expr, e->v.Set.elts);
3307 ADDOP_I(c, BUILD_SET, n);
3308 break;
3309 case GeneratorExp_kind:
3310 return compiler_genexp(c, e);
3311 case ListComp_kind:
3312 return compiler_listcomp(c, e);
3313 case SetComp_kind:
3314 return compiler_setcomp(c, e);
3315 case DictComp_kind:
3316 return compiler_dictcomp(c, e);
3317 case Yield_kind:
Benjamin Peterson527c6222012-01-14 08:58:23 -05003318 case YieldFrom_kind: {
3319 expr_ty value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 if (c->u->u_ste->ste_type != FunctionBlock)
3321 return compiler_error(c, "'yield' outside function");
Benjamin Peterson527c6222012-01-14 08:58:23 -05003322 value = (e->kind == YieldFrom_kind) ? e->v.YieldFrom.value : e->v.Yield.value;
3323 if (value) {
3324 VISIT(c, expr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 }
3326 else {
3327 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3328 }
Benjamin Peterson527c6222012-01-14 08:58:23 -05003329 if (e->kind == YieldFrom_kind) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05003330 ADDOP(c, GET_ITER);
3331 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Nick Coghlan1f7ce622012-01-13 21:43:40 +10003332 ADDOP(c, YIELD_FROM);
3333 }
3334 else {
3335 ADDOP(c, YIELD_VALUE);
3336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 break;
Benjamin Peterson527c6222012-01-14 08:58:23 -05003338 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 case Compare_kind:
3340 return compiler_compare(c, e);
3341 case Call_kind:
3342 return compiler_call(c, e);
3343 case Num_kind:
3344 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3345 break;
3346 case Str_kind:
3347 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3348 break;
3349 case Bytes_kind:
3350 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3351 break;
3352 case Ellipsis_kind:
3353 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3354 break;
3355 /* The following exprs can be assignment targets. */
3356 case Attribute_kind:
3357 if (e->v.Attribute.ctx != AugStore)
3358 VISIT(c, expr, e->v.Attribute.value);
3359 switch (e->v.Attribute.ctx) {
3360 case AugLoad:
3361 ADDOP(c, DUP_TOP);
3362 /* Fall through to load */
3363 case Load:
3364 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3365 break;
3366 case AugStore:
3367 ADDOP(c, ROT_TWO);
3368 /* Fall through to save */
3369 case Store:
3370 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3371 break;
3372 case Del:
3373 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3374 break;
3375 case Param:
3376 default:
3377 PyErr_SetString(PyExc_SystemError,
3378 "param invalid in attribute expression");
3379 return 0;
3380 }
3381 break;
3382 case Subscript_kind:
3383 switch (e->v.Subscript.ctx) {
3384 case AugLoad:
3385 VISIT(c, expr, e->v.Subscript.value);
3386 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3387 break;
3388 case Load:
3389 VISIT(c, expr, e->v.Subscript.value);
3390 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3391 break;
3392 case AugStore:
3393 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3394 break;
3395 case Store:
3396 VISIT(c, expr, e->v.Subscript.value);
3397 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3398 break;
3399 case Del:
3400 VISIT(c, expr, e->v.Subscript.value);
3401 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3402 break;
3403 case Param:
3404 default:
3405 PyErr_SetString(PyExc_SystemError,
3406 "param invalid in subscript expression");
3407 return 0;
3408 }
3409 break;
3410 case Starred_kind:
3411 switch (e->v.Starred.ctx) {
3412 case Store:
3413 /* In all legitimate cases, the Starred node was already replaced
3414 * by compiler_list/compiler_tuple. XXX: is that okay? */
3415 return compiler_error(c,
3416 "starred assignment target must be in a list or tuple");
3417 default:
3418 return compiler_error(c,
3419 "can use starred expression only as assignment target");
3420 }
3421 break;
3422 case Name_kind:
3423 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3424 /* child nodes of List and Tuple will have expr_context set */
3425 case List_kind:
3426 return compiler_list(c, e);
3427 case Tuple_kind:
3428 return compiler_tuple(c, e);
3429 }
3430 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431}
3432
3433static int
3434compiler_augassign(struct compiler *c, stmt_ty s)
3435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 expr_ty e = s->v.AugAssign.target;
3437 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 switch (e->kind) {
3442 case Attribute_kind:
3443 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3444 AugLoad, e->lineno, e->col_offset, c->c_arena);
3445 if (auge == NULL)
3446 return 0;
3447 VISIT(c, expr, auge);
3448 VISIT(c, expr, s->v.AugAssign.value);
3449 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3450 auge->v.Attribute.ctx = AugStore;
3451 VISIT(c, expr, auge);
3452 break;
3453 case Subscript_kind:
3454 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3455 AugLoad, e->lineno, e->col_offset, c->c_arena);
3456 if (auge == NULL)
3457 return 0;
3458 VISIT(c, expr, auge);
3459 VISIT(c, expr, s->v.AugAssign.value);
3460 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3461 auge->v.Subscript.ctx = AugStore;
3462 VISIT(c, expr, auge);
3463 break;
3464 case Name_kind:
3465 if (!compiler_nameop(c, e->v.Name.id, Load))
3466 return 0;
3467 VISIT(c, expr, s->v.AugAssign.value);
3468 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3469 return compiler_nameop(c, e->v.Name.id, Store);
3470 default:
3471 PyErr_Format(PyExc_SystemError,
3472 "invalid node type (%d) for augmented assignment",
3473 e->kind);
3474 return 0;
3475 }
3476 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477}
3478
3479static int
3480compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 struct fblockinfo *f;
3483 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3484 PyErr_SetString(PyExc_SystemError,
3485 "too many statically nested blocks");
3486 return 0;
3487 }
3488 f = &c->u->u_fblock[c->u->u_nfblocks++];
3489 f->fb_type = t;
3490 f->fb_block = b;
3491 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492}
3493
3494static void
3495compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 struct compiler_unit *u = c->u;
3498 assert(u->u_nfblocks > 0);
3499 u->u_nfblocks--;
3500 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3501 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502}
3503
Thomas Wouters89f507f2006-12-13 04:49:30 +00003504static int
3505compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 int i;
3507 struct compiler_unit *u = c->u;
3508 for (i = 0; i < u->u_nfblocks; ++i) {
3509 if (u->u_fblock[i].fb_type == LOOP)
3510 return 1;
3511 }
3512 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003513}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514/* Raises a SyntaxError and returns 0.
3515 If something goes wrong, a different exception may be raised.
3516*/
3517
3518static int
3519compiler_error(struct compiler *c, const char *errstr)
3520{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003521 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3525 if (!loc) {
3526 Py_INCREF(Py_None);
3527 loc = Py_None;
3528 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003529 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003530 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 if (!u)
3532 goto exit;
3533 v = Py_BuildValue("(zO)", errstr, u);
3534 if (!v)
3535 goto exit;
3536 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 Py_DECREF(loc);
3539 Py_XDECREF(u);
3540 Py_XDECREF(v);
3541 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542}
3543
3544static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545compiler_handle_subscr(struct compiler *c, const char *kind,
3546 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 /* XXX this code is duplicated */
3551 switch (ctx) {
3552 case AugLoad: /* fall through to Load */
3553 case Load: op = BINARY_SUBSCR; break;
3554 case AugStore:/* fall through to Store */
3555 case Store: op = STORE_SUBSCR; break;
3556 case Del: op = DELETE_SUBSCR; break;
3557 case Param:
3558 PyErr_Format(PyExc_SystemError,
3559 "invalid %s kind %d in subscript\n",
3560 kind, ctx);
3561 return 0;
3562 }
3563 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003564 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 }
3566 else if (ctx == AugStore) {
3567 ADDOP(c, ROT_THREE);
3568 }
3569 ADDOP(c, op);
3570 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571}
3572
3573static int
3574compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 int n = 2;
3577 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 /* only handles the cases where BUILD_SLICE is emitted */
3580 if (s->v.Slice.lower) {
3581 VISIT(c, expr, s->v.Slice.lower);
3582 }
3583 else {
3584 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3585 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 if (s->v.Slice.upper) {
3588 VISIT(c, expr, s->v.Slice.upper);
3589 }
3590 else {
3591 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3592 }
3593
3594 if (s->v.Slice.step) {
3595 n++;
3596 VISIT(c, expr, s->v.Slice.step);
3597 }
3598 ADDOP_I(c, BUILD_SLICE, n);
3599 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600}
3601
3602static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3604 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 switch (s->kind) {
3607 case Slice_kind:
3608 return compiler_slice(c, s, ctx);
3609 case Index_kind:
3610 VISIT(c, expr, s->v.Index.value);
3611 break;
3612 case ExtSlice_kind:
3613 default:
3614 PyErr_SetString(PyExc_SystemError,
3615 "extended slice invalid in nested slice");
3616 return 0;
3617 }
3618 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619}
3620
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621static int
3622compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 char * kindname = NULL;
3625 switch (s->kind) {
3626 case Index_kind:
3627 kindname = "index";
3628 if (ctx != AugStore) {
3629 VISIT(c, expr, s->v.Index.value);
3630 }
3631 break;
3632 case Slice_kind:
3633 kindname = "slice";
3634 if (ctx != AugStore) {
3635 if (!compiler_slice(c, s, ctx))
3636 return 0;
3637 }
3638 break;
3639 case ExtSlice_kind:
3640 kindname = "extended slice";
3641 if (ctx != AugStore) {
3642 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3643 for (i = 0; i < n; i++) {
3644 slice_ty sub = (slice_ty)asdl_seq_GET(
3645 s->v.ExtSlice.dims, i);
3646 if (!compiler_visit_nested_slice(c, sub, ctx))
3647 return 0;
3648 }
3649 ADDOP_I(c, BUILD_TUPLE, n);
3650 }
3651 break;
3652 default:
3653 PyErr_Format(PyExc_SystemError,
3654 "invalid subscript kind %d", s->kind);
3655 return 0;
3656 }
3657 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658}
3659
Thomas Wouters89f507f2006-12-13 04:49:30 +00003660/* End of the compiler section, beginning of the assembler section */
3661
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662/* do depth-first search of basic block graph, starting with block.
3663 post records the block indices in post-order.
3664
3665 XXX must handle implicit jumps from one block to next
3666*/
3667
Thomas Wouters89f507f2006-12-13 04:49:30 +00003668struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 PyObject *a_bytecode; /* string containing bytecode */
3670 int a_offset; /* offset into bytecode */
3671 int a_nblocks; /* number of reachable blocks */
3672 basicblock **a_postorder; /* list of blocks in dfs postorder */
3673 PyObject *a_lnotab; /* string containing lnotab */
3674 int a_lnotab_off; /* offset into lnotab */
3675 int a_lineno; /* last lineno of emitted instruction */
3676 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003677};
3678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679static void
3680dfs(struct compiler *c, basicblock *b, struct assembler *a)
3681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 int i;
3683 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 if (b->b_seen)
3686 return;
3687 b->b_seen = 1;
3688 if (b->b_next != NULL)
3689 dfs(c, b->b_next, a);
3690 for (i = 0; i < b->b_iused; i++) {
3691 instr = &b->b_instr[i];
3692 if (instr->i_jrel || instr->i_jabs)
3693 dfs(c, instr->i_target, a);
3694 }
3695 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003696}
3697
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003698static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003699stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 int i, target_depth;
3702 struct instr *instr;
3703 if (b->b_seen || b->b_startdepth >= depth)
3704 return maxdepth;
3705 b->b_seen = 1;
3706 b->b_startdepth = depth;
3707 for (i = 0; i < b->b_iused; i++) {
3708 instr = &b->b_instr[i];
3709 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3710 if (depth > maxdepth)
3711 maxdepth = depth;
3712 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3713 if (instr->i_jrel || instr->i_jabs) {
3714 target_depth = depth;
3715 if (instr->i_opcode == FOR_ITER) {
3716 target_depth = depth-2;
3717 } else if (instr->i_opcode == SETUP_FINALLY ||
3718 instr->i_opcode == SETUP_EXCEPT) {
3719 target_depth = depth+3;
3720 if (target_depth > maxdepth)
3721 maxdepth = target_depth;
3722 }
3723 maxdepth = stackdepth_walk(c, instr->i_target,
3724 target_depth, maxdepth);
3725 if (instr->i_opcode == JUMP_ABSOLUTE ||
3726 instr->i_opcode == JUMP_FORWARD) {
3727 goto out; /* remaining code is dead */
3728 }
3729 }
3730 }
3731 if (b->b_next)
3732 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003733out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 b->b_seen = 0;
3735 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736}
3737
3738/* Find the flow path that needs the largest stack. We assume that
3739 * cycles in the flow graph have no net effect on the stack depth.
3740 */
3741static int
3742stackdepth(struct compiler *c)
3743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 basicblock *b, *entryblock;
3745 entryblock = NULL;
3746 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3747 b->b_seen = 0;
3748 b->b_startdepth = INT_MIN;
3749 entryblock = b;
3750 }
3751 if (!entryblock)
3752 return 0;
3753 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754}
3755
3756static int
3757assemble_init(struct assembler *a, int nblocks, int firstlineno)
3758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 memset(a, 0, sizeof(struct assembler));
3760 a->a_lineno = firstlineno;
3761 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3762 if (!a->a_bytecode)
3763 return 0;
3764 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3765 if (!a->a_lnotab)
3766 return 0;
3767 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3768 PyErr_NoMemory();
3769 return 0;
3770 }
3771 a->a_postorder = (basicblock **)PyObject_Malloc(
3772 sizeof(basicblock *) * nblocks);
3773 if (!a->a_postorder) {
3774 PyErr_NoMemory();
3775 return 0;
3776 }
3777 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778}
3779
3780static void
3781assemble_free(struct assembler *a)
3782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 Py_XDECREF(a->a_bytecode);
3784 Py_XDECREF(a->a_lnotab);
3785 if (a->a_postorder)
3786 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787}
3788
3789/* Return the size of a basic block in bytes. */
3790
3791static int
3792instrsize(struct instr *instr)
3793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 if (!instr->i_hasarg)
3795 return 1; /* 1 byte for the opcode*/
3796 if (instr->i_oparg > 0xffff)
3797 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3798 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799}
3800
3801static int
3802blocksize(basicblock *b)
3803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 int i;
3805 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 for (i = 0; i < b->b_iused; i++)
3808 size += instrsize(&b->b_instr[i]);
3809 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810}
3811
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003812/* Appends a pair to the end of the line number table, a_lnotab, representing
3813 the instruction's bytecode offset and line number. See
3814 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003815
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003816static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 int d_bytecode, d_lineno;
3820 int len;
3821 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 d_bytecode = a->a_offset - a->a_lineno_off;
3824 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 assert(d_bytecode >= 0);
3827 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 if(d_bytecode == 0 && d_lineno == 0)
3830 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 if (d_bytecode > 255) {
3833 int j, nbytes, ncodes = d_bytecode / 255;
3834 nbytes = a->a_lnotab_off + 2 * ncodes;
3835 len = PyBytes_GET_SIZE(a->a_lnotab);
3836 if (nbytes >= len) {
3837 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3838 len = nbytes;
3839 else if (len <= INT_MAX / 2)
3840 len *= 2;
3841 else {
3842 PyErr_NoMemory();
3843 return 0;
3844 }
3845 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3846 return 0;
3847 }
3848 lnotab = (unsigned char *)
3849 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3850 for (j = 0; j < ncodes; j++) {
3851 *lnotab++ = 255;
3852 *lnotab++ = 0;
3853 }
3854 d_bytecode -= ncodes * 255;
3855 a->a_lnotab_off += ncodes * 2;
3856 }
3857 assert(d_bytecode <= 255);
3858 if (d_lineno > 255) {
3859 int j, nbytes, ncodes = d_lineno / 255;
3860 nbytes = a->a_lnotab_off + 2 * ncodes;
3861 len = PyBytes_GET_SIZE(a->a_lnotab);
3862 if (nbytes >= len) {
3863 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3864 len = nbytes;
3865 else if (len <= INT_MAX / 2)
3866 len *= 2;
3867 else {
3868 PyErr_NoMemory();
3869 return 0;
3870 }
3871 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3872 return 0;
3873 }
3874 lnotab = (unsigned char *)
3875 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3876 *lnotab++ = d_bytecode;
3877 *lnotab++ = 255;
3878 d_bytecode = 0;
3879 for (j = 1; j < ncodes; j++) {
3880 *lnotab++ = 0;
3881 *lnotab++ = 255;
3882 }
3883 d_lineno -= ncodes * 255;
3884 a->a_lnotab_off += ncodes * 2;
3885 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 len = PyBytes_GET_SIZE(a->a_lnotab);
3888 if (a->a_lnotab_off + 2 >= len) {
3889 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3890 return 0;
3891 }
3892 lnotab = (unsigned char *)
3893 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 a->a_lnotab_off += 2;
3896 if (d_bytecode) {
3897 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003898 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 }
3900 else { /* First line of a block; def stmt, etc. */
3901 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003902 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 }
3904 a->a_lineno = i->i_lineno;
3905 a->a_lineno_off = a->a_offset;
3906 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003907}
3908
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909/* assemble_emit()
3910 Extend the bytecode with a new instruction.
3911 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003912*/
3913
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003914static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 int size, arg = 0, ext = 0;
3918 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3919 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 size = instrsize(i);
3922 if (i->i_hasarg) {
3923 arg = i->i_oparg;
3924 ext = arg >> 16;
3925 }
3926 if (i->i_lineno && !assemble_lnotab(a, i))
3927 return 0;
3928 if (a->a_offset + size >= len) {
3929 if (len > PY_SSIZE_T_MAX / 2)
3930 return 0;
3931 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3932 return 0;
3933 }
3934 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3935 a->a_offset += size;
3936 if (size == 6) {
3937 assert(i->i_hasarg);
3938 *code++ = (char)EXTENDED_ARG;
3939 *code++ = ext & 0xff;
3940 *code++ = ext >> 8;
3941 arg &= 0xffff;
3942 }
3943 *code++ = i->i_opcode;
3944 if (i->i_hasarg) {
3945 assert(size == 3 || size == 6);
3946 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003947 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 }
3949 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003950}
3951
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003952static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003953assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 basicblock *b;
3956 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3957 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 /* Compute the size of each block and fixup jump args.
3960 Replace block pointer with position in bytecode. */
3961 do {
3962 totsize = 0;
3963 for (i = a->a_nblocks - 1; i >= 0; i--) {
3964 b = a->a_postorder[i];
3965 bsize = blocksize(b);
3966 b->b_offset = totsize;
3967 totsize += bsize;
3968 }
3969 last_extended_arg_count = extended_arg_count;
3970 extended_arg_count = 0;
3971 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3972 bsize = b->b_offset;
3973 for (i = 0; i < b->b_iused; i++) {
3974 struct instr *instr = &b->b_instr[i];
3975 /* Relative jumps are computed relative to
3976 the instruction pointer after fetching
3977 the jump instruction.
3978 */
3979 bsize += instrsize(instr);
3980 if (instr->i_jabs)
3981 instr->i_oparg = instr->i_target->b_offset;
3982 else if (instr->i_jrel) {
3983 int delta = instr->i_target->b_offset - bsize;
3984 instr->i_oparg = delta;
3985 }
3986 else
3987 continue;
3988 if (instr->i_oparg > 0xffff)
3989 extended_arg_count++;
3990 }
3991 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 /* XXX: This is an awful hack that could hurt performance, but
3994 on the bright side it should work until we come up
3995 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 The issue is that in the first loop blocksize() is called
3998 which calls instrsize() which requires i_oparg be set
3999 appropriately. There is a bootstrap problem because
4000 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 So we loop until we stop seeing new EXTENDED_ARGs.
4003 The only EXTENDED_ARGs that could be popping up are
4004 ones in jump instructions. So this should converge
4005 fairly quickly.
4006 */
4007 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004008}
4009
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004010static PyObject *
4011dict_keys_inorder(PyObject *dict, int offset)
4012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 PyObject *tuple, *k, *v;
4014 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 tuple = PyTuple_New(size);
4017 if (tuple == NULL)
4018 return NULL;
4019 while (PyDict_Next(dict, &pos, &k, &v)) {
4020 i = PyLong_AS_LONG(v);
4021 /* The keys of the dictionary are tuples. (see compiler_add_o)
4022 The object we want is always first, though. */
4023 k = PyTuple_GET_ITEM(k, 0);
4024 Py_INCREF(k);
4025 assert((i - offset) < size);
4026 assert((i - offset) >= 0);
4027 PyTuple_SET_ITEM(tuple, i - offset, k);
4028 }
4029 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004030}
4031
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004032static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004033compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 PySTEntryObject *ste = c->u->u_ste;
4036 int flags = 0, n;
4037 if (ste->ste_type != ModuleBlock)
4038 flags |= CO_NEWLOCALS;
4039 if (ste->ste_type == FunctionBlock) {
4040 if (!ste->ste_unoptimized)
4041 flags |= CO_OPTIMIZED;
4042 if (ste->ste_nested)
4043 flags |= CO_NESTED;
4044 if (ste->ste_generator)
4045 flags |= CO_GENERATOR;
4046 if (ste->ste_varargs)
4047 flags |= CO_VARARGS;
4048 if (ste->ste_varkeywords)
4049 flags |= CO_VARKEYWORDS;
4050 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 /* (Only) inherit compilerflags in PyCF_MASK */
4053 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 n = PyDict_Size(c->u->u_freevars);
4056 if (n < 0)
4057 return -1;
4058 if (n == 0) {
4059 n = PyDict_Size(c->u->u_cellvars);
4060 if (n < 0)
4061 return -1;
4062 if (n == 0) {
4063 flags |= CO_NOFREE;
4064 }
4065 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004068}
4069
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070static PyCodeObject *
4071makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 PyObject *tmp;
4074 PyCodeObject *co = NULL;
4075 PyObject *consts = NULL;
4076 PyObject *names = NULL;
4077 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 PyObject *name = NULL;
4079 PyObject *freevars = NULL;
4080 PyObject *cellvars = NULL;
4081 PyObject *bytecode = NULL;
4082 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 tmp = dict_keys_inorder(c->u->u_consts, 0);
4085 if (!tmp)
4086 goto error;
4087 consts = PySequence_List(tmp); /* optimize_code requires a list */
4088 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 names = dict_keys_inorder(c->u->u_names, 0);
4091 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4092 if (!consts || !names || !varnames)
4093 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4096 if (!cellvars)
4097 goto error;
4098 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4099 if (!freevars)
4100 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004101 nlocals = PyDict_Size(c->u->u_varnames);
4102 flags = compute_code_flags(c);
4103 if (flags < 0)
4104 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4107 if (!bytecode)
4108 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4111 if (!tmp)
4112 goto error;
4113 Py_DECREF(consts);
4114 consts = tmp;
4115
4116 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4117 nlocals, stackdepth(c), flags,
4118 bytecode, consts, names, varnames,
4119 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004120 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 c->u->u_firstlineno,
4122 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 Py_XDECREF(consts);
4125 Py_XDECREF(names);
4126 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 Py_XDECREF(name);
4128 Py_XDECREF(freevars);
4129 Py_XDECREF(cellvars);
4130 Py_XDECREF(bytecode);
4131 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004132}
4133
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004134
4135/* For debugging purposes only */
4136#if 0
4137static void
4138dump_instr(const struct instr *i)
4139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 const char *jrel = i->i_jrel ? "jrel " : "";
4141 const char *jabs = i->i_jabs ? "jabs " : "";
4142 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 *arg = '\0';
4145 if (i->i_hasarg)
4146 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4149 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004150}
4151
4152static void
4153dump_basicblock(const basicblock *b)
4154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 const char *seen = b->b_seen ? "seen " : "";
4156 const char *b_return = b->b_return ? "return " : "";
4157 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4158 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4159 if (b->b_instr) {
4160 int i;
4161 for (i = 0; i < b->b_iused; i++) {
4162 fprintf(stderr, " [%02d] ", i);
4163 dump_instr(b->b_instr + i);
4164 }
4165 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004166}
4167#endif
4168
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169static PyCodeObject *
4170assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 basicblock *b, *entryblock;
4173 struct assembler a;
4174 int i, j, nblocks;
4175 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 /* Make sure every block that falls off the end returns None.
4178 XXX NEXT_BLOCK() isn't quite right, because if the last
4179 block ends with a jump or return b_next shouldn't set.
4180 */
4181 if (!c->u->u_curblock->b_return) {
4182 NEXT_BLOCK(c);
4183 if (addNone)
4184 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4185 ADDOP(c, RETURN_VALUE);
4186 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 nblocks = 0;
4189 entryblock = NULL;
4190 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4191 nblocks++;
4192 entryblock = b;
4193 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 /* Set firstlineno if it wasn't explicitly set. */
4196 if (!c->u->u_firstlineno) {
4197 if (entryblock && entryblock->b_instr)
4198 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4199 else
4200 c->u->u_firstlineno = 1;
4201 }
4202 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4203 goto error;
4204 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 /* Can't modify the bytecode after computing jump offsets. */
4207 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 /* Emit code in reverse postorder from dfs. */
4210 for (i = a.a_nblocks - 1; i >= 0; i--) {
4211 b = a.a_postorder[i];
4212 for (j = 0; j < b->b_iused; j++)
4213 if (!assemble_emit(&a, &b->b_instr[j]))
4214 goto error;
4215 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4218 goto error;
4219 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4220 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004223 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004224 assemble_free(&a);
4225 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004226}
Georg Brandl8334fd92010-12-04 10:26:46 +00004227
4228#undef PyAST_Compile
4229PyAPI_FUNC(PyCodeObject *)
4230PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4231 PyArena *arena)
4232{
4233 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4234}
4235
4236