blob: 1722a5f97d99ac01ad7e269fd176970f8cba72cd [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_) {
1412 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
1413 if (!compiler_visit_expr(c, default_)) {
1414 return -1;
1415 }
1416 default_count++;
1417 }
1418 }
1419 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001420}
1421
1422static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001423compiler_visit_argannotation(struct compiler *c, identifier id,
1424 expr_ty annotation, PyObject *names)
1425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (annotation) {
1427 VISIT(c, expr, annotation);
1428 if (PyList_Append(names, id))
1429 return -1;
1430 }
1431 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001432}
1433
1434static int
1435compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1436 PyObject *names)
1437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 int i, error;
1439 for (i = 0; i < asdl_seq_LEN(args); i++) {
1440 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1441 error = compiler_visit_argannotation(
1442 c,
1443 arg->arg,
1444 arg->annotation,
1445 names);
1446 if (error)
1447 return error;
1448 }
1449 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001450}
1451
1452static int
1453compiler_visit_annotations(struct compiler *c, arguments_ty args,
1454 expr_ty returns)
1455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 /* Push arg annotations and a list of the argument names. Return the #
1457 of items pushed. The expressions are evaluated out-of-order wrt the
1458 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1461 */
1462 static identifier return_str;
1463 PyObject *names;
1464 int len;
1465 names = PyList_New(0);
1466 if (!names)
1467 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (compiler_visit_argannotations(c, args->args, names))
1470 goto error;
1471 if (args->varargannotation &&
1472 compiler_visit_argannotation(c, args->vararg,
1473 args->varargannotation, names))
1474 goto error;
1475 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1476 goto error;
1477 if (args->kwargannotation &&
1478 compiler_visit_argannotation(c, args->kwarg,
1479 args->kwargannotation, names))
1480 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (!return_str) {
1483 return_str = PyUnicode_InternFromString("return");
1484 if (!return_str)
1485 goto error;
1486 }
1487 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1488 goto error;
1489 }
1490
1491 len = PyList_GET_SIZE(names);
1492 if (len > 65534) {
1493 /* len must fit in 16 bits, and len is incremented below */
1494 PyErr_SetString(PyExc_SyntaxError,
1495 "too many annotations");
1496 goto error;
1497 }
1498 if (len) {
1499 /* convert names to a tuple and place on stack */
1500 PyObject *elt;
1501 int i;
1502 PyObject *s = PyTuple_New(len);
1503 if (!s)
1504 goto error;
1505 for (i = 0; i < len; i++) {
1506 elt = PyList_GET_ITEM(names, i);
1507 Py_INCREF(elt);
1508 PyTuple_SET_ITEM(s, i, elt);
1509 }
1510 ADDOP_O(c, LOAD_CONST, s, consts);
1511 Py_DECREF(s);
1512 len++; /* include the just-pushed tuple */
1513 }
1514 Py_DECREF(names);
1515 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001516
1517error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 Py_DECREF(names);
1519 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001520}
1521
1522static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523compiler_function(struct compiler *c, stmt_ty s)
1524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001526 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 arguments_ty args = s->v.FunctionDef.args;
1528 expr_ty returns = s->v.FunctionDef.returns;
1529 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1530 stmt_ty st;
1531 int i, n, docstring, kw_default_count = 0, arglength;
1532 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (!compiler_decorators(c, decos))
1537 return 0;
1538 if (args->kwonlyargs) {
1539 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1540 args->kw_defaults);
1541 if (res < 0)
1542 return 0;
1543 kw_default_count = res;
1544 }
1545 if (args->defaults)
1546 VISIT_SEQ(c, expr, args->defaults);
1547 num_annotations = compiler_visit_annotations(c, args, returns);
1548 if (num_annotations < 0)
1549 return 0;
1550 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001551
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001552 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1553 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 s->lineno))
1555 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1558 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001559 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 first_const = st->v.Expr.value->v.Str.s;
1561 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1562 compiler_exit_scope(c);
1563 return 0;
1564 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 c->u->u_argcount = asdl_seq_LEN(args->args);
1567 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1568 n = asdl_seq_LEN(s->v.FunctionDef.body);
1569 /* if there was a docstring, we need to skip the first statement */
1570 for (i = docstring; i < n; i++) {
1571 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1572 VISIT_IN_SCOPE(c, stmt, st);
1573 }
1574 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001575 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001577 if (qualname == NULL || co == NULL) {
1578 Py_XDECREF(qualname);
1579 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001581 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 arglength = asdl_seq_LEN(args->defaults);
1584 arglength |= kw_default_count << 8;
1585 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001586 compiler_make_closure(c, co, arglength, qualname);
1587 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 /* decorators */
1591 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1592 ADDOP_I(c, CALL_FUNCTION, 1);
1593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596}
1597
1598static int
1599compiler_class(struct compiler *c, stmt_ty s)
1600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 PyCodeObject *co;
1602 PyObject *str;
1603 int i;
1604 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (!compiler_decorators(c, decos))
1607 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 /* ultimately generate code for:
1610 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1611 where:
1612 <func> is a function/closure created from the class body;
1613 it has a single argument (__locals__) where the dict
1614 (or MutableSequence) representing the locals is passed
1615 <name> is the class name
1616 <bases> is the positional arguments and *varargs argument
1617 <keywords> is the keyword arguments and **kwds argument
1618 This borrows from compiler_call.
1619 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001622 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1623 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 return 0;
1625 /* this block represents what we do in the new scope */
1626 {
1627 /* use the class name for name mangling */
1628 Py_INCREF(s->v.ClassDef.name);
1629 Py_XDECREF(c->u->u_private);
1630 c->u->u_private = s->v.ClassDef.name;
1631 /* force it to have one mandatory argument */
1632 c->u->u_argcount = 1;
1633 /* load the first argument (__locals__) ... */
1634 ADDOP_I(c, LOAD_FAST, 0);
1635 /* ... and store it into f_locals */
1636 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1637 /* load (global) __name__ ... */
1638 str = PyUnicode_InternFromString("__name__");
1639 if (!str || !compiler_nameop(c, str, Load)) {
1640 Py_XDECREF(str);
1641 compiler_exit_scope(c);
1642 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001643 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 Py_DECREF(str);
1645 /* ... and store it as __module__ */
1646 str = PyUnicode_InternFromString("__module__");
1647 if (!str || !compiler_nameop(c, str, Store)) {
1648 Py_XDECREF(str);
1649 compiler_exit_scope(c);
1650 return 0;
1651 }
1652 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001653 /* store the __qualname__ */
1654 str = compiler_scope_qualname(c);
1655 if (!str) {
1656 compiler_exit_scope(c);
1657 return 0;
1658 }
1659 ADDOP_O(c, LOAD_CONST, str, consts);
1660 Py_DECREF(str);
1661 str = PyUnicode_InternFromString("__qualname__");
1662 if (!str || !compiler_nameop(c, str, Store)) {
1663 Py_XDECREF(str);
1664 compiler_exit_scope(c);
1665 return 0;
1666 }
1667 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 /* compile the body proper */
1669 if (!compiler_body(c, s->v.ClassDef.body)) {
1670 compiler_exit_scope(c);
1671 return 0;
1672 }
1673 /* return the (empty) __class__ cell */
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05001674 str = PyUnicode_InternFromString("@__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (str == NULL) {
1676 compiler_exit_scope(c);
1677 return 0;
1678 }
1679 i = compiler_lookup_arg(c->u->u_cellvars, str);
1680 Py_DECREF(str);
1681 if (i == -1) {
1682 /* This happens when nobody references the cell */
1683 PyErr_Clear();
1684 /* Return None */
1685 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1686 }
1687 else {
1688 /* Return the cell where to store __class__ */
1689 ADDOP_I(c, LOAD_CLOSURE, i);
1690 }
1691 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1692 /* create the code object */
1693 co = assemble(c, 1);
1694 }
1695 /* leave the new scope */
1696 compiler_exit_scope(c);
1697 if (co == NULL)
1698 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* 2. load the 'build_class' function */
1701 ADDOP(c, LOAD_BUILD_CLASS);
1702
1703 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001704 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 Py_DECREF(co);
1706
1707 /* 4. load class name */
1708 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1709
1710 /* 5. generate the rest of the code for the call */
1711 if (!compiler_call_helper(c, 2,
1712 s->v.ClassDef.bases,
1713 s->v.ClassDef.keywords,
1714 s->v.ClassDef.starargs,
1715 s->v.ClassDef.kwargs))
1716 return 0;
1717
1718 /* 6. apply decorators */
1719 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1720 ADDOP_I(c, CALL_FUNCTION, 1);
1721 }
1722
1723 /* 7. store into <name> */
1724 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1725 return 0;
1726 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001727}
1728
1729static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001730compiler_ifexp(struct compiler *c, expr_ty e)
1731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 basicblock *end, *next;
1733
1734 assert(e->kind == IfExp_kind);
1735 end = compiler_new_block(c);
1736 if (end == NULL)
1737 return 0;
1738 next = compiler_new_block(c);
1739 if (next == NULL)
1740 return 0;
1741 VISIT(c, expr, e->v.IfExp.test);
1742 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1743 VISIT(c, expr, e->v.IfExp.body);
1744 ADDOP_JREL(c, JUMP_FORWARD, end);
1745 compiler_use_next_block(c, next);
1746 VISIT(c, expr, e->v.IfExp.orelse);
1747 compiler_use_next_block(c, end);
1748 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001749}
1750
1751static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001752compiler_lambda(struct compiler *c, expr_ty e)
1753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001755 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 static identifier name;
1757 int kw_default_count = 0, arglength;
1758 arguments_ty args = e->v.Lambda.args;
1759 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (!name) {
1762 name = PyUnicode_InternFromString("<lambda>");
1763 if (!name)
1764 return 0;
1765 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (args->kwonlyargs) {
1768 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1769 args->kw_defaults);
1770 if (res < 0) return 0;
1771 kw_default_count = res;
1772 }
1773 if (args->defaults)
1774 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001775 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1776 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 /* Make None the first constant, so the lambda can't have a
1780 docstring. */
1781 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1782 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 c->u->u_argcount = asdl_seq_LEN(args->args);
1785 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1786 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1787 if (c->u->u_ste->ste_generator) {
1788 ADDOP_IN_SCOPE(c, POP_TOP);
1789 }
1790 else {
1791 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1792 }
1793 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001794 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001796 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 arglength = asdl_seq_LEN(args->defaults);
1800 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001801 compiler_make_closure(c, co, arglength, qualname);
1802 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 Py_DECREF(co);
1804
1805 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806}
1807
1808static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809compiler_if(struct compiler *c, stmt_ty s)
1810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 basicblock *end, *next;
1812 int constant;
1813 assert(s->kind == If_kind);
1814 end = compiler_new_block(c);
1815 if (end == NULL)
1816 return 0;
1817
Georg Brandl8334fd92010-12-04 10:26:46 +00001818 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 /* constant = 0: "if 0"
1820 * constant = 1: "if 1", "if 2", ...
1821 * constant = -1: rest */
1822 if (constant == 0) {
1823 if (s->v.If.orelse)
1824 VISIT_SEQ(c, stmt, s->v.If.orelse);
1825 } else if (constant == 1) {
1826 VISIT_SEQ(c, stmt, s->v.If.body);
1827 } else {
1828 if (s->v.If.orelse) {
1829 next = compiler_new_block(c);
1830 if (next == NULL)
1831 return 0;
1832 }
1833 else
1834 next = end;
1835 VISIT(c, expr, s->v.If.test);
1836 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1837 VISIT_SEQ(c, stmt, s->v.If.body);
1838 ADDOP_JREL(c, JUMP_FORWARD, end);
1839 if (s->v.If.orelse) {
1840 compiler_use_next_block(c, next);
1841 VISIT_SEQ(c, stmt, s->v.If.orelse);
1842 }
1843 }
1844 compiler_use_next_block(c, end);
1845 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846}
1847
1848static int
1849compiler_for(struct compiler *c, stmt_ty s)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 start = compiler_new_block(c);
1854 cleanup = compiler_new_block(c);
1855 end = compiler_new_block(c);
1856 if (start == NULL || end == NULL || cleanup == NULL)
1857 return 0;
1858 ADDOP_JREL(c, SETUP_LOOP, end);
1859 if (!compiler_push_fblock(c, LOOP, start))
1860 return 0;
1861 VISIT(c, expr, s->v.For.iter);
1862 ADDOP(c, GET_ITER);
1863 compiler_use_next_block(c, start);
1864 ADDOP_JREL(c, FOR_ITER, cleanup);
1865 VISIT(c, expr, s->v.For.target);
1866 VISIT_SEQ(c, stmt, s->v.For.body);
1867 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1868 compiler_use_next_block(c, cleanup);
1869 ADDOP(c, POP_BLOCK);
1870 compiler_pop_fblock(c, LOOP, start);
1871 VISIT_SEQ(c, stmt, s->v.For.orelse);
1872 compiler_use_next_block(c, end);
1873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874}
1875
1876static int
1877compiler_while(struct compiler *c, stmt_ty s)
1878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001880 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (constant == 0) {
1883 if (s->v.While.orelse)
1884 VISIT_SEQ(c, stmt, s->v.While.orelse);
1885 return 1;
1886 }
1887 loop = compiler_new_block(c);
1888 end = compiler_new_block(c);
1889 if (constant == -1) {
1890 anchor = compiler_new_block(c);
1891 if (anchor == NULL)
1892 return 0;
1893 }
1894 if (loop == NULL || end == NULL)
1895 return 0;
1896 if (s->v.While.orelse) {
1897 orelse = compiler_new_block(c);
1898 if (orelse == NULL)
1899 return 0;
1900 }
1901 else
1902 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 ADDOP_JREL(c, SETUP_LOOP, end);
1905 compiler_use_next_block(c, loop);
1906 if (!compiler_push_fblock(c, LOOP, loop))
1907 return 0;
1908 if (constant == -1) {
1909 VISIT(c, expr, s->v.While.test);
1910 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1911 }
1912 VISIT_SEQ(c, stmt, s->v.While.body);
1913 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 /* XXX should the two POP instructions be in a separate block
1916 if there is no else clause ?
1917 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (constant == -1) {
1920 compiler_use_next_block(c, anchor);
1921 ADDOP(c, POP_BLOCK);
1922 }
1923 compiler_pop_fblock(c, LOOP, loop);
1924 if (orelse != NULL) /* what if orelse is just pass? */
1925 VISIT_SEQ(c, stmt, s->v.While.orelse);
1926 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929}
1930
1931static int
1932compiler_continue(struct compiler *c)
1933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1935 static const char IN_FINALLY_ERROR_MSG[] =
1936 "'continue' not supported inside 'finally' clause";
1937 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 if (!c->u->u_nfblocks)
1940 return compiler_error(c, LOOP_ERROR_MSG);
1941 i = c->u->u_nfblocks - 1;
1942 switch (c->u->u_fblock[i].fb_type) {
1943 case LOOP:
1944 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1945 break;
1946 case EXCEPT:
1947 case FINALLY_TRY:
1948 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1949 /* Prevent continue anywhere under a finally
1950 even if hidden in a sub-try or except. */
1951 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1952 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1953 }
1954 if (i == -1)
1955 return compiler_error(c, LOOP_ERROR_MSG);
1956 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1957 break;
1958 case FINALLY_END:
1959 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1960 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963}
1964
1965/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966
1967 SETUP_FINALLY L
1968 <code for body>
1969 POP_BLOCK
1970 LOAD_CONST <None>
1971 L: <code for finalbody>
1972 END_FINALLY
1973
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974 The special instructions use the block stack. Each block
1975 stack entry contains the instruction that created it (here
1976 SETUP_FINALLY), the level of the value stack at the time the
1977 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 Pushes the current value stack level and the label
1981 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 Pops en entry from the block stack, and pops the value
1984 stack until its level is the same as indicated on the
1985 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 Pops a variable number of entries from the *value* stack
1988 and re-raises the exception they specify. The number of
1989 entries popped depends on the (pseudo) exception type.
1990
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 The block stack is unwound when an exception is raised:
1992 when a SETUP_FINALLY entry is found, the exception is pushed
1993 onto the value stack (and the exception condition is cleared),
1994 and the interpreter jumps to the label gotten from the block
1995 stack.
1996*/
1997
1998static int
1999compiler_try_finally(struct compiler *c, stmt_ty s)
2000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 basicblock *body, *end;
2002 body = compiler_new_block(c);
2003 end = compiler_new_block(c);
2004 if (body == NULL || end == NULL)
2005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 ADDOP_JREL(c, SETUP_FINALLY, end);
2008 compiler_use_next_block(c, body);
2009 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2010 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002011 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2012 if (!compiler_try_except(c, s))
2013 return 0;
2014 }
2015 else {
2016 VISIT_SEQ(c, stmt, s->v.Try.body);
2017 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 ADDOP(c, POP_BLOCK);
2019 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2022 compiler_use_next_block(c, end);
2023 if (!compiler_push_fblock(c, FINALLY_END, end))
2024 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002025 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 ADDOP(c, END_FINALLY);
2027 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030}
2031
2032/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002033 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034 (The contents of the value stack is shown in [], with the top
2035 at the right; 'tb' is trace-back info, 'val' the exception's
2036 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037
2038 Value stack Label Instruction Argument
2039 [] SETUP_EXCEPT L1
2040 [] <code for S>
2041 [] POP_BLOCK
2042 [] JUMP_FORWARD L0
2043
2044 [tb, val, exc] L1: DUP )
2045 [tb, val, exc, exc] <evaluate E1> )
2046 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2047 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2048 [tb, val, exc] POP
2049 [tb, val] <assign to V1> (or POP if no V1)
2050 [tb] POP
2051 [] <code for S1>
2052 JUMP_FORWARD L0
2053
2054 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 .............................etc.......................
2056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2058
2059 [] L0: <next statement>
2060
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 Of course, parts are not generated if Vi or Ei is not present.
2062*/
2063static int
2064compiler_try_except(struct compiler *c, stmt_ty s)
2065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 basicblock *body, *orelse, *except, *end;
2067 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 body = compiler_new_block(c);
2070 except = compiler_new_block(c);
2071 orelse = compiler_new_block(c);
2072 end = compiler_new_block(c);
2073 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2074 return 0;
2075 ADDOP_JREL(c, SETUP_EXCEPT, except);
2076 compiler_use_next_block(c, body);
2077 if (!compiler_push_fblock(c, EXCEPT, body))
2078 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002079 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 ADDOP(c, POP_BLOCK);
2081 compiler_pop_fblock(c, EXCEPT, body);
2082 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002083 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 compiler_use_next_block(c, except);
2085 for (i = 0; i < n; i++) {
2086 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002087 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (!handler->v.ExceptHandler.type && i < n-1)
2089 return compiler_error(c, "default 'except:' must be last");
2090 c->u->u_lineno_set = 0;
2091 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002092 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 except = compiler_new_block(c);
2094 if (except == NULL)
2095 return 0;
2096 if (handler->v.ExceptHandler.type) {
2097 ADDOP(c, DUP_TOP);
2098 VISIT(c, expr, handler->v.ExceptHandler.type);
2099 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2100 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2101 }
2102 ADDOP(c, POP_TOP);
2103 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002104 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002105
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002106 cleanup_end = compiler_new_block(c);
2107 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002108 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002109 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002110
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002111 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2112 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002114 /*
2115 try:
2116 # body
2117 except type as name:
2118 try:
2119 # body
2120 finally:
2121 name = None
2122 del name
2123 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002125 /* second try: */
2126 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2127 compiler_use_next_block(c, cleanup_body);
2128 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2129 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002131 /* second # body */
2132 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2133 ADDOP(c, POP_BLOCK);
2134 ADDOP(c, POP_EXCEPT);
2135 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002137 /* finally: */
2138 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2139 compiler_use_next_block(c, cleanup_end);
2140 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2141 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002143 /* name = None */
2144 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2145 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002147 /* del name */
2148 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002150 ADDOP(c, END_FINALLY);
2151 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 }
2153 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002154 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002156 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002157 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002158 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159
Guido van Rossumb940e112007-01-10 16:19:56 +00002160 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002161 ADDOP(c, POP_TOP);
2162 compiler_use_next_block(c, cleanup_body);
2163 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2164 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002166 ADDOP(c, POP_EXCEPT);
2167 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 }
2169 ADDOP_JREL(c, JUMP_FORWARD, end);
2170 compiler_use_next_block(c, except);
2171 }
2172 ADDOP(c, END_FINALLY);
2173 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002174 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 compiler_use_next_block(c, end);
2176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177}
2178
2179static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002180compiler_try(struct compiler *c, stmt_ty s) {
2181 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2182 return compiler_try_finally(c, s);
2183 else
2184 return compiler_try_except(c, s);
2185}
2186
2187
2188static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189compiler_import_as(struct compiler *c, identifier name, identifier asname)
2190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* The IMPORT_NAME opcode was already generated. This function
2192 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 If there is a dot in name, we need to split it and emit a
2195 LOAD_ATTR for each name.
2196 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2198 PyUnicode_GET_LENGTH(name), 1);
2199 if (dot == -2)
2200 return -1;
2201 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002203 Py_ssize_t pos = dot + 1;
2204 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002206 dot = PyUnicode_FindChar(name, '.', pos,
2207 PyUnicode_GET_LENGTH(name), 1);
2208 if (dot == -2)
2209 return -1;
2210 attr = PyUnicode_Substring(name, pos,
2211 (dot != -1) ? dot :
2212 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (!attr)
2214 return -1;
2215 ADDOP_O(c, LOAD_ATTR, attr, names);
2216 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 }
2219 }
2220 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221}
2222
2223static int
2224compiler_import(struct compiler *c, stmt_ty s)
2225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* The Import node stores a module name like a.b.c as a single
2227 string. This is convenient for all cases except
2228 import a.b.c as d
2229 where we need to parse that string to extract the individual
2230 module names.
2231 XXX Perhaps change the representation to make this case simpler?
2232 */
2233 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 for (i = 0; i < n; i++) {
2236 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2237 int r;
2238 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 level = PyLong_FromLong(0);
2241 if (level == NULL)
2242 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 ADDOP_O(c, LOAD_CONST, level, consts);
2245 Py_DECREF(level);
2246 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2247 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (alias->asname) {
2250 r = compiler_import_as(c, alias->name, alias->asname);
2251 if (!r)
2252 return r;
2253 }
2254 else {
2255 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002256 Py_ssize_t dot = PyUnicode_FindChar(
2257 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2258 if (dot != -1)
2259 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002261 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 Py_DECREF(tmp);
2263 }
2264 if (!r)
2265 return r;
2266 }
2267 }
2268 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269}
2270
2271static int
2272compiler_from_import(struct compiler *c, stmt_ty s)
2273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyObject *names = PyTuple_New(n);
2277 PyObject *level;
2278 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 if (!empty_string) {
2281 empty_string = PyUnicode_FromString("");
2282 if (!empty_string)
2283 return 0;
2284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 if (!names)
2287 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 level = PyLong_FromLong(s->v.ImportFrom.level);
2290 if (!level) {
2291 Py_DECREF(names);
2292 return 0;
2293 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* build up the names */
2296 for (i = 0; i < n; i++) {
2297 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2298 Py_INCREF(alias->name);
2299 PyTuple_SET_ITEM(names, i, alias->name);
2300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2303 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2304 Py_DECREF(level);
2305 Py_DECREF(names);
2306 return compiler_error(c, "from __future__ imports must occur "
2307 "at the beginning of the file");
2308 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 ADDOP_O(c, LOAD_CONST, level, consts);
2311 Py_DECREF(level);
2312 ADDOP_O(c, LOAD_CONST, names, consts);
2313 Py_DECREF(names);
2314 if (s->v.ImportFrom.module) {
2315 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2316 }
2317 else {
2318 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2319 }
2320 for (i = 0; i < n; i++) {
2321 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2322 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002324 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 assert(n == 1);
2326 ADDOP(c, IMPORT_STAR);
2327 return 1;
2328 }
2329
2330 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2331 store_name = alias->name;
2332 if (alias->asname)
2333 store_name = alias->asname;
2334
2335 if (!compiler_nameop(c, store_name, Store)) {
2336 Py_DECREF(names);
2337 return 0;
2338 }
2339 }
2340 /* remove imported module */
2341 ADDOP(c, POP_TOP);
2342 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343}
2344
2345static int
2346compiler_assert(struct compiler *c, stmt_ty s)
2347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 static PyObject *assertion_error = NULL;
2349 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350
Georg Brandl8334fd92010-12-04 10:26:46 +00002351 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 return 1;
2353 if (assertion_error == NULL) {
2354 assertion_error = PyUnicode_InternFromString("AssertionError");
2355 if (assertion_error == NULL)
2356 return 0;
2357 }
2358 if (s->v.Assert.test->kind == Tuple_kind &&
2359 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2360 const char* msg =
2361 "assertion is always true, perhaps remove parentheses?";
2362 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2363 c->u->u_lineno, NULL, NULL) == -1)
2364 return 0;
2365 }
2366 VISIT(c, expr, s->v.Assert.test);
2367 end = compiler_new_block(c);
2368 if (end == NULL)
2369 return 0;
2370 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2371 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2372 if (s->v.Assert.msg) {
2373 VISIT(c, expr, s->v.Assert.msg);
2374 ADDOP_I(c, CALL_FUNCTION, 1);
2375 }
2376 ADDOP_I(c, RAISE_VARARGS, 1);
2377 compiler_use_next_block(c, end);
2378 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379}
2380
2381static int
2382compiler_visit_stmt(struct compiler *c, stmt_ty s)
2383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* Always assign a lineno to the next instruction for a stmt. */
2387 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002388 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 switch (s->kind) {
2392 case FunctionDef_kind:
2393 return compiler_function(c, s);
2394 case ClassDef_kind:
2395 return compiler_class(c, s);
2396 case Return_kind:
2397 if (c->u->u_ste->ste_type != FunctionBlock)
2398 return compiler_error(c, "'return' outside function");
2399 if (s->v.Return.value) {
2400 VISIT(c, expr, s->v.Return.value);
2401 }
2402 else
2403 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2404 ADDOP(c, RETURN_VALUE);
2405 break;
2406 case Delete_kind:
2407 VISIT_SEQ(c, expr, s->v.Delete.targets)
2408 break;
2409 case Assign_kind:
2410 n = asdl_seq_LEN(s->v.Assign.targets);
2411 VISIT(c, expr, s->v.Assign.value);
2412 for (i = 0; i < n; i++) {
2413 if (i < n - 1)
2414 ADDOP(c, DUP_TOP);
2415 VISIT(c, expr,
2416 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2417 }
2418 break;
2419 case AugAssign_kind:
2420 return compiler_augassign(c, s);
2421 case For_kind:
2422 return compiler_for(c, s);
2423 case While_kind:
2424 return compiler_while(c, s);
2425 case If_kind:
2426 return compiler_if(c, s);
2427 case Raise_kind:
2428 n = 0;
2429 if (s->v.Raise.exc) {
2430 VISIT(c, expr, s->v.Raise.exc);
2431 n++;
2432 if (s->v.Raise.cause) {
2433 VISIT(c, expr, s->v.Raise.cause);
2434 n++;
2435 }
2436 }
2437 ADDOP_I(c, RAISE_VARARGS, n);
2438 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002439 case Try_kind:
2440 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 case Assert_kind:
2442 return compiler_assert(c, s);
2443 case Import_kind:
2444 return compiler_import(c, s);
2445 case ImportFrom_kind:
2446 return compiler_from_import(c, s);
2447 case Global_kind:
2448 case Nonlocal_kind:
2449 break;
2450 case Expr_kind:
2451 if (c->c_interactive && c->c_nestlevel <= 1) {
2452 VISIT(c, expr, s->v.Expr.value);
2453 ADDOP(c, PRINT_EXPR);
2454 }
2455 else if (s->v.Expr.value->kind != Str_kind &&
2456 s->v.Expr.value->kind != Num_kind) {
2457 VISIT(c, expr, s->v.Expr.value);
2458 ADDOP(c, POP_TOP);
2459 }
2460 break;
2461 case Pass_kind:
2462 break;
2463 case Break_kind:
2464 if (!compiler_in_loop(c))
2465 return compiler_error(c, "'break' outside loop");
2466 ADDOP(c, BREAK_LOOP);
2467 break;
2468 case Continue_kind:
2469 return compiler_continue(c);
2470 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002471 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 }
2473 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474}
2475
2476static int
2477unaryop(unaryop_ty op)
2478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 switch (op) {
2480 case Invert:
2481 return UNARY_INVERT;
2482 case Not:
2483 return UNARY_NOT;
2484 case UAdd:
2485 return UNARY_POSITIVE;
2486 case USub:
2487 return UNARY_NEGATIVE;
2488 default:
2489 PyErr_Format(PyExc_SystemError,
2490 "unary op %d should not be possible", op);
2491 return 0;
2492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493}
2494
2495static int
2496binop(struct compiler *c, operator_ty op)
2497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 switch (op) {
2499 case Add:
2500 return BINARY_ADD;
2501 case Sub:
2502 return BINARY_SUBTRACT;
2503 case Mult:
2504 return BINARY_MULTIPLY;
2505 case Div:
2506 return BINARY_TRUE_DIVIDE;
2507 case Mod:
2508 return BINARY_MODULO;
2509 case Pow:
2510 return BINARY_POWER;
2511 case LShift:
2512 return BINARY_LSHIFT;
2513 case RShift:
2514 return BINARY_RSHIFT;
2515 case BitOr:
2516 return BINARY_OR;
2517 case BitXor:
2518 return BINARY_XOR;
2519 case BitAnd:
2520 return BINARY_AND;
2521 case FloorDiv:
2522 return BINARY_FLOOR_DIVIDE;
2523 default:
2524 PyErr_Format(PyExc_SystemError,
2525 "binary op %d should not be possible", op);
2526 return 0;
2527 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002528}
2529
2530static int
2531cmpop(cmpop_ty op)
2532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 switch (op) {
2534 case Eq:
2535 return PyCmp_EQ;
2536 case NotEq:
2537 return PyCmp_NE;
2538 case Lt:
2539 return PyCmp_LT;
2540 case LtE:
2541 return PyCmp_LE;
2542 case Gt:
2543 return PyCmp_GT;
2544 case GtE:
2545 return PyCmp_GE;
2546 case Is:
2547 return PyCmp_IS;
2548 case IsNot:
2549 return PyCmp_IS_NOT;
2550 case In:
2551 return PyCmp_IN;
2552 case NotIn:
2553 return PyCmp_NOT_IN;
2554 default:
2555 return PyCmp_BAD;
2556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557}
2558
2559static int
2560inplace_binop(struct compiler *c, operator_ty op)
2561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 switch (op) {
2563 case Add:
2564 return INPLACE_ADD;
2565 case Sub:
2566 return INPLACE_SUBTRACT;
2567 case Mult:
2568 return INPLACE_MULTIPLY;
2569 case Div:
2570 return INPLACE_TRUE_DIVIDE;
2571 case Mod:
2572 return INPLACE_MODULO;
2573 case Pow:
2574 return INPLACE_POWER;
2575 case LShift:
2576 return INPLACE_LSHIFT;
2577 case RShift:
2578 return INPLACE_RSHIFT;
2579 case BitOr:
2580 return INPLACE_OR;
2581 case BitXor:
2582 return INPLACE_XOR;
2583 case BitAnd:
2584 return INPLACE_AND;
2585 case FloorDiv:
2586 return INPLACE_FLOOR_DIVIDE;
2587 default:
2588 PyErr_Format(PyExc_SystemError,
2589 "inplace binary op %d should not be possible", op);
2590 return 0;
2591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592}
2593
2594static int
2595compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 int op, scope, arg;
2598 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 PyObject *dict = c->u->u_names;
2601 PyObject *mangled;
2602 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 mangled = _Py_Mangle(c->u->u_private, name);
2605 if (!mangled)
2606 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 op = 0;
2609 optype = OP_NAME;
2610 scope = PyST_GetScope(c->u->u_ste, mangled);
2611 switch (scope) {
2612 case FREE:
2613 dict = c->u->u_freevars;
2614 optype = OP_DEREF;
2615 break;
2616 case CELL:
2617 dict = c->u->u_cellvars;
2618 optype = OP_DEREF;
2619 break;
2620 case LOCAL:
2621 if (c->u->u_ste->ste_type == FunctionBlock)
2622 optype = OP_FAST;
2623 break;
2624 case GLOBAL_IMPLICIT:
2625 if (c->u->u_ste->ste_type == FunctionBlock &&
2626 !c->u->u_ste->ste_unoptimized)
2627 optype = OP_GLOBAL;
2628 break;
2629 case GLOBAL_EXPLICIT:
2630 optype = OP_GLOBAL;
2631 break;
2632 default:
2633 /* scope can be 0 */
2634 break;
2635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 switch (optype) {
2641 case OP_DEREF:
2642 switch (ctx) {
2643 case Load: op = LOAD_DEREF; break;
2644 case Store: op = STORE_DEREF; break;
2645 case AugLoad:
2646 case AugStore:
2647 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002648 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 case Param:
2650 default:
2651 PyErr_SetString(PyExc_SystemError,
2652 "param invalid for deref variable");
2653 return 0;
2654 }
2655 break;
2656 case OP_FAST:
2657 switch (ctx) {
2658 case Load: op = LOAD_FAST; break;
2659 case Store: op = STORE_FAST; break;
2660 case Del: op = DELETE_FAST; break;
2661 case AugLoad:
2662 case AugStore:
2663 break;
2664 case Param:
2665 default:
2666 PyErr_SetString(PyExc_SystemError,
2667 "param invalid for local variable");
2668 return 0;
2669 }
2670 ADDOP_O(c, op, mangled, varnames);
2671 Py_DECREF(mangled);
2672 return 1;
2673 case OP_GLOBAL:
2674 switch (ctx) {
2675 case Load: op = LOAD_GLOBAL; break;
2676 case Store: op = STORE_GLOBAL; break;
2677 case Del: op = DELETE_GLOBAL; break;
2678 case AugLoad:
2679 case AugStore:
2680 break;
2681 case Param:
2682 default:
2683 PyErr_SetString(PyExc_SystemError,
2684 "param invalid for global variable");
2685 return 0;
2686 }
2687 break;
2688 case OP_NAME:
2689 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002690 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 case Store: op = STORE_NAME; break;
2692 case Del: op = DELETE_NAME; break;
2693 case AugLoad:
2694 case AugStore:
2695 break;
2696 case Param:
2697 default:
2698 PyErr_SetString(PyExc_SystemError,
2699 "param invalid for name variable");
2700 return 0;
2701 }
2702 break;
2703 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 assert(op);
2706 arg = compiler_add_o(c, dict, mangled);
2707 Py_DECREF(mangled);
2708 if (arg < 0)
2709 return 0;
2710 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711}
2712
2713static int
2714compiler_boolop(struct compiler *c, expr_ty e)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 basicblock *end;
2717 int jumpi, i, n;
2718 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 assert(e->kind == BoolOp_kind);
2721 if (e->v.BoolOp.op == And)
2722 jumpi = JUMP_IF_FALSE_OR_POP;
2723 else
2724 jumpi = JUMP_IF_TRUE_OR_POP;
2725 end = compiler_new_block(c);
2726 if (end == NULL)
2727 return 0;
2728 s = e->v.BoolOp.values;
2729 n = asdl_seq_LEN(s) - 1;
2730 assert(n >= 0);
2731 for (i = 0; i < n; ++i) {
2732 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2733 ADDOP_JABS(c, jumpi, end);
2734 }
2735 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2736 compiler_use_next_block(c, end);
2737 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738}
2739
2740static int
2741compiler_list(struct compiler *c, expr_ty e)
2742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 int n = asdl_seq_LEN(e->v.List.elts);
2744 if (e->v.List.ctx == Store) {
2745 int i, seen_star = 0;
2746 for (i = 0; i < n; i++) {
2747 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2748 if (elt->kind == Starred_kind && !seen_star) {
2749 if ((i >= (1 << 8)) ||
2750 (n-i-1 >= (INT_MAX >> 8)))
2751 return compiler_error(c,
2752 "too many expressions in "
2753 "star-unpacking assignment");
2754 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2755 seen_star = 1;
2756 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2757 } else if (elt->kind == Starred_kind) {
2758 return compiler_error(c,
2759 "two starred expressions in assignment");
2760 }
2761 }
2762 if (!seen_star) {
2763 ADDOP_I(c, UNPACK_SEQUENCE, n);
2764 }
2765 }
2766 VISIT_SEQ(c, expr, e->v.List.elts);
2767 if (e->v.List.ctx == Load) {
2768 ADDOP_I(c, BUILD_LIST, n);
2769 }
2770 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771}
2772
2773static int
2774compiler_tuple(struct compiler *c, expr_ty e)
2775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 int n = asdl_seq_LEN(e->v.Tuple.elts);
2777 if (e->v.Tuple.ctx == Store) {
2778 int i, seen_star = 0;
2779 for (i = 0; i < n; i++) {
2780 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2781 if (elt->kind == Starred_kind && !seen_star) {
2782 if ((i >= (1 << 8)) ||
2783 (n-i-1 >= (INT_MAX >> 8)))
2784 return compiler_error(c,
2785 "too many expressions in "
2786 "star-unpacking assignment");
2787 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2788 seen_star = 1;
2789 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2790 } else if (elt->kind == Starred_kind) {
2791 return compiler_error(c,
2792 "two starred expressions in assignment");
2793 }
2794 }
2795 if (!seen_star) {
2796 ADDOP_I(c, UNPACK_SEQUENCE, n);
2797 }
2798 }
2799 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2800 if (e->v.Tuple.ctx == Load) {
2801 ADDOP_I(c, BUILD_TUPLE, n);
2802 }
2803 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804}
2805
2806static int
2807compiler_compare(struct compiler *c, expr_ty e)
2808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 int i, n;
2810 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2813 VISIT(c, expr, e->v.Compare.left);
2814 n = asdl_seq_LEN(e->v.Compare.ops);
2815 assert(n > 0);
2816 if (n > 1) {
2817 cleanup = compiler_new_block(c);
2818 if (cleanup == NULL)
2819 return 0;
2820 VISIT(c, expr,
2821 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2822 }
2823 for (i = 1; i < n; i++) {
2824 ADDOP(c, DUP_TOP);
2825 ADDOP(c, ROT_THREE);
2826 ADDOP_I(c, COMPARE_OP,
2827 cmpop((cmpop_ty)(asdl_seq_GET(
2828 e->v.Compare.ops, i - 1))));
2829 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2830 NEXT_BLOCK(c);
2831 if (i < (n - 1))
2832 VISIT(c, expr,
2833 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2834 }
2835 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2836 ADDOP_I(c, COMPARE_OP,
2837 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2838 if (n > 1) {
2839 basicblock *end = compiler_new_block(c);
2840 if (end == NULL)
2841 return 0;
2842 ADDOP_JREL(c, JUMP_FORWARD, end);
2843 compiler_use_next_block(c, cleanup);
2844 ADDOP(c, ROT_TWO);
2845 ADDOP(c, POP_TOP);
2846 compiler_use_next_block(c, end);
2847 }
2848 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849}
2850
2851static int
2852compiler_call(struct compiler *c, expr_ty e)
2853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 VISIT(c, expr, e->v.Call.func);
2855 return compiler_call_helper(c, 0,
2856 e->v.Call.args,
2857 e->v.Call.keywords,
2858 e->v.Call.starargs,
2859 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002860}
2861
2862/* shared code between compiler_call and compiler_class */
2863static int
2864compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 int n, /* Args already pushed */
2866 asdl_seq *args,
2867 asdl_seq *keywords,
2868 expr_ty starargs,
2869 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 n += asdl_seq_LEN(args);
2874 VISIT_SEQ(c, expr, args);
2875 if (keywords) {
2876 VISIT_SEQ(c, keyword, keywords);
2877 n |= asdl_seq_LEN(keywords) << 8;
2878 }
2879 if (starargs) {
2880 VISIT(c, expr, starargs);
2881 code |= 1;
2882 }
2883 if (kwargs) {
2884 VISIT(c, expr, kwargs);
2885 code |= 2;
2886 }
2887 switch (code) {
2888 case 0:
2889 ADDOP_I(c, CALL_FUNCTION, n);
2890 break;
2891 case 1:
2892 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2893 break;
2894 case 2:
2895 ADDOP_I(c, CALL_FUNCTION_KW, n);
2896 break;
2897 case 3:
2898 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2899 break;
2900 }
2901 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002902}
2903
Nick Coghlan650f0d02007-04-15 12:05:43 +00002904
2905/* List and set comprehensions and generator expressions work by creating a
2906 nested function to perform the actual iteration. This means that the
2907 iteration variables don't leak into the current scope.
2908 The defined function is called immediately following its definition, with the
2909 result of that call being the result of the expression.
2910 The LC/SC version returns the populated container, while the GE version is
2911 flagged in symtable.c as a generator, so it returns the generator object
2912 when the function is called.
2913 This code *knows* that the loop cannot contain break, continue, or return,
2914 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2915
2916 Possible cleanups:
2917 - iterate over the generator sequence instead of using recursion
2918*/
2919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921compiler_comprehension_generator(struct compiler *c,
2922 asdl_seq *generators, int gen_index,
2923 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 /* generate code for the iterator, then each of the ifs,
2926 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 comprehension_ty gen;
2929 basicblock *start, *anchor, *skip, *if_cleanup;
2930 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 start = compiler_new_block(c);
2933 skip = compiler_new_block(c);
2934 if_cleanup = compiler_new_block(c);
2935 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2938 anchor == NULL)
2939 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 if (gen_index == 0) {
2944 /* Receive outermost iter as an implicit argument */
2945 c->u->u_argcount = 1;
2946 ADDOP_I(c, LOAD_FAST, 0);
2947 }
2948 else {
2949 /* Sub-iter - calculate on the fly */
2950 VISIT(c, expr, gen->iter);
2951 ADDOP(c, GET_ITER);
2952 }
2953 compiler_use_next_block(c, start);
2954 ADDOP_JREL(c, FOR_ITER, anchor);
2955 NEXT_BLOCK(c);
2956 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 /* XXX this needs to be cleaned up...a lot! */
2959 n = asdl_seq_LEN(gen->ifs);
2960 for (i = 0; i < n; i++) {
2961 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2962 VISIT(c, expr, e);
2963 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2964 NEXT_BLOCK(c);
2965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 if (++gen_index < asdl_seq_LEN(generators))
2968 if (!compiler_comprehension_generator(c,
2969 generators, gen_index,
2970 elt, val, type))
2971 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 /* only append after the last for generator */
2974 if (gen_index >= asdl_seq_LEN(generators)) {
2975 /* comprehension specific code */
2976 switch (type) {
2977 case COMP_GENEXP:
2978 VISIT(c, expr, elt);
2979 ADDOP(c, YIELD_VALUE);
2980 ADDOP(c, POP_TOP);
2981 break;
2982 case COMP_LISTCOMP:
2983 VISIT(c, expr, elt);
2984 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2985 break;
2986 case COMP_SETCOMP:
2987 VISIT(c, expr, elt);
2988 ADDOP_I(c, SET_ADD, gen_index + 1);
2989 break;
2990 case COMP_DICTCOMP:
2991 /* With 'd[k] = v', v is evaluated before k, so we do
2992 the same. */
2993 VISIT(c, expr, val);
2994 VISIT(c, expr, elt);
2995 ADDOP_I(c, MAP_ADD, gen_index + 1);
2996 break;
2997 default:
2998 return 0;
2999 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 compiler_use_next_block(c, skip);
3002 }
3003 compiler_use_next_block(c, if_cleanup);
3004 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3005 compiler_use_next_block(c, anchor);
3006
3007 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008}
3009
3010static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003011compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 PyCodeObject *co = NULL;
3015 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003016 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 outermost_iter = ((comprehension_ty)
3019 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003020
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003021 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3022 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 if (type != COMP_GENEXP) {
3026 int op;
3027 switch (type) {
3028 case COMP_LISTCOMP:
3029 op = BUILD_LIST;
3030 break;
3031 case COMP_SETCOMP:
3032 op = BUILD_SET;
3033 break;
3034 case COMP_DICTCOMP:
3035 op = BUILD_MAP;
3036 break;
3037 default:
3038 PyErr_Format(PyExc_SystemError,
3039 "unknown comprehension type %d", type);
3040 goto error_in_scope;
3041 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 ADDOP_I(c, op, 0);
3044 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 if (!compiler_comprehension_generator(c, generators, 0, elt,
3047 val, type))
3048 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 if (type != COMP_GENEXP) {
3051 ADDOP(c, RETURN_VALUE);
3052 }
3053
3054 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003055 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003057 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 goto error;
3059
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003060 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003062 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 Py_DECREF(co);
3064
3065 VISIT(c, expr, outermost_iter);
3066 ADDOP(c, GET_ITER);
3067 ADDOP_I(c, CALL_FUNCTION, 1);
3068 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003069error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003071error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003072 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 Py_XDECREF(co);
3074 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003075}
3076
3077static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078compiler_genexp(struct compiler *c, expr_ty e)
3079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 static identifier name;
3081 if (!name) {
3082 name = PyUnicode_FromString("<genexpr>");
3083 if (!name)
3084 return 0;
3085 }
3086 assert(e->kind == GeneratorExp_kind);
3087 return compiler_comprehension(c, e, COMP_GENEXP, name,
3088 e->v.GeneratorExp.generators,
3089 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090}
3091
3092static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003093compiler_listcomp(struct compiler *c, expr_ty e)
3094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 static identifier name;
3096 if (!name) {
3097 name = PyUnicode_FromString("<listcomp>");
3098 if (!name)
3099 return 0;
3100 }
3101 assert(e->kind == ListComp_kind);
3102 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3103 e->v.ListComp.generators,
3104 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003105}
3106
3107static int
3108compiler_setcomp(struct compiler *c, expr_ty e)
3109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 static identifier name;
3111 if (!name) {
3112 name = PyUnicode_FromString("<setcomp>");
3113 if (!name)
3114 return 0;
3115 }
3116 assert(e->kind == SetComp_kind);
3117 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3118 e->v.SetComp.generators,
3119 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003120}
3121
3122
3123static int
3124compiler_dictcomp(struct compiler *c, expr_ty e)
3125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 static identifier name;
3127 if (!name) {
3128 name = PyUnicode_FromString("<dictcomp>");
3129 if (!name)
3130 return 0;
3131 }
3132 assert(e->kind == DictComp_kind);
3133 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3134 e->v.DictComp.generators,
3135 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003136}
3137
3138
3139static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140compiler_visit_keyword(struct compiler *c, keyword_ty k)
3141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3143 VISIT(c, expr, k->value);
3144 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145}
3146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 whether they are true or false.
3149
3150 Return values: 1 for true, 0 for false, -1 for non-constant.
3151 */
3152
3153static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003154expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 char *id;
3157 switch (e->kind) {
3158 case Ellipsis_kind:
3159 return 1;
3160 case Num_kind:
3161 return PyObject_IsTrue(e->v.Num.n);
3162 case Str_kind:
3163 return PyObject_IsTrue(e->v.Str.s);
3164 case Name_kind:
3165 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003166 id = PyUnicode_AsUTF8(e->v.Name.id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 if (strcmp(id, "True") == 0) return 1;
3168 if (strcmp(id, "False") == 0) return 0;
3169 if (strcmp(id, "None") == 0) return 0;
3170 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003171 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 /* fall through */
3173 default:
3174 return -1;
3175 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176}
3177
Guido van Rossumc2e20742006-02-27 22:32:47 +00003178/*
3179 Implements the with statement from PEP 343.
3180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003182
3183 with EXPR as VAR:
3184 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185
Guido van Rossumc2e20742006-02-27 22:32:47 +00003186 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187
Thomas Wouters477c8d52006-05-27 19:21:47 +00003188 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003189 exit = context.__exit__ # not calling it
3190 value = context.__enter__()
3191 try:
3192 VAR = value # if VAR present in the syntax
3193 BLOCK
3194 finally:
3195 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003197 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003199 exit(*exc)
3200 */
3201static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003202compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003203{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003204 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003205 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003206
3207 assert(s->kind == With_kind);
3208
Guido van Rossumc2e20742006-02-27 22:32:47 +00003209 block = compiler_new_block(c);
3210 finally = compiler_new_block(c);
3211 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003212 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003213
Thomas Wouters477c8d52006-05-27 19:21:47 +00003214 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003215 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003216 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003217
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003218 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003219 compiler_use_next_block(c, block);
3220 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003221 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003222 }
3223
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003224 if (item->optional_vars) {
3225 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003226 }
3227 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003229 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003230 }
3231
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003232 pos++;
3233 if (pos == asdl_seq_LEN(s->v.With.items))
3234 /* BLOCK code */
3235 VISIT_SEQ(c, stmt, s->v.With.body)
3236 else if (!compiler_with(c, s, pos))
3237 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003238
3239 /* End of try block; start the finally block */
3240 ADDOP(c, POP_BLOCK);
3241 compiler_pop_fblock(c, FINALLY_TRY, block);
3242
3243 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3244 compiler_use_next_block(c, finally);
3245 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003246 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003247
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003248 /* Finally block starts; context.__exit__ is on the stack under
3249 the exception or return information. Just issue our magic
3250 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003251 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003252
3253 /* Finally block ends. */
3254 ADDOP(c, END_FINALLY);
3255 compiler_pop_fblock(c, FINALLY_END, finally);
3256 return 1;
3257}
3258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259static int
3260compiler_visit_expr(struct compiler *c, expr_ty e)
3261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 /* If expr e has a different line number than the last expr/stmt,
3265 set a new line number for the next instruction.
3266 */
3267 if (e->lineno > c->u->u_lineno) {
3268 c->u->u_lineno = e->lineno;
3269 c->u->u_lineno_set = 0;
3270 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003271 /* Updating the column offset is always harmless. */
3272 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 switch (e->kind) {
3274 case BoolOp_kind:
3275 return compiler_boolop(c, e);
3276 case BinOp_kind:
3277 VISIT(c, expr, e->v.BinOp.left);
3278 VISIT(c, expr, e->v.BinOp.right);
3279 ADDOP(c, binop(c, e->v.BinOp.op));
3280 break;
3281 case UnaryOp_kind:
3282 VISIT(c, expr, e->v.UnaryOp.operand);
3283 ADDOP(c, unaryop(e->v.UnaryOp.op));
3284 break;
3285 case Lambda_kind:
3286 return compiler_lambda(c, e);
3287 case IfExp_kind:
3288 return compiler_ifexp(c, e);
3289 case Dict_kind:
3290 n = asdl_seq_LEN(e->v.Dict.values);
3291 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3292 for (i = 0; i < n; i++) {
3293 VISIT(c, expr,
3294 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3295 VISIT(c, expr,
3296 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3297 ADDOP(c, STORE_MAP);
3298 }
3299 break;
3300 case Set_kind:
3301 n = asdl_seq_LEN(e->v.Set.elts);
3302 VISIT_SEQ(c, expr, e->v.Set.elts);
3303 ADDOP_I(c, BUILD_SET, n);
3304 break;
3305 case GeneratorExp_kind:
3306 return compiler_genexp(c, e);
3307 case ListComp_kind:
3308 return compiler_listcomp(c, e);
3309 case SetComp_kind:
3310 return compiler_setcomp(c, e);
3311 case DictComp_kind:
3312 return compiler_dictcomp(c, e);
3313 case Yield_kind:
Benjamin Peterson527c6222012-01-14 08:58:23 -05003314 case YieldFrom_kind: {
3315 expr_ty value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 if (c->u->u_ste->ste_type != FunctionBlock)
3317 return compiler_error(c, "'yield' outside function");
Benjamin Peterson527c6222012-01-14 08:58:23 -05003318 value = (e->kind == YieldFrom_kind) ? e->v.YieldFrom.value : e->v.Yield.value;
3319 if (value) {
3320 VISIT(c, expr, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 }
3322 else {
3323 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3324 }
Benjamin Peterson527c6222012-01-14 08:58:23 -05003325 if (e->kind == YieldFrom_kind) {
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05003326 ADDOP(c, GET_ITER);
3327 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Nick Coghlan1f7ce622012-01-13 21:43:40 +10003328 ADDOP(c, YIELD_FROM);
3329 }
3330 else {
3331 ADDOP(c, YIELD_VALUE);
3332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 break;
Benjamin Peterson527c6222012-01-14 08:58:23 -05003334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 case Compare_kind:
3336 return compiler_compare(c, e);
3337 case Call_kind:
3338 return compiler_call(c, e);
3339 case Num_kind:
3340 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3341 break;
3342 case Str_kind:
3343 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3344 break;
3345 case Bytes_kind:
3346 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3347 break;
3348 case Ellipsis_kind:
3349 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3350 break;
3351 /* The following exprs can be assignment targets. */
3352 case Attribute_kind:
3353 if (e->v.Attribute.ctx != AugStore)
3354 VISIT(c, expr, e->v.Attribute.value);
3355 switch (e->v.Attribute.ctx) {
3356 case AugLoad:
3357 ADDOP(c, DUP_TOP);
3358 /* Fall through to load */
3359 case Load:
3360 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3361 break;
3362 case AugStore:
3363 ADDOP(c, ROT_TWO);
3364 /* Fall through to save */
3365 case Store:
3366 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3367 break;
3368 case Del:
3369 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3370 break;
3371 case Param:
3372 default:
3373 PyErr_SetString(PyExc_SystemError,
3374 "param invalid in attribute expression");
3375 return 0;
3376 }
3377 break;
3378 case Subscript_kind:
3379 switch (e->v.Subscript.ctx) {
3380 case AugLoad:
3381 VISIT(c, expr, e->v.Subscript.value);
3382 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3383 break;
3384 case Load:
3385 VISIT(c, expr, e->v.Subscript.value);
3386 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3387 break;
3388 case AugStore:
3389 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3390 break;
3391 case Store:
3392 VISIT(c, expr, e->v.Subscript.value);
3393 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3394 break;
3395 case Del:
3396 VISIT(c, expr, e->v.Subscript.value);
3397 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3398 break;
3399 case Param:
3400 default:
3401 PyErr_SetString(PyExc_SystemError,
3402 "param invalid in subscript expression");
3403 return 0;
3404 }
3405 break;
3406 case Starred_kind:
3407 switch (e->v.Starred.ctx) {
3408 case Store:
3409 /* In all legitimate cases, the Starred node was already replaced
3410 * by compiler_list/compiler_tuple. XXX: is that okay? */
3411 return compiler_error(c,
3412 "starred assignment target must be in a list or tuple");
3413 default:
3414 return compiler_error(c,
3415 "can use starred expression only as assignment target");
3416 }
3417 break;
3418 case Name_kind:
3419 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3420 /* child nodes of List and Tuple will have expr_context set */
3421 case List_kind:
3422 return compiler_list(c, e);
3423 case Tuple_kind:
3424 return compiler_tuple(c, e);
3425 }
3426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427}
3428
3429static int
3430compiler_augassign(struct compiler *c, stmt_ty s)
3431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 expr_ty e = s->v.AugAssign.target;
3433 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 switch (e->kind) {
3438 case Attribute_kind:
3439 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3440 AugLoad, e->lineno, e->col_offset, c->c_arena);
3441 if (auge == NULL)
3442 return 0;
3443 VISIT(c, expr, auge);
3444 VISIT(c, expr, s->v.AugAssign.value);
3445 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3446 auge->v.Attribute.ctx = AugStore;
3447 VISIT(c, expr, auge);
3448 break;
3449 case Subscript_kind:
3450 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3451 AugLoad, e->lineno, e->col_offset, c->c_arena);
3452 if (auge == NULL)
3453 return 0;
3454 VISIT(c, expr, auge);
3455 VISIT(c, expr, s->v.AugAssign.value);
3456 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3457 auge->v.Subscript.ctx = AugStore;
3458 VISIT(c, expr, auge);
3459 break;
3460 case Name_kind:
3461 if (!compiler_nameop(c, e->v.Name.id, Load))
3462 return 0;
3463 VISIT(c, expr, s->v.AugAssign.value);
3464 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3465 return compiler_nameop(c, e->v.Name.id, Store);
3466 default:
3467 PyErr_Format(PyExc_SystemError,
3468 "invalid node type (%d) for augmented assignment",
3469 e->kind);
3470 return 0;
3471 }
3472 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473}
3474
3475static int
3476compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 struct fblockinfo *f;
3479 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3480 PyErr_SetString(PyExc_SystemError,
3481 "too many statically nested blocks");
3482 return 0;
3483 }
3484 f = &c->u->u_fblock[c->u->u_nfblocks++];
3485 f->fb_type = t;
3486 f->fb_block = b;
3487 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488}
3489
3490static void
3491compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 struct compiler_unit *u = c->u;
3494 assert(u->u_nfblocks > 0);
3495 u->u_nfblocks--;
3496 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3497 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498}
3499
Thomas Wouters89f507f2006-12-13 04:49:30 +00003500static int
3501compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 int i;
3503 struct compiler_unit *u = c->u;
3504 for (i = 0; i < u->u_nfblocks; ++i) {
3505 if (u->u_fblock[i].fb_type == LOOP)
3506 return 1;
3507 }
3508 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003509}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510/* Raises a SyntaxError and returns 0.
3511 If something goes wrong, a different exception may be raised.
3512*/
3513
3514static int
3515compiler_error(struct compiler *c, const char *errstr)
3516{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003517 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3521 if (!loc) {
3522 Py_INCREF(Py_None);
3523 loc = Py_None;
3524 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003525 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003526 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 if (!u)
3528 goto exit;
3529 v = Py_BuildValue("(zO)", errstr, u);
3530 if (!v)
3531 goto exit;
3532 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 Py_DECREF(loc);
3535 Py_XDECREF(u);
3536 Py_XDECREF(v);
3537 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538}
3539
3540static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541compiler_handle_subscr(struct compiler *c, const char *kind,
3542 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 /* XXX this code is duplicated */
3547 switch (ctx) {
3548 case AugLoad: /* fall through to Load */
3549 case Load: op = BINARY_SUBSCR; break;
3550 case AugStore:/* fall through to Store */
3551 case Store: op = STORE_SUBSCR; break;
3552 case Del: op = DELETE_SUBSCR; break;
3553 case Param:
3554 PyErr_Format(PyExc_SystemError,
3555 "invalid %s kind %d in subscript\n",
3556 kind, ctx);
3557 return 0;
3558 }
3559 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003560 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 }
3562 else if (ctx == AugStore) {
3563 ADDOP(c, ROT_THREE);
3564 }
3565 ADDOP(c, op);
3566 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567}
3568
3569static int
3570compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 int n = 2;
3573 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 /* only handles the cases where BUILD_SLICE is emitted */
3576 if (s->v.Slice.lower) {
3577 VISIT(c, expr, s->v.Slice.lower);
3578 }
3579 else {
3580 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3581 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 if (s->v.Slice.upper) {
3584 VISIT(c, expr, s->v.Slice.upper);
3585 }
3586 else {
3587 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3588 }
3589
3590 if (s->v.Slice.step) {
3591 n++;
3592 VISIT(c, expr, s->v.Slice.step);
3593 }
3594 ADDOP_I(c, BUILD_SLICE, n);
3595 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596}
3597
3598static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3600 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 switch (s->kind) {
3603 case Slice_kind:
3604 return compiler_slice(c, s, ctx);
3605 case Index_kind:
3606 VISIT(c, expr, s->v.Index.value);
3607 break;
3608 case ExtSlice_kind:
3609 default:
3610 PyErr_SetString(PyExc_SystemError,
3611 "extended slice invalid in nested slice");
3612 return 0;
3613 }
3614 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615}
3616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617static int
3618compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 char * kindname = NULL;
3621 switch (s->kind) {
3622 case Index_kind:
3623 kindname = "index";
3624 if (ctx != AugStore) {
3625 VISIT(c, expr, s->v.Index.value);
3626 }
3627 break;
3628 case Slice_kind:
3629 kindname = "slice";
3630 if (ctx != AugStore) {
3631 if (!compiler_slice(c, s, ctx))
3632 return 0;
3633 }
3634 break;
3635 case ExtSlice_kind:
3636 kindname = "extended slice";
3637 if (ctx != AugStore) {
3638 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3639 for (i = 0; i < n; i++) {
3640 slice_ty sub = (slice_ty)asdl_seq_GET(
3641 s->v.ExtSlice.dims, i);
3642 if (!compiler_visit_nested_slice(c, sub, ctx))
3643 return 0;
3644 }
3645 ADDOP_I(c, BUILD_TUPLE, n);
3646 }
3647 break;
3648 default:
3649 PyErr_Format(PyExc_SystemError,
3650 "invalid subscript kind %d", s->kind);
3651 return 0;
3652 }
3653 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654}
3655
Thomas Wouters89f507f2006-12-13 04:49:30 +00003656/* End of the compiler section, beginning of the assembler section */
3657
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658/* do depth-first search of basic block graph, starting with block.
3659 post records the block indices in post-order.
3660
3661 XXX must handle implicit jumps from one block to next
3662*/
3663
Thomas Wouters89f507f2006-12-13 04:49:30 +00003664struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 PyObject *a_bytecode; /* string containing bytecode */
3666 int a_offset; /* offset into bytecode */
3667 int a_nblocks; /* number of reachable blocks */
3668 basicblock **a_postorder; /* list of blocks in dfs postorder */
3669 PyObject *a_lnotab; /* string containing lnotab */
3670 int a_lnotab_off; /* offset into lnotab */
3671 int a_lineno; /* last lineno of emitted instruction */
3672 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003673};
3674
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675static void
3676dfs(struct compiler *c, basicblock *b, struct assembler *a)
3677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 int i;
3679 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 if (b->b_seen)
3682 return;
3683 b->b_seen = 1;
3684 if (b->b_next != NULL)
3685 dfs(c, b->b_next, a);
3686 for (i = 0; i < b->b_iused; i++) {
3687 instr = &b->b_instr[i];
3688 if (instr->i_jrel || instr->i_jabs)
3689 dfs(c, instr->i_target, a);
3690 }
3691 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003692}
3693
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003694static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 int i, target_depth;
3698 struct instr *instr;
3699 if (b->b_seen || b->b_startdepth >= depth)
3700 return maxdepth;
3701 b->b_seen = 1;
3702 b->b_startdepth = depth;
3703 for (i = 0; i < b->b_iused; i++) {
3704 instr = &b->b_instr[i];
3705 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3706 if (depth > maxdepth)
3707 maxdepth = depth;
3708 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3709 if (instr->i_jrel || instr->i_jabs) {
3710 target_depth = depth;
3711 if (instr->i_opcode == FOR_ITER) {
3712 target_depth = depth-2;
3713 } else if (instr->i_opcode == SETUP_FINALLY ||
3714 instr->i_opcode == SETUP_EXCEPT) {
3715 target_depth = depth+3;
3716 if (target_depth > maxdepth)
3717 maxdepth = target_depth;
3718 }
3719 maxdepth = stackdepth_walk(c, instr->i_target,
3720 target_depth, maxdepth);
3721 if (instr->i_opcode == JUMP_ABSOLUTE ||
3722 instr->i_opcode == JUMP_FORWARD) {
3723 goto out; /* remaining code is dead */
3724 }
3725 }
3726 }
3727 if (b->b_next)
3728 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 b->b_seen = 0;
3731 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003732}
3733
3734/* Find the flow path that needs the largest stack. We assume that
3735 * cycles in the flow graph have no net effect on the stack depth.
3736 */
3737static int
3738stackdepth(struct compiler *c)
3739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 basicblock *b, *entryblock;
3741 entryblock = NULL;
3742 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3743 b->b_seen = 0;
3744 b->b_startdepth = INT_MIN;
3745 entryblock = b;
3746 }
3747 if (!entryblock)
3748 return 0;
3749 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750}
3751
3752static int
3753assemble_init(struct assembler *a, int nblocks, int firstlineno)
3754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 memset(a, 0, sizeof(struct assembler));
3756 a->a_lineno = firstlineno;
3757 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3758 if (!a->a_bytecode)
3759 return 0;
3760 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3761 if (!a->a_lnotab)
3762 return 0;
3763 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3764 PyErr_NoMemory();
3765 return 0;
3766 }
3767 a->a_postorder = (basicblock **)PyObject_Malloc(
3768 sizeof(basicblock *) * nblocks);
3769 if (!a->a_postorder) {
3770 PyErr_NoMemory();
3771 return 0;
3772 }
3773 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774}
3775
3776static void
3777assemble_free(struct assembler *a)
3778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 Py_XDECREF(a->a_bytecode);
3780 Py_XDECREF(a->a_lnotab);
3781 if (a->a_postorder)
3782 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783}
3784
3785/* Return the size of a basic block in bytes. */
3786
3787static int
3788instrsize(struct instr *instr)
3789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 if (!instr->i_hasarg)
3791 return 1; /* 1 byte for the opcode*/
3792 if (instr->i_oparg > 0xffff)
3793 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3794 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795}
3796
3797static int
3798blocksize(basicblock *b)
3799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 int i;
3801 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 for (i = 0; i < b->b_iused; i++)
3804 size += instrsize(&b->b_instr[i]);
3805 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806}
3807
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003808/* Appends a pair to the end of the line number table, a_lnotab, representing
3809 the instruction's bytecode offset and line number. See
3810 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003811
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003812static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 int d_bytecode, d_lineno;
3816 int len;
3817 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 d_bytecode = a->a_offset - a->a_lineno_off;
3820 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 assert(d_bytecode >= 0);
3823 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if(d_bytecode == 0 && d_lineno == 0)
3826 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 if (d_bytecode > 255) {
3829 int j, nbytes, ncodes = d_bytecode / 255;
3830 nbytes = a->a_lnotab_off + 2 * ncodes;
3831 len = PyBytes_GET_SIZE(a->a_lnotab);
3832 if (nbytes >= len) {
3833 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3834 len = nbytes;
3835 else if (len <= INT_MAX / 2)
3836 len *= 2;
3837 else {
3838 PyErr_NoMemory();
3839 return 0;
3840 }
3841 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3842 return 0;
3843 }
3844 lnotab = (unsigned char *)
3845 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3846 for (j = 0; j < ncodes; j++) {
3847 *lnotab++ = 255;
3848 *lnotab++ = 0;
3849 }
3850 d_bytecode -= ncodes * 255;
3851 a->a_lnotab_off += ncodes * 2;
3852 }
3853 assert(d_bytecode <= 255);
3854 if (d_lineno > 255) {
3855 int j, nbytes, ncodes = d_lineno / 255;
3856 nbytes = a->a_lnotab_off + 2 * ncodes;
3857 len = PyBytes_GET_SIZE(a->a_lnotab);
3858 if (nbytes >= len) {
3859 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3860 len = nbytes;
3861 else if (len <= INT_MAX / 2)
3862 len *= 2;
3863 else {
3864 PyErr_NoMemory();
3865 return 0;
3866 }
3867 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3868 return 0;
3869 }
3870 lnotab = (unsigned char *)
3871 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3872 *lnotab++ = d_bytecode;
3873 *lnotab++ = 255;
3874 d_bytecode = 0;
3875 for (j = 1; j < ncodes; j++) {
3876 *lnotab++ = 0;
3877 *lnotab++ = 255;
3878 }
3879 d_lineno -= ncodes * 255;
3880 a->a_lnotab_off += ncodes * 2;
3881 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 len = PyBytes_GET_SIZE(a->a_lnotab);
3884 if (a->a_lnotab_off + 2 >= len) {
3885 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3886 return 0;
3887 }
3888 lnotab = (unsigned char *)
3889 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 a->a_lnotab_off += 2;
3892 if (d_bytecode) {
3893 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003894 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 }
3896 else { /* First line of a block; def stmt, etc. */
3897 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003898 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 }
3900 a->a_lineno = i->i_lineno;
3901 a->a_lineno_off = a->a_offset;
3902 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003903}
3904
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905/* assemble_emit()
3906 Extend the bytecode with a new instruction.
3907 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003908*/
3909
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003910static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 int size, arg = 0, ext = 0;
3914 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3915 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 size = instrsize(i);
3918 if (i->i_hasarg) {
3919 arg = i->i_oparg;
3920 ext = arg >> 16;
3921 }
3922 if (i->i_lineno && !assemble_lnotab(a, i))
3923 return 0;
3924 if (a->a_offset + size >= len) {
3925 if (len > PY_SSIZE_T_MAX / 2)
3926 return 0;
3927 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3928 return 0;
3929 }
3930 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3931 a->a_offset += size;
3932 if (size == 6) {
3933 assert(i->i_hasarg);
3934 *code++ = (char)EXTENDED_ARG;
3935 *code++ = ext & 0xff;
3936 *code++ = ext >> 8;
3937 arg &= 0xffff;
3938 }
3939 *code++ = i->i_opcode;
3940 if (i->i_hasarg) {
3941 assert(size == 3 || size == 6);
3942 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003943 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 }
3945 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003946}
3947
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003948static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 basicblock *b;
3952 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3953 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 /* Compute the size of each block and fixup jump args.
3956 Replace block pointer with position in bytecode. */
3957 do {
3958 totsize = 0;
3959 for (i = a->a_nblocks - 1; i >= 0; i--) {
3960 b = a->a_postorder[i];
3961 bsize = blocksize(b);
3962 b->b_offset = totsize;
3963 totsize += bsize;
3964 }
3965 last_extended_arg_count = extended_arg_count;
3966 extended_arg_count = 0;
3967 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3968 bsize = b->b_offset;
3969 for (i = 0; i < b->b_iused; i++) {
3970 struct instr *instr = &b->b_instr[i];
3971 /* Relative jumps are computed relative to
3972 the instruction pointer after fetching
3973 the jump instruction.
3974 */
3975 bsize += instrsize(instr);
3976 if (instr->i_jabs)
3977 instr->i_oparg = instr->i_target->b_offset;
3978 else if (instr->i_jrel) {
3979 int delta = instr->i_target->b_offset - bsize;
3980 instr->i_oparg = delta;
3981 }
3982 else
3983 continue;
3984 if (instr->i_oparg > 0xffff)
3985 extended_arg_count++;
3986 }
3987 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 /* XXX: This is an awful hack that could hurt performance, but
3990 on the bright side it should work until we come up
3991 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 The issue is that in the first loop blocksize() is called
3994 which calls instrsize() which requires i_oparg be set
3995 appropriately. There is a bootstrap problem because
3996 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 So we loop until we stop seeing new EXTENDED_ARGs.
3999 The only EXTENDED_ARGs that could be popping up are
4000 ones in jump instructions. So this should converge
4001 fairly quickly.
4002 */
4003 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004004}
4005
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004006static PyObject *
4007dict_keys_inorder(PyObject *dict, int offset)
4008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 PyObject *tuple, *k, *v;
4010 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 tuple = PyTuple_New(size);
4013 if (tuple == NULL)
4014 return NULL;
4015 while (PyDict_Next(dict, &pos, &k, &v)) {
4016 i = PyLong_AS_LONG(v);
4017 /* The keys of the dictionary are tuples. (see compiler_add_o)
4018 The object we want is always first, though. */
4019 k = PyTuple_GET_ITEM(k, 0);
4020 Py_INCREF(k);
4021 assert((i - offset) < size);
4022 assert((i - offset) >= 0);
4023 PyTuple_SET_ITEM(tuple, i - offset, k);
4024 }
4025 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004026}
4027
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004028static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004029compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 PySTEntryObject *ste = c->u->u_ste;
4032 int flags = 0, n;
4033 if (ste->ste_type != ModuleBlock)
4034 flags |= CO_NEWLOCALS;
4035 if (ste->ste_type == FunctionBlock) {
4036 if (!ste->ste_unoptimized)
4037 flags |= CO_OPTIMIZED;
4038 if (ste->ste_nested)
4039 flags |= CO_NESTED;
4040 if (ste->ste_generator)
4041 flags |= CO_GENERATOR;
4042 if (ste->ste_varargs)
4043 flags |= CO_VARARGS;
4044 if (ste->ste_varkeywords)
4045 flags |= CO_VARKEYWORDS;
4046 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 /* (Only) inherit compilerflags in PyCF_MASK */
4049 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 n = PyDict_Size(c->u->u_freevars);
4052 if (n < 0)
4053 return -1;
4054 if (n == 0) {
4055 n = PyDict_Size(c->u->u_cellvars);
4056 if (n < 0)
4057 return -1;
4058 if (n == 0) {
4059 flags |= CO_NOFREE;
4060 }
4061 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004064}
4065
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066static PyCodeObject *
4067makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 PyObject *tmp;
4070 PyCodeObject *co = NULL;
4071 PyObject *consts = NULL;
4072 PyObject *names = NULL;
4073 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 PyObject *name = NULL;
4075 PyObject *freevars = NULL;
4076 PyObject *cellvars = NULL;
4077 PyObject *bytecode = NULL;
4078 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 tmp = dict_keys_inorder(c->u->u_consts, 0);
4081 if (!tmp)
4082 goto error;
4083 consts = PySequence_List(tmp); /* optimize_code requires a list */
4084 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 names = dict_keys_inorder(c->u->u_names, 0);
4087 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4088 if (!consts || !names || !varnames)
4089 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4092 if (!cellvars)
4093 goto error;
4094 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4095 if (!freevars)
4096 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 nlocals = PyDict_Size(c->u->u_varnames);
4098 flags = compute_code_flags(c);
4099 if (flags < 0)
4100 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4103 if (!bytecode)
4104 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4107 if (!tmp)
4108 goto error;
4109 Py_DECREF(consts);
4110 consts = tmp;
4111
4112 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4113 nlocals, stackdepth(c), flags,
4114 bytecode, consts, names, varnames,
4115 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004116 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 c->u->u_firstlineno,
4118 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 Py_XDECREF(consts);
4121 Py_XDECREF(names);
4122 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 Py_XDECREF(name);
4124 Py_XDECREF(freevars);
4125 Py_XDECREF(cellvars);
4126 Py_XDECREF(bytecode);
4127 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004128}
4129
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004130
4131/* For debugging purposes only */
4132#if 0
4133static void
4134dump_instr(const struct instr *i)
4135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 const char *jrel = i->i_jrel ? "jrel " : "";
4137 const char *jabs = i->i_jabs ? "jabs " : "";
4138 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 *arg = '\0';
4141 if (i->i_hasarg)
4142 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4145 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004146}
4147
4148static void
4149dump_basicblock(const basicblock *b)
4150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 const char *seen = b->b_seen ? "seen " : "";
4152 const char *b_return = b->b_return ? "return " : "";
4153 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4154 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4155 if (b->b_instr) {
4156 int i;
4157 for (i = 0; i < b->b_iused; i++) {
4158 fprintf(stderr, " [%02d] ", i);
4159 dump_instr(b->b_instr + i);
4160 }
4161 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004162}
4163#endif
4164
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165static PyCodeObject *
4166assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 basicblock *b, *entryblock;
4169 struct assembler a;
4170 int i, j, nblocks;
4171 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 /* Make sure every block that falls off the end returns None.
4174 XXX NEXT_BLOCK() isn't quite right, because if the last
4175 block ends with a jump or return b_next shouldn't set.
4176 */
4177 if (!c->u->u_curblock->b_return) {
4178 NEXT_BLOCK(c);
4179 if (addNone)
4180 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4181 ADDOP(c, RETURN_VALUE);
4182 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 nblocks = 0;
4185 entryblock = NULL;
4186 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4187 nblocks++;
4188 entryblock = b;
4189 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 /* Set firstlineno if it wasn't explicitly set. */
4192 if (!c->u->u_firstlineno) {
4193 if (entryblock && entryblock->b_instr)
4194 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4195 else
4196 c->u->u_firstlineno = 1;
4197 }
4198 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4199 goto error;
4200 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 /* Can't modify the bytecode after computing jump offsets. */
4203 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 /* Emit code in reverse postorder from dfs. */
4206 for (i = a.a_nblocks - 1; i >= 0; i--) {
4207 b = a.a_postorder[i];
4208 for (j = 0; j < b->b_iused; j++)
4209 if (!assemble_emit(&a, &b->b_instr[j]))
4210 goto error;
4211 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4214 goto error;
4215 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4216 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004219 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 assemble_free(&a);
4221 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004222}
Georg Brandl8334fd92010-12-04 10:26:46 +00004223
4224#undef PyAST_Compile
4225PyAPI_FUNC(PyCodeObject *)
4226PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4227 PyArena *arena)
4228{
4229 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4230}
4231
4232