blob: 849f48785dcee50294e941bfbccac6d71a90633c [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;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 case POP_BLOCK:
846 return 0;
847 case POP_EXCEPT:
848 return 0; /* -3 except if bad bytecode */
849 case END_FINALLY:
850 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 case STORE_NAME:
853 return -1;
854 case DELETE_NAME:
855 return 0;
856 case UNPACK_SEQUENCE:
857 return oparg-1;
858 case UNPACK_EX:
859 return (oparg&0xFF) + (oparg>>8);
860 case FOR_ITER:
861 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 case STORE_ATTR:
864 return -2;
865 case DELETE_ATTR:
866 return -1;
867 case STORE_GLOBAL:
868 return -1;
869 case DELETE_GLOBAL:
870 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 case LOAD_CONST:
872 return 1;
873 case LOAD_NAME:
874 return 1;
875 case BUILD_TUPLE:
876 case BUILD_LIST:
877 case BUILD_SET:
878 return 1-oparg;
879 case BUILD_MAP:
880 return 1;
881 case LOAD_ATTR:
882 return 0;
883 case COMPARE_OP:
884 return -1;
885 case IMPORT_NAME:
886 return -1;
887 case IMPORT_FROM:
888 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 case JUMP_FORWARD:
891 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
892 case JUMP_IF_FALSE_OR_POP: /* "" */
893 case JUMP_ABSOLUTE:
894 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case POP_JUMP_IF_FALSE:
897 case POP_JUMP_IF_TRUE:
898 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case LOAD_GLOBAL:
901 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case CONTINUE_LOOP:
904 return 0;
905 case SETUP_LOOP:
906 return 0;
907 case SETUP_EXCEPT:
908 case SETUP_FINALLY:
909 return 6; /* can push 3 values for the new exception
910 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 case LOAD_FAST:
913 return 1;
914 case STORE_FAST:
915 return -1;
916 case DELETE_FAST:
917 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 case RAISE_VARARGS:
920 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000921#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case CALL_FUNCTION:
923 return -NARGS(oparg);
924 case CALL_FUNCTION_VAR:
925 case CALL_FUNCTION_KW:
926 return -NARGS(oparg)-1;
927 case CALL_FUNCTION_VAR_KW:
928 return -NARGS(oparg)-2;
929 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100930 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100932 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000933#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case BUILD_SLICE:
935 if (oparg == 3)
936 return -2;
937 else
938 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case LOAD_CLOSURE:
941 return 1;
942 case LOAD_DEREF:
943 return 1;
944 case STORE_DEREF:
945 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000946 case DELETE_DEREF:
947 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 default:
949 fprintf(stderr, "opcode = %d\n", opcode);
950 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
953 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954}
955
956/* Add an opcode with no argument.
957 Returns 0 on failure, 1 on success.
958*/
959
960static int
961compiler_addop(struct compiler *c, int opcode)
962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 basicblock *b;
964 struct instr *i;
965 int off;
966 off = compiler_next_instr(c, c->u->u_curblock);
967 if (off < 0)
968 return 0;
969 b = c->u->u_curblock;
970 i = &b->b_instr[off];
971 i->i_opcode = opcode;
972 i->i_hasarg = 0;
973 if (opcode == RETURN_VALUE)
974 b->b_return = 1;
975 compiler_set_lineno(c, off);
976 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977}
978
979static int
980compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *t, *v;
983 Py_ssize_t arg;
984 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* necessary to make sure types aren't coerced (e.g., int and long) */
987 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
988 if (PyFloat_Check(o)) {
989 d = PyFloat_AS_DOUBLE(o);
990 /* all we need is to make the tuple different in either the 0.0
991 * or -0.0 case from all others, just to avoid the "coercion".
992 */
993 if (d == 0.0 && copysign(1.0, d) < 0.0)
994 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
995 else
996 t = PyTuple_Pack(2, o, o->ob_type);
997 }
998 else if (PyComplex_Check(o)) {
999 Py_complex z;
1000 int real_negzero, imag_negzero;
1001 /* For the complex case we must make complex(x, 0.)
1002 different from complex(x, -0.) and complex(0., y)
1003 different from complex(-0., y), for any x and y.
1004 All four complex zeros must be distinguished.*/
1005 z = PyComplex_AsCComplex(o);
1006 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1007 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1008 if (real_negzero && imag_negzero) {
1009 t = PyTuple_Pack(5, o, o->ob_type,
1010 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001011 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 else if (imag_negzero) {
1013 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001014 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 else if (real_negzero) {
1016 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1017 }
1018 else {
1019 t = PyTuple_Pack(2, o, o->ob_type);
1020 }
1021 }
1022 else {
1023 t = PyTuple_Pack(2, o, o->ob_type);
1024 }
1025 if (t == NULL)
1026 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 v = PyDict_GetItem(dict, t);
1029 if (!v) {
1030 if (PyErr_Occurred())
1031 return -1;
1032 arg = PyDict_Size(dict);
1033 v = PyLong_FromLong(arg);
1034 if (!v) {
1035 Py_DECREF(t);
1036 return -1;
1037 }
1038 if (PyDict_SetItem(dict, t, v) < 0) {
1039 Py_DECREF(t);
1040 Py_DECREF(v);
1041 return -1;
1042 }
1043 Py_DECREF(v);
1044 }
1045 else
1046 arg = PyLong_AsLong(v);
1047 Py_DECREF(t);
1048 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049}
1050
1051static int
1052compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054{
1055 int arg = compiler_add_o(c, dict, o);
1056 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001057 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058 return compiler_addop_i(c, opcode, arg);
1059}
1060
1061static int
1062compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064{
1065 int arg;
1066 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1067 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001068 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069 arg = compiler_add_o(c, dict, mangled);
1070 Py_DECREF(mangled);
1071 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001072 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073 return compiler_addop_i(c, opcode, arg);
1074}
1075
1076/* Add an opcode with an integer argument.
1077 Returns 0 on failure, 1 on success.
1078*/
1079
1080static int
1081compiler_addop_i(struct compiler *c, int opcode, int oparg)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 struct instr *i;
1084 int off;
1085 off = compiler_next_instr(c, c->u->u_curblock);
1086 if (off < 0)
1087 return 0;
1088 i = &c->u->u_curblock->b_instr[off];
1089 i->i_opcode = opcode;
1090 i->i_oparg = oparg;
1091 i->i_hasarg = 1;
1092 compiler_set_lineno(c, off);
1093 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001094}
1095
1096static int
1097compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 struct instr *i;
1100 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 assert(b != NULL);
1103 off = compiler_next_instr(c, c->u->u_curblock);
1104 if (off < 0)
1105 return 0;
1106 i = &c->u->u_curblock->b_instr[off];
1107 i->i_opcode = opcode;
1108 i->i_target = b;
1109 i->i_hasarg = 1;
1110 if (absolute)
1111 i->i_jabs = 1;
1112 else
1113 i->i_jrel = 1;
1114 compiler_set_lineno(c, off);
1115 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116}
1117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1119 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 it as the current block. NEXT_BLOCK() also creates an implicit jump
1121 from the current block to the new block.
1122*/
1123
Thomas Wouters89f507f2006-12-13 04:49:30 +00001124/* The returns inside these macros make it impossible to decref objects
1125 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001126*/
1127
1128
1129#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (compiler_use_new_block((C)) == NULL) \
1131 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132}
1133
1134#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (compiler_next_block((C)) == NULL) \
1136 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137}
1138
1139#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 if (!compiler_addop((C), (OP))) \
1141 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142}
1143
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001144#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (!compiler_addop((C), (OP))) { \
1146 compiler_exit_scope(c); \
1147 return 0; \
1148 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001149}
1150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1153 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154}
1155
1156#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1158 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159}
1160
1161#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (!compiler_addop_i((C), (OP), (O))) \
1163 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
1166#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (!compiler_addop_j((C), (OP), (O), 1)) \
1168 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169}
1170
1171#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (!compiler_addop_j((C), (OP), (O), 0)) \
1173 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174}
1175
1176/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1177 the ASDL name to synthesize the name of the C type and the visit function.
1178*/
1179
1180#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (!compiler_visit_ ## TYPE((C), (V))) \
1182 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183}
1184
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001185#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!compiler_visit_ ## TYPE((C), (V))) { \
1187 compiler_exit_scope(c); \
1188 return 0; \
1189 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001190}
1191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (!compiler_visit_slice((C), (V), (CTX))) \
1194 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195}
1196
1197#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 int _i; \
1199 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1200 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1201 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1202 if (!compiler_visit_ ## TYPE((C), elt)) \
1203 return 0; \
1204 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205}
1206
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001207#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 int _i; \
1209 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1210 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1211 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1212 if (!compiler_visit_ ## TYPE((C), elt)) { \
1213 compiler_exit_scope(c); \
1214 return 0; \
1215 } \
1216 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001217}
1218
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219static int
1220compiler_isdocstring(stmt_ty s)
1221{
1222 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001223 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224 return s->v.Expr.value->kind == Str_kind;
1225}
1226
1227/* Compile a sequence of statements, checking for a docstring. */
1228
1229static int
1230compiler_body(struct compiler *c, asdl_seq *stmts)
1231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 int i = 0;
1233 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (!asdl_seq_LEN(stmts))
1236 return 1;
1237 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001238 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 /* don't generate docstrings if -OO */
1240 i = 1;
1241 VISIT(c, expr, st->v.Expr.value);
1242 if (!compiler_nameop(c, __doc__, Store))
1243 return 0;
1244 }
1245 for (; i < asdl_seq_LEN(stmts); i++)
1246 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1247 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001248}
1249
1250static PyCodeObject *
1251compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyCodeObject *co;
1254 int addNone = 1;
1255 static PyObject *module;
1256 if (!module) {
1257 module = PyUnicode_InternFromString("<module>");
1258 if (!module)
1259 return NULL;
1260 }
1261 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001262 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 return NULL;
1264 switch (mod->kind) {
1265 case Module_kind:
1266 if (!compiler_body(c, mod->v.Module.body)) {
1267 compiler_exit_scope(c);
1268 return 0;
1269 }
1270 break;
1271 case Interactive_kind:
1272 c->c_interactive = 1;
1273 VISIT_SEQ_IN_SCOPE(c, stmt,
1274 mod->v.Interactive.body);
1275 break;
1276 case Expression_kind:
1277 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1278 addNone = 0;
1279 break;
1280 case Suite_kind:
1281 PyErr_SetString(PyExc_SystemError,
1282 "suite should not be possible");
1283 return 0;
1284 default:
1285 PyErr_Format(PyExc_SystemError,
1286 "module kind %d should not be possible",
1287 mod->kind);
1288 return 0;
1289 }
1290 co = assemble(c, addNone);
1291 compiler_exit_scope(c);
1292 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001293}
1294
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295/* The test for LOCAL must come before the test for FREE in order to
1296 handle classes where name is both local and free. The local var is
1297 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001298*/
1299
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300static int
1301get_ref_type(struct compiler *c, PyObject *name)
1302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 int scope = PyST_GetScope(c->u->u_ste, name);
1304 if (scope == 0) {
1305 char buf[350];
1306 PyOS_snprintf(buf, sizeof(buf),
1307 "unknown scope for %.100s in %.100s(%s) in %s\n"
1308 "symbols: %s\nlocals: %s\nglobals: %s",
1309 PyBytes_AS_STRING(name),
1310 PyBytes_AS_STRING(c->u->u_name),
1311 PyObject_REPR(c->u->u_ste->ste_id),
1312 c->c_filename,
1313 PyObject_REPR(c->u->u_ste->ste_symbols),
1314 PyObject_REPR(c->u->u_varnames),
1315 PyObject_REPR(c->u->u_names)
1316 );
1317 Py_FatalError(buf);
1318 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321}
1322
1323static int
1324compiler_lookup_arg(PyObject *dict, PyObject *name)
1325{
1326 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001329 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001331 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001333 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001334 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335}
1336
1337static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001338compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001341 if (qualname == NULL)
1342 qualname = co->co_name;
1343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (free == 0) {
1345 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001346 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 ADDOP_I(c, MAKE_FUNCTION, args);
1348 return 1;
1349 }
1350 for (i = 0; i < free; ++i) {
1351 /* Bypass com_addop_varname because it will generate
1352 LOAD_DEREF but LOAD_CLOSURE is needed.
1353 */
1354 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1355 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* Special case: If a class contains a method with a
1358 free variable that has the same name as a method,
1359 the name will be considered free *and* local in the
1360 class. It should be handled by the closure, as
1361 well as by the normal name loookup logic.
1362 */
1363 reftype = get_ref_type(c, name);
1364 if (reftype == CELL)
1365 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1366 else /* (reftype == FREE) */
1367 arg = compiler_lookup_arg(c->u->u_freevars, name);
1368 if (arg == -1) {
1369 fprintf(stderr,
1370 "lookup %s in %s %d %d\n"
1371 "freevars of %s: %s\n",
1372 PyObject_REPR(name),
1373 PyBytes_AS_STRING(c->u->u_name),
1374 reftype, arg,
1375 _PyUnicode_AsString(co->co_name),
1376 PyObject_REPR(co->co_freevars));
1377 Py_FatalError("compiler_make_closure()");
1378 }
1379 ADDOP_I(c, LOAD_CLOSURE, arg);
1380 }
1381 ADDOP_I(c, BUILD_TUPLE, free);
1382 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001383 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 ADDOP_I(c, MAKE_CLOSURE, args);
1385 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386}
1387
1388static int
1389compiler_decorators(struct compiler *c, asdl_seq* decos)
1390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (!decos)
1394 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1397 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1398 }
1399 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400}
1401
1402static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001403compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 int i, default_count = 0;
1407 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1408 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1409 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1410 if (default_) {
1411 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
1412 if (!compiler_visit_expr(c, default_)) {
1413 return -1;
1414 }
1415 default_count++;
1416 }
1417 }
1418 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001419}
1420
1421static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001422compiler_visit_argannotation(struct compiler *c, identifier id,
1423 expr_ty annotation, PyObject *names)
1424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 if (annotation) {
1426 VISIT(c, expr, annotation);
1427 if (PyList_Append(names, id))
1428 return -1;
1429 }
1430 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001431}
1432
1433static int
1434compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1435 PyObject *names)
1436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 int i, error;
1438 for (i = 0; i < asdl_seq_LEN(args); i++) {
1439 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1440 error = compiler_visit_argannotation(
1441 c,
1442 arg->arg,
1443 arg->annotation,
1444 names);
1445 if (error)
1446 return error;
1447 }
1448 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001449}
1450
1451static int
1452compiler_visit_annotations(struct compiler *c, arguments_ty args,
1453 expr_ty returns)
1454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 /* Push arg annotations and a list of the argument names. Return the #
1456 of items pushed. The expressions are evaluated out-of-order wrt the
1457 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1460 */
1461 static identifier return_str;
1462 PyObject *names;
1463 int len;
1464 names = PyList_New(0);
1465 if (!names)
1466 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (compiler_visit_argannotations(c, args->args, names))
1469 goto error;
1470 if (args->varargannotation &&
1471 compiler_visit_argannotation(c, args->vararg,
1472 args->varargannotation, names))
1473 goto error;
1474 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1475 goto error;
1476 if (args->kwargannotation &&
1477 compiler_visit_argannotation(c, args->kwarg,
1478 args->kwargannotation, names))
1479 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!return_str) {
1482 return_str = PyUnicode_InternFromString("return");
1483 if (!return_str)
1484 goto error;
1485 }
1486 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1487 goto error;
1488 }
1489
1490 len = PyList_GET_SIZE(names);
1491 if (len > 65534) {
1492 /* len must fit in 16 bits, and len is incremented below */
1493 PyErr_SetString(PyExc_SyntaxError,
1494 "too many annotations");
1495 goto error;
1496 }
1497 if (len) {
1498 /* convert names to a tuple and place on stack */
1499 PyObject *elt;
1500 int i;
1501 PyObject *s = PyTuple_New(len);
1502 if (!s)
1503 goto error;
1504 for (i = 0; i < len; i++) {
1505 elt = PyList_GET_ITEM(names, i);
1506 Py_INCREF(elt);
1507 PyTuple_SET_ITEM(s, i, elt);
1508 }
1509 ADDOP_O(c, LOAD_CONST, s, consts);
1510 Py_DECREF(s);
1511 len++; /* include the just-pushed tuple */
1512 }
1513 Py_DECREF(names);
1514 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001515
1516error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 Py_DECREF(names);
1518 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001519}
1520
1521static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522compiler_function(struct compiler *c, stmt_ty s)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001525 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 arguments_ty args = s->v.FunctionDef.args;
1527 expr_ty returns = s->v.FunctionDef.returns;
1528 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1529 stmt_ty st;
1530 int i, n, docstring, kw_default_count = 0, arglength;
1531 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (!compiler_decorators(c, decos))
1536 return 0;
1537 if (args->kwonlyargs) {
1538 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1539 args->kw_defaults);
1540 if (res < 0)
1541 return 0;
1542 kw_default_count = res;
1543 }
1544 if (args->defaults)
1545 VISIT_SEQ(c, expr, args->defaults);
1546 num_annotations = compiler_visit_annotations(c, args, returns);
1547 if (num_annotations < 0)
1548 return 0;
1549 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001550
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001551 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1552 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 s->lineno))
1554 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1557 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001558 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 first_const = st->v.Expr.value->v.Str.s;
1560 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1561 compiler_exit_scope(c);
1562 return 0;
1563 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 c->u->u_argcount = asdl_seq_LEN(args->args);
1566 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1567 n = asdl_seq_LEN(s->v.FunctionDef.body);
1568 /* if there was a docstring, we need to skip the first statement */
1569 for (i = docstring; i < n; i++) {
1570 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1571 VISIT_IN_SCOPE(c, stmt, st);
1572 }
1573 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001574 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001576 if (qualname == NULL || co == NULL) {
1577 Py_XDECREF(qualname);
1578 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001580 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 arglength = asdl_seq_LEN(args->defaults);
1583 arglength |= kw_default_count << 8;
1584 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001585 compiler_make_closure(c, co, arglength, qualname);
1586 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 /* decorators */
1590 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1591 ADDOP_I(c, CALL_FUNCTION, 1);
1592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595}
1596
1597static int
1598compiler_class(struct compiler *c, stmt_ty s)
1599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 PyCodeObject *co;
1601 PyObject *str;
1602 int i;
1603 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (!compiler_decorators(c, decos))
1606 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 /* ultimately generate code for:
1609 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1610 where:
1611 <func> is a function/closure created from the class body;
1612 it has a single argument (__locals__) where the dict
1613 (or MutableSequence) representing the locals is passed
1614 <name> is the class name
1615 <bases> is the positional arguments and *varargs argument
1616 <keywords> is the keyword arguments and **kwds argument
1617 This borrows from compiler_call.
1618 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001621 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1622 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 return 0;
1624 /* this block represents what we do in the new scope */
1625 {
1626 /* use the class name for name mangling */
1627 Py_INCREF(s->v.ClassDef.name);
1628 Py_XDECREF(c->u->u_private);
1629 c->u->u_private = s->v.ClassDef.name;
1630 /* force it to have one mandatory argument */
1631 c->u->u_argcount = 1;
1632 /* load the first argument (__locals__) ... */
1633 ADDOP_I(c, LOAD_FAST, 0);
1634 /* ... and store it into f_locals */
1635 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1636 /* load (global) __name__ ... */
1637 str = PyUnicode_InternFromString("__name__");
1638 if (!str || !compiler_nameop(c, str, Load)) {
1639 Py_XDECREF(str);
1640 compiler_exit_scope(c);
1641 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001642 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 Py_DECREF(str);
1644 /* ... and store it as __module__ */
1645 str = PyUnicode_InternFromString("__module__");
1646 if (!str || !compiler_nameop(c, str, Store)) {
1647 Py_XDECREF(str);
1648 compiler_exit_scope(c);
1649 return 0;
1650 }
1651 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001652 /* store the __qualname__ */
1653 str = compiler_scope_qualname(c);
1654 if (!str) {
1655 compiler_exit_scope(c);
1656 return 0;
1657 }
1658 ADDOP_O(c, LOAD_CONST, str, consts);
1659 Py_DECREF(str);
1660 str = PyUnicode_InternFromString("__qualname__");
1661 if (!str || !compiler_nameop(c, str, Store)) {
1662 Py_XDECREF(str);
1663 compiler_exit_scope(c);
1664 return 0;
1665 }
1666 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 /* compile the body proper */
1668 if (!compiler_body(c, s->v.ClassDef.body)) {
1669 compiler_exit_scope(c);
1670 return 0;
1671 }
1672 /* return the (empty) __class__ cell */
Benjamin Petersonf5ff2232011-06-19 19:42:22 -05001673 str = PyUnicode_InternFromString("@__class__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (str == NULL) {
1675 compiler_exit_scope(c);
1676 return 0;
1677 }
1678 i = compiler_lookup_arg(c->u->u_cellvars, str);
1679 Py_DECREF(str);
1680 if (i == -1) {
1681 /* This happens when nobody references the cell */
1682 PyErr_Clear();
1683 /* Return None */
1684 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1685 }
1686 else {
1687 /* Return the cell where to store __class__ */
1688 ADDOP_I(c, LOAD_CLOSURE, i);
1689 }
1690 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1691 /* create the code object */
1692 co = assemble(c, 1);
1693 }
1694 /* leave the new scope */
1695 compiler_exit_scope(c);
1696 if (co == NULL)
1697 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 /* 2. load the 'build_class' function */
1700 ADDOP(c, LOAD_BUILD_CLASS);
1701
1702 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001703 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 Py_DECREF(co);
1705
1706 /* 4. load class name */
1707 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1708
1709 /* 5. generate the rest of the code for the call */
1710 if (!compiler_call_helper(c, 2,
1711 s->v.ClassDef.bases,
1712 s->v.ClassDef.keywords,
1713 s->v.ClassDef.starargs,
1714 s->v.ClassDef.kwargs))
1715 return 0;
1716
1717 /* 6. apply decorators */
1718 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1719 ADDOP_I(c, CALL_FUNCTION, 1);
1720 }
1721
1722 /* 7. store into <name> */
1723 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1724 return 0;
1725 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726}
1727
1728static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001729compiler_ifexp(struct compiler *c, expr_ty e)
1730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 basicblock *end, *next;
1732
1733 assert(e->kind == IfExp_kind);
1734 end = compiler_new_block(c);
1735 if (end == NULL)
1736 return 0;
1737 next = compiler_new_block(c);
1738 if (next == NULL)
1739 return 0;
1740 VISIT(c, expr, e->v.IfExp.test);
1741 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1742 VISIT(c, expr, e->v.IfExp.body);
1743 ADDOP_JREL(c, JUMP_FORWARD, end);
1744 compiler_use_next_block(c, next);
1745 VISIT(c, expr, e->v.IfExp.orelse);
1746 compiler_use_next_block(c, end);
1747 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001748}
1749
1750static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751compiler_lambda(struct compiler *c, expr_ty e)
1752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001754 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 static identifier name;
1756 int kw_default_count = 0, arglength;
1757 arguments_ty args = e->v.Lambda.args;
1758 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (!name) {
1761 name = PyUnicode_InternFromString("<lambda>");
1762 if (!name)
1763 return 0;
1764 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (args->kwonlyargs) {
1767 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1768 args->kw_defaults);
1769 if (res < 0) return 0;
1770 kw_default_count = res;
1771 }
1772 if (args->defaults)
1773 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001774 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1775 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* Make None the first constant, so the lambda can't have a
1779 docstring. */
1780 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1781 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 c->u->u_argcount = asdl_seq_LEN(args->args);
1784 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1785 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1786 if (c->u->u_ste->ste_generator) {
1787 ADDOP_IN_SCOPE(c, POP_TOP);
1788 }
1789 else {
1790 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1791 }
1792 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001793 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001795 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 arglength = asdl_seq_LEN(args->defaults);
1799 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001800 compiler_make_closure(c, co, arglength, qualname);
1801 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 Py_DECREF(co);
1803
1804 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805}
1806
1807static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808compiler_if(struct compiler *c, stmt_ty s)
1809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 basicblock *end, *next;
1811 int constant;
1812 assert(s->kind == If_kind);
1813 end = compiler_new_block(c);
1814 if (end == NULL)
1815 return 0;
1816
Georg Brandl8334fd92010-12-04 10:26:46 +00001817 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 /* constant = 0: "if 0"
1819 * constant = 1: "if 1", "if 2", ...
1820 * constant = -1: rest */
1821 if (constant == 0) {
1822 if (s->v.If.orelse)
1823 VISIT_SEQ(c, stmt, s->v.If.orelse);
1824 } else if (constant == 1) {
1825 VISIT_SEQ(c, stmt, s->v.If.body);
1826 } else {
1827 if (s->v.If.orelse) {
1828 next = compiler_new_block(c);
1829 if (next == NULL)
1830 return 0;
1831 }
1832 else
1833 next = end;
1834 VISIT(c, expr, s->v.If.test);
1835 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1836 VISIT_SEQ(c, stmt, s->v.If.body);
1837 ADDOP_JREL(c, JUMP_FORWARD, end);
1838 if (s->v.If.orelse) {
1839 compiler_use_next_block(c, next);
1840 VISIT_SEQ(c, stmt, s->v.If.orelse);
1841 }
1842 }
1843 compiler_use_next_block(c, end);
1844 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845}
1846
1847static int
1848compiler_for(struct compiler *c, stmt_ty s)
1849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 start = compiler_new_block(c);
1853 cleanup = compiler_new_block(c);
1854 end = compiler_new_block(c);
1855 if (start == NULL || end == NULL || cleanup == NULL)
1856 return 0;
1857 ADDOP_JREL(c, SETUP_LOOP, end);
1858 if (!compiler_push_fblock(c, LOOP, start))
1859 return 0;
1860 VISIT(c, expr, s->v.For.iter);
1861 ADDOP(c, GET_ITER);
1862 compiler_use_next_block(c, start);
1863 ADDOP_JREL(c, FOR_ITER, cleanup);
1864 VISIT(c, expr, s->v.For.target);
1865 VISIT_SEQ(c, stmt, s->v.For.body);
1866 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1867 compiler_use_next_block(c, cleanup);
1868 ADDOP(c, POP_BLOCK);
1869 compiler_pop_fblock(c, LOOP, start);
1870 VISIT_SEQ(c, stmt, s->v.For.orelse);
1871 compiler_use_next_block(c, end);
1872 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873}
1874
1875static int
1876compiler_while(struct compiler *c, stmt_ty s)
1877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001879 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (constant == 0) {
1882 if (s->v.While.orelse)
1883 VISIT_SEQ(c, stmt, s->v.While.orelse);
1884 return 1;
1885 }
1886 loop = compiler_new_block(c);
1887 end = compiler_new_block(c);
1888 if (constant == -1) {
1889 anchor = compiler_new_block(c);
1890 if (anchor == NULL)
1891 return 0;
1892 }
1893 if (loop == NULL || end == NULL)
1894 return 0;
1895 if (s->v.While.orelse) {
1896 orelse = compiler_new_block(c);
1897 if (orelse == NULL)
1898 return 0;
1899 }
1900 else
1901 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 ADDOP_JREL(c, SETUP_LOOP, end);
1904 compiler_use_next_block(c, loop);
1905 if (!compiler_push_fblock(c, LOOP, loop))
1906 return 0;
1907 if (constant == -1) {
1908 VISIT(c, expr, s->v.While.test);
1909 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1910 }
1911 VISIT_SEQ(c, stmt, s->v.While.body);
1912 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 /* XXX should the two POP instructions be in a separate block
1915 if there is no else clause ?
1916 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (constant == -1) {
1919 compiler_use_next_block(c, anchor);
1920 ADDOP(c, POP_BLOCK);
1921 }
1922 compiler_pop_fblock(c, LOOP, loop);
1923 if (orelse != NULL) /* what if orelse is just pass? */
1924 VISIT_SEQ(c, stmt, s->v.While.orelse);
1925 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928}
1929
1930static int
1931compiler_continue(struct compiler *c)
1932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1934 static const char IN_FINALLY_ERROR_MSG[] =
1935 "'continue' not supported inside 'finally' clause";
1936 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 if (!c->u->u_nfblocks)
1939 return compiler_error(c, LOOP_ERROR_MSG);
1940 i = c->u->u_nfblocks - 1;
1941 switch (c->u->u_fblock[i].fb_type) {
1942 case LOOP:
1943 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1944 break;
1945 case EXCEPT:
1946 case FINALLY_TRY:
1947 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1948 /* Prevent continue anywhere under a finally
1949 even if hidden in a sub-try or except. */
1950 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1951 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1952 }
1953 if (i == -1)
1954 return compiler_error(c, LOOP_ERROR_MSG);
1955 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1956 break;
1957 case FINALLY_END:
1958 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1959 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
1964/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965
1966 SETUP_FINALLY L
1967 <code for body>
1968 POP_BLOCK
1969 LOAD_CONST <None>
1970 L: <code for finalbody>
1971 END_FINALLY
1972
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973 The special instructions use the block stack. Each block
1974 stack entry contains the instruction that created it (here
1975 SETUP_FINALLY), the level of the value stack at the time the
1976 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 Pushes the current value stack level and the label
1980 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 Pops en entry from the block stack, and pops the value
1983 stack until its level is the same as indicated on the
1984 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 Pops a variable number of entries from the *value* stack
1987 and re-raises the exception they specify. The number of
1988 entries popped depends on the (pseudo) exception type.
1989
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 The block stack is unwound when an exception is raised:
1991 when a SETUP_FINALLY entry is found, the exception is pushed
1992 onto the value stack (and the exception condition is cleared),
1993 and the interpreter jumps to the label gotten from the block
1994 stack.
1995*/
1996
1997static int
1998compiler_try_finally(struct compiler *c, stmt_ty s)
1999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 basicblock *body, *end;
2001 body = compiler_new_block(c);
2002 end = compiler_new_block(c);
2003 if (body == NULL || end == NULL)
2004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 ADDOP_JREL(c, SETUP_FINALLY, end);
2007 compiler_use_next_block(c, body);
2008 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2009 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002010 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2011 if (!compiler_try_except(c, s))
2012 return 0;
2013 }
2014 else {
2015 VISIT_SEQ(c, stmt, s->v.Try.body);
2016 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 ADDOP(c, POP_BLOCK);
2018 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2021 compiler_use_next_block(c, end);
2022 if (!compiler_push_fblock(c, FINALLY_END, end))
2023 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002024 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 ADDOP(c, END_FINALLY);
2026 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029}
2030
2031/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002032 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 (The contents of the value stack is shown in [], with the top
2034 at the right; 'tb' is trace-back info, 'val' the exception's
2035 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036
2037 Value stack Label Instruction Argument
2038 [] SETUP_EXCEPT L1
2039 [] <code for S>
2040 [] POP_BLOCK
2041 [] JUMP_FORWARD L0
2042
2043 [tb, val, exc] L1: DUP )
2044 [tb, val, exc, exc] <evaluate E1> )
2045 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2046 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2047 [tb, val, exc] POP
2048 [tb, val] <assign to V1> (or POP if no V1)
2049 [tb] POP
2050 [] <code for S1>
2051 JUMP_FORWARD L0
2052
2053 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 .............................etc.......................
2055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2057
2058 [] L0: <next statement>
2059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 Of course, parts are not generated if Vi or Ei is not present.
2061*/
2062static int
2063compiler_try_except(struct compiler *c, stmt_ty s)
2064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 basicblock *body, *orelse, *except, *end;
2066 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 body = compiler_new_block(c);
2069 except = compiler_new_block(c);
2070 orelse = compiler_new_block(c);
2071 end = compiler_new_block(c);
2072 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2073 return 0;
2074 ADDOP_JREL(c, SETUP_EXCEPT, except);
2075 compiler_use_next_block(c, body);
2076 if (!compiler_push_fblock(c, EXCEPT, body))
2077 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002078 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 ADDOP(c, POP_BLOCK);
2080 compiler_pop_fblock(c, EXCEPT, body);
2081 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002082 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 compiler_use_next_block(c, except);
2084 for (i = 0; i < n; i++) {
2085 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002086 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 if (!handler->v.ExceptHandler.type && i < n-1)
2088 return compiler_error(c, "default 'except:' must be last");
2089 c->u->u_lineno_set = 0;
2090 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002091 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 except = compiler_new_block(c);
2093 if (except == NULL)
2094 return 0;
2095 if (handler->v.ExceptHandler.type) {
2096 ADDOP(c, DUP_TOP);
2097 VISIT(c, expr, handler->v.ExceptHandler.type);
2098 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2099 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2100 }
2101 ADDOP(c, POP_TOP);
2102 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002103 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002104
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002105 cleanup_end = compiler_new_block(c);
2106 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002107 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002108 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002109
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002110 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2111 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002113 /*
2114 try:
2115 # body
2116 except type as name:
2117 try:
2118 # body
2119 finally:
2120 name = None
2121 del name
2122 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002124 /* second try: */
2125 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2126 compiler_use_next_block(c, cleanup_body);
2127 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2128 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002130 /* second # body */
2131 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2132 ADDOP(c, POP_BLOCK);
2133 ADDOP(c, POP_EXCEPT);
2134 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002136 /* finally: */
2137 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2138 compiler_use_next_block(c, cleanup_end);
2139 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2140 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002142 /* name = None */
2143 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2144 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002146 /* del name */
2147 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002149 ADDOP(c, END_FINALLY);
2150 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 }
2152 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002153 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002155 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002156 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002157 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158
Guido van Rossumb940e112007-01-10 16:19:56 +00002159 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002160 ADDOP(c, POP_TOP);
2161 compiler_use_next_block(c, cleanup_body);
2162 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2163 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002165 ADDOP(c, POP_EXCEPT);
2166 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 }
2168 ADDOP_JREL(c, JUMP_FORWARD, end);
2169 compiler_use_next_block(c, except);
2170 }
2171 ADDOP(c, END_FINALLY);
2172 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002173 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 compiler_use_next_block(c, end);
2175 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176}
2177
2178static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002179compiler_try(struct compiler *c, stmt_ty s) {
2180 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2181 return compiler_try_finally(c, s);
2182 else
2183 return compiler_try_except(c, s);
2184}
2185
2186
2187static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188compiler_import_as(struct compiler *c, identifier name, identifier asname)
2189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* The IMPORT_NAME opcode was already generated. This function
2191 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 If there is a dot in name, we need to split it and emit a
2194 LOAD_ATTR for each name.
2195 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002196 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2197 PyUnicode_GET_LENGTH(name), 1);
2198 if (dot == -2)
2199 return -1;
2200 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002202 Py_ssize_t pos = dot + 1;
2203 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 dot = PyUnicode_FindChar(name, '.', pos,
2206 PyUnicode_GET_LENGTH(name), 1);
2207 if (dot == -2)
2208 return -1;
2209 attr = PyUnicode_Substring(name, pos,
2210 (dot != -1) ? dot :
2211 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (!attr)
2213 return -1;
2214 ADDOP_O(c, LOAD_ATTR, attr, names);
2215 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 }
2218 }
2219 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002220}
2221
2222static int
2223compiler_import(struct compiler *c, stmt_ty s)
2224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* The Import node stores a module name like a.b.c as a single
2226 string. This is convenient for all cases except
2227 import a.b.c as d
2228 where we need to parse that string to extract the individual
2229 module names.
2230 XXX Perhaps change the representation to make this case simpler?
2231 */
2232 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 for (i = 0; i < n; i++) {
2235 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2236 int r;
2237 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 level = PyLong_FromLong(0);
2240 if (level == NULL)
2241 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 ADDOP_O(c, LOAD_CONST, level, consts);
2244 Py_DECREF(level);
2245 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2246 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (alias->asname) {
2249 r = compiler_import_as(c, alias->name, alias->asname);
2250 if (!r)
2251 return r;
2252 }
2253 else {
2254 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255 Py_ssize_t dot = PyUnicode_FindChar(
2256 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2257 if (dot != -1)
2258 tmp = PyUnicode_Substring(alias->name, 0, dot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_DECREF(tmp);
2262 }
2263 if (!r)
2264 return r;
2265 }
2266 }
2267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268}
2269
2270static int
2271compiler_from_import(struct compiler *c, stmt_ty s)
2272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 PyObject *names = PyTuple_New(n);
2276 PyObject *level;
2277 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (!empty_string) {
2280 empty_string = PyUnicode_FromString("");
2281 if (!empty_string)
2282 return 0;
2283 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 if (!names)
2286 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 level = PyLong_FromLong(s->v.ImportFrom.level);
2289 if (!level) {
2290 Py_DECREF(names);
2291 return 0;
2292 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* build up the names */
2295 for (i = 0; i < n; i++) {
2296 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2297 Py_INCREF(alias->name);
2298 PyTuple_SET_ITEM(names, i, alias->name);
2299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2302 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2303 Py_DECREF(level);
2304 Py_DECREF(names);
2305 return compiler_error(c, "from __future__ imports must occur "
2306 "at the beginning of the file");
2307 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 ADDOP_O(c, LOAD_CONST, level, consts);
2310 Py_DECREF(level);
2311 ADDOP_O(c, LOAD_CONST, names, consts);
2312 Py_DECREF(names);
2313 if (s->v.ImportFrom.module) {
2314 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2315 }
2316 else {
2317 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2318 }
2319 for (i = 0; i < n; i++) {
2320 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2321 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002323 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 assert(n == 1);
2325 ADDOP(c, IMPORT_STAR);
2326 return 1;
2327 }
2328
2329 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2330 store_name = alias->name;
2331 if (alias->asname)
2332 store_name = alias->asname;
2333
2334 if (!compiler_nameop(c, store_name, Store)) {
2335 Py_DECREF(names);
2336 return 0;
2337 }
2338 }
2339 /* remove imported module */
2340 ADDOP(c, POP_TOP);
2341 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342}
2343
2344static int
2345compiler_assert(struct compiler *c, stmt_ty s)
2346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 static PyObject *assertion_error = NULL;
2348 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349
Georg Brandl8334fd92010-12-04 10:26:46 +00002350 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 return 1;
2352 if (assertion_error == NULL) {
2353 assertion_error = PyUnicode_InternFromString("AssertionError");
2354 if (assertion_error == NULL)
2355 return 0;
2356 }
2357 if (s->v.Assert.test->kind == Tuple_kind &&
2358 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2359 const char* msg =
2360 "assertion is always true, perhaps remove parentheses?";
2361 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2362 c->u->u_lineno, NULL, NULL) == -1)
2363 return 0;
2364 }
2365 VISIT(c, expr, s->v.Assert.test);
2366 end = compiler_new_block(c);
2367 if (end == NULL)
2368 return 0;
2369 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2370 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2371 if (s->v.Assert.msg) {
2372 VISIT(c, expr, s->v.Assert.msg);
2373 ADDOP_I(c, CALL_FUNCTION, 1);
2374 }
2375 ADDOP_I(c, RAISE_VARARGS, 1);
2376 compiler_use_next_block(c, end);
2377 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002378}
2379
2380static int
2381compiler_visit_stmt(struct compiler *c, stmt_ty s)
2382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 /* Always assign a lineno to the next instruction for a stmt. */
2386 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002387 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 switch (s->kind) {
2391 case FunctionDef_kind:
2392 return compiler_function(c, s);
2393 case ClassDef_kind:
2394 return compiler_class(c, s);
2395 case Return_kind:
2396 if (c->u->u_ste->ste_type != FunctionBlock)
2397 return compiler_error(c, "'return' outside function");
2398 if (s->v.Return.value) {
2399 VISIT(c, expr, s->v.Return.value);
2400 }
2401 else
2402 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2403 ADDOP(c, RETURN_VALUE);
2404 break;
2405 case Delete_kind:
2406 VISIT_SEQ(c, expr, s->v.Delete.targets)
2407 break;
2408 case Assign_kind:
2409 n = asdl_seq_LEN(s->v.Assign.targets);
2410 VISIT(c, expr, s->v.Assign.value);
2411 for (i = 0; i < n; i++) {
2412 if (i < n - 1)
2413 ADDOP(c, DUP_TOP);
2414 VISIT(c, expr,
2415 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2416 }
2417 break;
2418 case AugAssign_kind:
2419 return compiler_augassign(c, s);
2420 case For_kind:
2421 return compiler_for(c, s);
2422 case While_kind:
2423 return compiler_while(c, s);
2424 case If_kind:
2425 return compiler_if(c, s);
2426 case Raise_kind:
2427 n = 0;
2428 if (s->v.Raise.exc) {
2429 VISIT(c, expr, s->v.Raise.exc);
2430 n++;
2431 if (s->v.Raise.cause) {
2432 VISIT(c, expr, s->v.Raise.cause);
2433 n++;
2434 }
2435 }
2436 ADDOP_I(c, RAISE_VARARGS, n);
2437 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002438 case Try_kind:
2439 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 case Assert_kind:
2441 return compiler_assert(c, s);
2442 case Import_kind:
2443 return compiler_import(c, s);
2444 case ImportFrom_kind:
2445 return compiler_from_import(c, s);
2446 case Global_kind:
2447 case Nonlocal_kind:
2448 break;
2449 case Expr_kind:
2450 if (c->c_interactive && c->c_nestlevel <= 1) {
2451 VISIT(c, expr, s->v.Expr.value);
2452 ADDOP(c, PRINT_EXPR);
2453 }
2454 else if (s->v.Expr.value->kind != Str_kind &&
2455 s->v.Expr.value->kind != Num_kind) {
2456 VISIT(c, expr, s->v.Expr.value);
2457 ADDOP(c, POP_TOP);
2458 }
2459 break;
2460 case Pass_kind:
2461 break;
2462 case Break_kind:
2463 if (!compiler_in_loop(c))
2464 return compiler_error(c, "'break' outside loop");
2465 ADDOP(c, BREAK_LOOP);
2466 break;
2467 case Continue_kind:
2468 return compiler_continue(c);
2469 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002470 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 }
2472 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473}
2474
2475static int
2476unaryop(unaryop_ty op)
2477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 switch (op) {
2479 case Invert:
2480 return UNARY_INVERT;
2481 case Not:
2482 return UNARY_NOT;
2483 case UAdd:
2484 return UNARY_POSITIVE;
2485 case USub:
2486 return UNARY_NEGATIVE;
2487 default:
2488 PyErr_Format(PyExc_SystemError,
2489 "unary op %d should not be possible", op);
2490 return 0;
2491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002492}
2493
2494static int
2495binop(struct compiler *c, operator_ty op)
2496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 switch (op) {
2498 case Add:
2499 return BINARY_ADD;
2500 case Sub:
2501 return BINARY_SUBTRACT;
2502 case Mult:
2503 return BINARY_MULTIPLY;
2504 case Div:
2505 return BINARY_TRUE_DIVIDE;
2506 case Mod:
2507 return BINARY_MODULO;
2508 case Pow:
2509 return BINARY_POWER;
2510 case LShift:
2511 return BINARY_LSHIFT;
2512 case RShift:
2513 return BINARY_RSHIFT;
2514 case BitOr:
2515 return BINARY_OR;
2516 case BitXor:
2517 return BINARY_XOR;
2518 case BitAnd:
2519 return BINARY_AND;
2520 case FloorDiv:
2521 return BINARY_FLOOR_DIVIDE;
2522 default:
2523 PyErr_Format(PyExc_SystemError,
2524 "binary op %d should not be possible", op);
2525 return 0;
2526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527}
2528
2529static int
2530cmpop(cmpop_ty op)
2531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 switch (op) {
2533 case Eq:
2534 return PyCmp_EQ;
2535 case NotEq:
2536 return PyCmp_NE;
2537 case Lt:
2538 return PyCmp_LT;
2539 case LtE:
2540 return PyCmp_LE;
2541 case Gt:
2542 return PyCmp_GT;
2543 case GtE:
2544 return PyCmp_GE;
2545 case Is:
2546 return PyCmp_IS;
2547 case IsNot:
2548 return PyCmp_IS_NOT;
2549 case In:
2550 return PyCmp_IN;
2551 case NotIn:
2552 return PyCmp_NOT_IN;
2553 default:
2554 return PyCmp_BAD;
2555 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556}
2557
2558static int
2559inplace_binop(struct compiler *c, operator_ty op)
2560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 switch (op) {
2562 case Add:
2563 return INPLACE_ADD;
2564 case Sub:
2565 return INPLACE_SUBTRACT;
2566 case Mult:
2567 return INPLACE_MULTIPLY;
2568 case Div:
2569 return INPLACE_TRUE_DIVIDE;
2570 case Mod:
2571 return INPLACE_MODULO;
2572 case Pow:
2573 return INPLACE_POWER;
2574 case LShift:
2575 return INPLACE_LSHIFT;
2576 case RShift:
2577 return INPLACE_RSHIFT;
2578 case BitOr:
2579 return INPLACE_OR;
2580 case BitXor:
2581 return INPLACE_XOR;
2582 case BitAnd:
2583 return INPLACE_AND;
2584 case FloorDiv:
2585 return INPLACE_FLOOR_DIVIDE;
2586 default:
2587 PyErr_Format(PyExc_SystemError,
2588 "inplace binary op %d should not be possible", op);
2589 return 0;
2590 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591}
2592
2593static int
2594compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 int op, scope, arg;
2597 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 PyObject *dict = c->u->u_names;
2600 PyObject *mangled;
2601 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 mangled = _Py_Mangle(c->u->u_private, name);
2604 if (!mangled)
2605 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 op = 0;
2608 optype = OP_NAME;
2609 scope = PyST_GetScope(c->u->u_ste, mangled);
2610 switch (scope) {
2611 case FREE:
2612 dict = c->u->u_freevars;
2613 optype = OP_DEREF;
2614 break;
2615 case CELL:
2616 dict = c->u->u_cellvars;
2617 optype = OP_DEREF;
2618 break;
2619 case LOCAL:
2620 if (c->u->u_ste->ste_type == FunctionBlock)
2621 optype = OP_FAST;
2622 break;
2623 case GLOBAL_IMPLICIT:
2624 if (c->u->u_ste->ste_type == FunctionBlock &&
2625 !c->u->u_ste->ste_unoptimized)
2626 optype = OP_GLOBAL;
2627 break;
2628 case GLOBAL_EXPLICIT:
2629 optype = OP_GLOBAL;
2630 break;
2631 default:
2632 /* scope can be 0 */
2633 break;
2634 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002637 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 switch (optype) {
2640 case OP_DEREF:
2641 switch (ctx) {
2642 case Load: op = LOAD_DEREF; break;
2643 case Store: op = STORE_DEREF; break;
2644 case AugLoad:
2645 case AugStore:
2646 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002647 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 case Param:
2649 default:
2650 PyErr_SetString(PyExc_SystemError,
2651 "param invalid for deref variable");
2652 return 0;
2653 }
2654 break;
2655 case OP_FAST:
2656 switch (ctx) {
2657 case Load: op = LOAD_FAST; break;
2658 case Store: op = STORE_FAST; break;
2659 case Del: op = DELETE_FAST; break;
2660 case AugLoad:
2661 case AugStore:
2662 break;
2663 case Param:
2664 default:
2665 PyErr_SetString(PyExc_SystemError,
2666 "param invalid for local variable");
2667 return 0;
2668 }
2669 ADDOP_O(c, op, mangled, varnames);
2670 Py_DECREF(mangled);
2671 return 1;
2672 case OP_GLOBAL:
2673 switch (ctx) {
2674 case Load: op = LOAD_GLOBAL; break;
2675 case Store: op = STORE_GLOBAL; break;
2676 case Del: op = DELETE_GLOBAL; break;
2677 case AugLoad:
2678 case AugStore:
2679 break;
2680 case Param:
2681 default:
2682 PyErr_SetString(PyExc_SystemError,
2683 "param invalid for global variable");
2684 return 0;
2685 }
2686 break;
2687 case OP_NAME:
2688 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002689 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 case Store: op = STORE_NAME; break;
2691 case Del: op = DELETE_NAME; break;
2692 case AugLoad:
2693 case AugStore:
2694 break;
2695 case Param:
2696 default:
2697 PyErr_SetString(PyExc_SystemError,
2698 "param invalid for name variable");
2699 return 0;
2700 }
2701 break;
2702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 assert(op);
2705 arg = compiler_add_o(c, dict, mangled);
2706 Py_DECREF(mangled);
2707 if (arg < 0)
2708 return 0;
2709 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710}
2711
2712static int
2713compiler_boolop(struct compiler *c, expr_ty e)
2714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 basicblock *end;
2716 int jumpi, i, n;
2717 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 assert(e->kind == BoolOp_kind);
2720 if (e->v.BoolOp.op == And)
2721 jumpi = JUMP_IF_FALSE_OR_POP;
2722 else
2723 jumpi = JUMP_IF_TRUE_OR_POP;
2724 end = compiler_new_block(c);
2725 if (end == NULL)
2726 return 0;
2727 s = e->v.BoolOp.values;
2728 n = asdl_seq_LEN(s) - 1;
2729 assert(n >= 0);
2730 for (i = 0; i < n; ++i) {
2731 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2732 ADDOP_JABS(c, jumpi, end);
2733 }
2734 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2735 compiler_use_next_block(c, end);
2736 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737}
2738
2739static int
2740compiler_list(struct compiler *c, expr_ty e)
2741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 int n = asdl_seq_LEN(e->v.List.elts);
2743 if (e->v.List.ctx == Store) {
2744 int i, seen_star = 0;
2745 for (i = 0; i < n; i++) {
2746 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2747 if (elt->kind == Starred_kind && !seen_star) {
2748 if ((i >= (1 << 8)) ||
2749 (n-i-1 >= (INT_MAX >> 8)))
2750 return compiler_error(c,
2751 "too many expressions in "
2752 "star-unpacking assignment");
2753 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2754 seen_star = 1;
2755 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2756 } else if (elt->kind == Starred_kind) {
2757 return compiler_error(c,
2758 "two starred expressions in assignment");
2759 }
2760 }
2761 if (!seen_star) {
2762 ADDOP_I(c, UNPACK_SEQUENCE, n);
2763 }
2764 }
2765 VISIT_SEQ(c, expr, e->v.List.elts);
2766 if (e->v.List.ctx == Load) {
2767 ADDOP_I(c, BUILD_LIST, n);
2768 }
2769 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770}
2771
2772static int
2773compiler_tuple(struct compiler *c, expr_ty e)
2774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 int n = asdl_seq_LEN(e->v.Tuple.elts);
2776 if (e->v.Tuple.ctx == Store) {
2777 int i, seen_star = 0;
2778 for (i = 0; i < n; i++) {
2779 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2780 if (elt->kind == Starred_kind && !seen_star) {
2781 if ((i >= (1 << 8)) ||
2782 (n-i-1 >= (INT_MAX >> 8)))
2783 return compiler_error(c,
2784 "too many expressions in "
2785 "star-unpacking assignment");
2786 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2787 seen_star = 1;
2788 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2789 } else if (elt->kind == Starred_kind) {
2790 return compiler_error(c,
2791 "two starred expressions in assignment");
2792 }
2793 }
2794 if (!seen_star) {
2795 ADDOP_I(c, UNPACK_SEQUENCE, n);
2796 }
2797 }
2798 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2799 if (e->v.Tuple.ctx == Load) {
2800 ADDOP_I(c, BUILD_TUPLE, n);
2801 }
2802 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002803}
2804
2805static int
2806compiler_compare(struct compiler *c, expr_ty e)
2807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 int i, n;
2809 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2812 VISIT(c, expr, e->v.Compare.left);
2813 n = asdl_seq_LEN(e->v.Compare.ops);
2814 assert(n > 0);
2815 if (n > 1) {
2816 cleanup = compiler_new_block(c);
2817 if (cleanup == NULL)
2818 return 0;
2819 VISIT(c, expr,
2820 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2821 }
2822 for (i = 1; i < n; i++) {
2823 ADDOP(c, DUP_TOP);
2824 ADDOP(c, ROT_THREE);
2825 ADDOP_I(c, COMPARE_OP,
2826 cmpop((cmpop_ty)(asdl_seq_GET(
2827 e->v.Compare.ops, i - 1))));
2828 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2829 NEXT_BLOCK(c);
2830 if (i < (n - 1))
2831 VISIT(c, expr,
2832 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2833 }
2834 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2835 ADDOP_I(c, COMPARE_OP,
2836 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2837 if (n > 1) {
2838 basicblock *end = compiler_new_block(c);
2839 if (end == NULL)
2840 return 0;
2841 ADDOP_JREL(c, JUMP_FORWARD, end);
2842 compiler_use_next_block(c, cleanup);
2843 ADDOP(c, ROT_TWO);
2844 ADDOP(c, POP_TOP);
2845 compiler_use_next_block(c, end);
2846 }
2847 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848}
2849
2850static int
2851compiler_call(struct compiler *c, expr_ty e)
2852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 VISIT(c, expr, e->v.Call.func);
2854 return compiler_call_helper(c, 0,
2855 e->v.Call.args,
2856 e->v.Call.keywords,
2857 e->v.Call.starargs,
2858 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002859}
2860
2861/* shared code between compiler_call and compiler_class */
2862static int
2863compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 int n, /* Args already pushed */
2865 asdl_seq *args,
2866 asdl_seq *keywords,
2867 expr_ty starargs,
2868 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 n += asdl_seq_LEN(args);
2873 VISIT_SEQ(c, expr, args);
2874 if (keywords) {
2875 VISIT_SEQ(c, keyword, keywords);
2876 n |= asdl_seq_LEN(keywords) << 8;
2877 }
2878 if (starargs) {
2879 VISIT(c, expr, starargs);
2880 code |= 1;
2881 }
2882 if (kwargs) {
2883 VISIT(c, expr, kwargs);
2884 code |= 2;
2885 }
2886 switch (code) {
2887 case 0:
2888 ADDOP_I(c, CALL_FUNCTION, n);
2889 break;
2890 case 1:
2891 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2892 break;
2893 case 2:
2894 ADDOP_I(c, CALL_FUNCTION_KW, n);
2895 break;
2896 case 3:
2897 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2898 break;
2899 }
2900 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901}
2902
Nick Coghlan650f0d02007-04-15 12:05:43 +00002903
2904/* List and set comprehensions and generator expressions work by creating a
2905 nested function to perform the actual iteration. This means that the
2906 iteration variables don't leak into the current scope.
2907 The defined function is called immediately following its definition, with the
2908 result of that call being the result of the expression.
2909 The LC/SC version returns the populated container, while the GE version is
2910 flagged in symtable.c as a generator, so it returns the generator object
2911 when the function is called.
2912 This code *knows* that the loop cannot contain break, continue, or return,
2913 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2914
2915 Possible cleanups:
2916 - iterate over the generator sequence instead of using recursion
2917*/
2918
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920compiler_comprehension_generator(struct compiler *c,
2921 asdl_seq *generators, int gen_index,
2922 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 /* generate code for the iterator, then each of the ifs,
2925 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 comprehension_ty gen;
2928 basicblock *start, *anchor, *skip, *if_cleanup;
2929 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 start = compiler_new_block(c);
2932 skip = compiler_new_block(c);
2933 if_cleanup = compiler_new_block(c);
2934 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2937 anchor == NULL)
2938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 if (gen_index == 0) {
2943 /* Receive outermost iter as an implicit argument */
2944 c->u->u_argcount = 1;
2945 ADDOP_I(c, LOAD_FAST, 0);
2946 }
2947 else {
2948 /* Sub-iter - calculate on the fly */
2949 VISIT(c, expr, gen->iter);
2950 ADDOP(c, GET_ITER);
2951 }
2952 compiler_use_next_block(c, start);
2953 ADDOP_JREL(c, FOR_ITER, anchor);
2954 NEXT_BLOCK(c);
2955 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 /* XXX this needs to be cleaned up...a lot! */
2958 n = asdl_seq_LEN(gen->ifs);
2959 for (i = 0; i < n; i++) {
2960 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2961 VISIT(c, expr, e);
2962 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2963 NEXT_BLOCK(c);
2964 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 if (++gen_index < asdl_seq_LEN(generators))
2967 if (!compiler_comprehension_generator(c,
2968 generators, gen_index,
2969 elt, val, type))
2970 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 /* only append after the last for generator */
2973 if (gen_index >= asdl_seq_LEN(generators)) {
2974 /* comprehension specific code */
2975 switch (type) {
2976 case COMP_GENEXP:
2977 VISIT(c, expr, elt);
2978 ADDOP(c, YIELD_VALUE);
2979 ADDOP(c, POP_TOP);
2980 break;
2981 case COMP_LISTCOMP:
2982 VISIT(c, expr, elt);
2983 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2984 break;
2985 case COMP_SETCOMP:
2986 VISIT(c, expr, elt);
2987 ADDOP_I(c, SET_ADD, gen_index + 1);
2988 break;
2989 case COMP_DICTCOMP:
2990 /* With 'd[k] = v', v is evaluated before k, so we do
2991 the same. */
2992 VISIT(c, expr, val);
2993 VISIT(c, expr, elt);
2994 ADDOP_I(c, MAP_ADD, gen_index + 1);
2995 break;
2996 default:
2997 return 0;
2998 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 compiler_use_next_block(c, skip);
3001 }
3002 compiler_use_next_block(c, if_cleanup);
3003 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3004 compiler_use_next_block(c, anchor);
3005
3006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007}
3008
3009static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003010compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 PyCodeObject *co = NULL;
3014 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003015 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 outermost_iter = ((comprehension_ty)
3018 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003019
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003020 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3021 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 if (type != COMP_GENEXP) {
3025 int op;
3026 switch (type) {
3027 case COMP_LISTCOMP:
3028 op = BUILD_LIST;
3029 break;
3030 case COMP_SETCOMP:
3031 op = BUILD_SET;
3032 break;
3033 case COMP_DICTCOMP:
3034 op = BUILD_MAP;
3035 break;
3036 default:
3037 PyErr_Format(PyExc_SystemError,
3038 "unknown comprehension type %d", type);
3039 goto error_in_scope;
3040 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 ADDOP_I(c, op, 0);
3043 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 if (!compiler_comprehension_generator(c, generators, 0, elt,
3046 val, type))
3047 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 if (type != COMP_GENEXP) {
3050 ADDOP(c, RETURN_VALUE);
3051 }
3052
3053 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003054 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003056 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 goto error;
3058
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003059 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003061 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 Py_DECREF(co);
3063
3064 VISIT(c, expr, outermost_iter);
3065 ADDOP(c, GET_ITER);
3066 ADDOP_I(c, CALL_FUNCTION, 1);
3067 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003068error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003070error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003071 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 Py_XDECREF(co);
3073 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003074}
3075
3076static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077compiler_genexp(struct compiler *c, expr_ty e)
3078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 static identifier name;
3080 if (!name) {
3081 name = PyUnicode_FromString("<genexpr>");
3082 if (!name)
3083 return 0;
3084 }
3085 assert(e->kind == GeneratorExp_kind);
3086 return compiler_comprehension(c, e, COMP_GENEXP, name,
3087 e->v.GeneratorExp.generators,
3088 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003089}
3090
3091static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003092compiler_listcomp(struct compiler *c, expr_ty e)
3093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 static identifier name;
3095 if (!name) {
3096 name = PyUnicode_FromString("<listcomp>");
3097 if (!name)
3098 return 0;
3099 }
3100 assert(e->kind == ListComp_kind);
3101 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3102 e->v.ListComp.generators,
3103 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003104}
3105
3106static int
3107compiler_setcomp(struct compiler *c, expr_ty e)
3108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 static identifier name;
3110 if (!name) {
3111 name = PyUnicode_FromString("<setcomp>");
3112 if (!name)
3113 return 0;
3114 }
3115 assert(e->kind == SetComp_kind);
3116 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3117 e->v.SetComp.generators,
3118 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003119}
3120
3121
3122static int
3123compiler_dictcomp(struct compiler *c, expr_ty e)
3124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 static identifier name;
3126 if (!name) {
3127 name = PyUnicode_FromString("<dictcomp>");
3128 if (!name)
3129 return 0;
3130 }
3131 assert(e->kind == DictComp_kind);
3132 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3133 e->v.DictComp.generators,
3134 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003135}
3136
3137
3138static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139compiler_visit_keyword(struct compiler *c, keyword_ty k)
3140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3142 VISIT(c, expr, k->value);
3143 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144}
3145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147 whether they are true or false.
3148
3149 Return values: 1 for true, 0 for false, -1 for non-constant.
3150 */
3151
3152static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003153expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 char *id;
3156 switch (e->kind) {
3157 case Ellipsis_kind:
3158 return 1;
3159 case Num_kind:
3160 return PyObject_IsTrue(e->v.Num.n);
3161 case Str_kind:
3162 return PyObject_IsTrue(e->v.Str.s);
3163 case Name_kind:
3164 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003165 id = PyUnicode_AsUTF8(e->v.Name.id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 if (strcmp(id, "True") == 0) return 1;
3167 if (strcmp(id, "False") == 0) return 0;
3168 if (strcmp(id, "None") == 0) return 0;
3169 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003170 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 /* fall through */
3172 default:
3173 return -1;
3174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175}
3176
Guido van Rossumc2e20742006-02-27 22:32:47 +00003177/*
3178 Implements the with statement from PEP 343.
3179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003181
3182 with EXPR as VAR:
3183 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184
Guido van Rossumc2e20742006-02-27 22:32:47 +00003185 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186
Thomas Wouters477c8d52006-05-27 19:21:47 +00003187 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003188 exit = context.__exit__ # not calling it
3189 value = context.__enter__()
3190 try:
3191 VAR = value # if VAR present in the syntax
3192 BLOCK
3193 finally:
3194 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003196 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003198 exit(*exc)
3199 */
3200static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003201compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003202{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003203 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003204 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003205
3206 assert(s->kind == With_kind);
3207
Guido van Rossumc2e20742006-02-27 22:32:47 +00003208 block = compiler_new_block(c);
3209 finally = compiler_new_block(c);
3210 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003211 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003212
Thomas Wouters477c8d52006-05-27 19:21:47 +00003213 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003214 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003215 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003216
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003217 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003218 compiler_use_next_block(c, block);
3219 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003220 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003221 }
3222
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003223 if (item->optional_vars) {
3224 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003225 }
3226 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003228 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003229 }
3230
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003231 pos++;
3232 if (pos == asdl_seq_LEN(s->v.With.items))
3233 /* BLOCK code */
3234 VISIT_SEQ(c, stmt, s->v.With.body)
3235 else if (!compiler_with(c, s, pos))
3236 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003237
3238 /* End of try block; start the finally block */
3239 ADDOP(c, POP_BLOCK);
3240 compiler_pop_fblock(c, FINALLY_TRY, block);
3241
3242 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3243 compiler_use_next_block(c, finally);
3244 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003245 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003246
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003247 /* Finally block starts; context.__exit__ is on the stack under
3248 the exception or return information. Just issue our magic
3249 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003250 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003251
3252 /* Finally block ends. */
3253 ADDOP(c, END_FINALLY);
3254 compiler_pop_fblock(c, FINALLY_END, finally);
3255 return 1;
3256}
3257
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258static int
3259compiler_visit_expr(struct compiler *c, expr_ty e)
3260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 /* If expr e has a different line number than the last expr/stmt,
3264 set a new line number for the next instruction.
3265 */
3266 if (e->lineno > c->u->u_lineno) {
3267 c->u->u_lineno = e->lineno;
3268 c->u->u_lineno_set = 0;
3269 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003270 /* Updating the column offset is always harmless. */
3271 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 switch (e->kind) {
3273 case BoolOp_kind:
3274 return compiler_boolop(c, e);
3275 case BinOp_kind:
3276 VISIT(c, expr, e->v.BinOp.left);
3277 VISIT(c, expr, e->v.BinOp.right);
3278 ADDOP(c, binop(c, e->v.BinOp.op));
3279 break;
3280 case UnaryOp_kind:
3281 VISIT(c, expr, e->v.UnaryOp.operand);
3282 ADDOP(c, unaryop(e->v.UnaryOp.op));
3283 break;
3284 case Lambda_kind:
3285 return compiler_lambda(c, e);
3286 case IfExp_kind:
3287 return compiler_ifexp(c, e);
3288 case Dict_kind:
3289 n = asdl_seq_LEN(e->v.Dict.values);
3290 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3291 for (i = 0; i < n; i++) {
3292 VISIT(c, expr,
3293 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3294 VISIT(c, expr,
3295 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3296 ADDOP(c, STORE_MAP);
3297 }
3298 break;
3299 case Set_kind:
3300 n = asdl_seq_LEN(e->v.Set.elts);
3301 VISIT_SEQ(c, expr, e->v.Set.elts);
3302 ADDOP_I(c, BUILD_SET, n);
3303 break;
3304 case GeneratorExp_kind:
3305 return compiler_genexp(c, e);
3306 case ListComp_kind:
3307 return compiler_listcomp(c, e);
3308 case SetComp_kind:
3309 return compiler_setcomp(c, e);
3310 case DictComp_kind:
3311 return compiler_dictcomp(c, e);
3312 case Yield_kind:
3313 if (c->u->u_ste->ste_type != FunctionBlock)
3314 return compiler_error(c, "'yield' outside function");
3315 if (e->v.Yield.value) {
3316 VISIT(c, expr, e->v.Yield.value);
3317 }
3318 else {
3319 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3320 }
3321 ADDOP(c, YIELD_VALUE);
3322 break;
3323 case Compare_kind:
3324 return compiler_compare(c, e);
3325 case Call_kind:
3326 return compiler_call(c, e);
3327 case Num_kind:
3328 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3329 break;
3330 case Str_kind:
3331 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3332 break;
3333 case Bytes_kind:
3334 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3335 break;
3336 case Ellipsis_kind:
3337 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3338 break;
3339 /* The following exprs can be assignment targets. */
3340 case Attribute_kind:
3341 if (e->v.Attribute.ctx != AugStore)
3342 VISIT(c, expr, e->v.Attribute.value);
3343 switch (e->v.Attribute.ctx) {
3344 case AugLoad:
3345 ADDOP(c, DUP_TOP);
3346 /* Fall through to load */
3347 case Load:
3348 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3349 break;
3350 case AugStore:
3351 ADDOP(c, ROT_TWO);
3352 /* Fall through to save */
3353 case Store:
3354 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3355 break;
3356 case Del:
3357 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3358 break;
3359 case Param:
3360 default:
3361 PyErr_SetString(PyExc_SystemError,
3362 "param invalid in attribute expression");
3363 return 0;
3364 }
3365 break;
3366 case Subscript_kind:
3367 switch (e->v.Subscript.ctx) {
3368 case AugLoad:
3369 VISIT(c, expr, e->v.Subscript.value);
3370 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3371 break;
3372 case Load:
3373 VISIT(c, expr, e->v.Subscript.value);
3374 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3375 break;
3376 case AugStore:
3377 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3378 break;
3379 case Store:
3380 VISIT(c, expr, e->v.Subscript.value);
3381 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3382 break;
3383 case Del:
3384 VISIT(c, expr, e->v.Subscript.value);
3385 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3386 break;
3387 case Param:
3388 default:
3389 PyErr_SetString(PyExc_SystemError,
3390 "param invalid in subscript expression");
3391 return 0;
3392 }
3393 break;
3394 case Starred_kind:
3395 switch (e->v.Starred.ctx) {
3396 case Store:
3397 /* In all legitimate cases, the Starred node was already replaced
3398 * by compiler_list/compiler_tuple. XXX: is that okay? */
3399 return compiler_error(c,
3400 "starred assignment target must be in a list or tuple");
3401 default:
3402 return compiler_error(c,
3403 "can use starred expression only as assignment target");
3404 }
3405 break;
3406 case Name_kind:
3407 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3408 /* child nodes of List and Tuple will have expr_context set */
3409 case List_kind:
3410 return compiler_list(c, e);
3411 case Tuple_kind:
3412 return compiler_tuple(c, e);
3413 }
3414 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003415}
3416
3417static int
3418compiler_augassign(struct compiler *c, stmt_ty s)
3419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 expr_ty e = s->v.AugAssign.target;
3421 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 switch (e->kind) {
3426 case Attribute_kind:
3427 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3428 AugLoad, e->lineno, e->col_offset, c->c_arena);
3429 if (auge == NULL)
3430 return 0;
3431 VISIT(c, expr, auge);
3432 VISIT(c, expr, s->v.AugAssign.value);
3433 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3434 auge->v.Attribute.ctx = AugStore;
3435 VISIT(c, expr, auge);
3436 break;
3437 case Subscript_kind:
3438 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3439 AugLoad, e->lineno, e->col_offset, c->c_arena);
3440 if (auge == NULL)
3441 return 0;
3442 VISIT(c, expr, auge);
3443 VISIT(c, expr, s->v.AugAssign.value);
3444 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3445 auge->v.Subscript.ctx = AugStore;
3446 VISIT(c, expr, auge);
3447 break;
3448 case Name_kind:
3449 if (!compiler_nameop(c, e->v.Name.id, Load))
3450 return 0;
3451 VISIT(c, expr, s->v.AugAssign.value);
3452 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3453 return compiler_nameop(c, e->v.Name.id, Store);
3454 default:
3455 PyErr_Format(PyExc_SystemError,
3456 "invalid node type (%d) for augmented assignment",
3457 e->kind);
3458 return 0;
3459 }
3460 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461}
3462
3463static int
3464compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 struct fblockinfo *f;
3467 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3468 PyErr_SetString(PyExc_SystemError,
3469 "too many statically nested blocks");
3470 return 0;
3471 }
3472 f = &c->u->u_fblock[c->u->u_nfblocks++];
3473 f->fb_type = t;
3474 f->fb_block = b;
3475 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003476}
3477
3478static void
3479compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 struct compiler_unit *u = c->u;
3482 assert(u->u_nfblocks > 0);
3483 u->u_nfblocks--;
3484 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3485 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003486}
3487
Thomas Wouters89f507f2006-12-13 04:49:30 +00003488static int
3489compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 int i;
3491 struct compiler_unit *u = c->u;
3492 for (i = 0; i < u->u_nfblocks; ++i) {
3493 if (u->u_fblock[i].fb_type == LOOP)
3494 return 1;
3495 }
3496 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003497}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498/* Raises a SyntaxError and returns 0.
3499 If something goes wrong, a different exception may be raised.
3500*/
3501
3502static int
3503compiler_error(struct compiler *c, const char *errstr)
3504{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003505 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3509 if (!loc) {
3510 Py_INCREF(Py_None);
3511 loc = Py_None;
3512 }
Benjamin Peterson43b06862011-05-27 09:08:01 -05003513 u = Py_BuildValue("(OiiO)", c->c_filename_obj, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003514 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 if (!u)
3516 goto exit;
3517 v = Py_BuildValue("(zO)", errstr, u);
3518 if (!v)
3519 goto exit;
3520 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 Py_DECREF(loc);
3523 Py_XDECREF(u);
3524 Py_XDECREF(v);
3525 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526}
3527
3528static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529compiler_handle_subscr(struct compiler *c, const char *kind,
3530 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 /* XXX this code is duplicated */
3535 switch (ctx) {
3536 case AugLoad: /* fall through to Load */
3537 case Load: op = BINARY_SUBSCR; break;
3538 case AugStore:/* fall through to Store */
3539 case Store: op = STORE_SUBSCR; break;
3540 case Del: op = DELETE_SUBSCR; break;
3541 case Param:
3542 PyErr_Format(PyExc_SystemError,
3543 "invalid %s kind %d in subscript\n",
3544 kind, ctx);
3545 return 0;
3546 }
3547 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003548 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 }
3550 else if (ctx == AugStore) {
3551 ADDOP(c, ROT_THREE);
3552 }
3553 ADDOP(c, op);
3554 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555}
3556
3557static int
3558compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 int n = 2;
3561 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 /* only handles the cases where BUILD_SLICE is emitted */
3564 if (s->v.Slice.lower) {
3565 VISIT(c, expr, s->v.Slice.lower);
3566 }
3567 else {
3568 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3569 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 if (s->v.Slice.upper) {
3572 VISIT(c, expr, s->v.Slice.upper);
3573 }
3574 else {
3575 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3576 }
3577
3578 if (s->v.Slice.step) {
3579 n++;
3580 VISIT(c, expr, s->v.Slice.step);
3581 }
3582 ADDOP_I(c, BUILD_SLICE, n);
3583 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584}
3585
3586static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3588 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 switch (s->kind) {
3591 case Slice_kind:
3592 return compiler_slice(c, s, ctx);
3593 case Index_kind:
3594 VISIT(c, expr, s->v.Index.value);
3595 break;
3596 case ExtSlice_kind:
3597 default:
3598 PyErr_SetString(PyExc_SystemError,
3599 "extended slice invalid in nested slice");
3600 return 0;
3601 }
3602 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003603}
3604
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605static int
3606compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 char * kindname = NULL;
3609 switch (s->kind) {
3610 case Index_kind:
3611 kindname = "index";
3612 if (ctx != AugStore) {
3613 VISIT(c, expr, s->v.Index.value);
3614 }
3615 break;
3616 case Slice_kind:
3617 kindname = "slice";
3618 if (ctx != AugStore) {
3619 if (!compiler_slice(c, s, ctx))
3620 return 0;
3621 }
3622 break;
3623 case ExtSlice_kind:
3624 kindname = "extended slice";
3625 if (ctx != AugStore) {
3626 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3627 for (i = 0; i < n; i++) {
3628 slice_ty sub = (slice_ty)asdl_seq_GET(
3629 s->v.ExtSlice.dims, i);
3630 if (!compiler_visit_nested_slice(c, sub, ctx))
3631 return 0;
3632 }
3633 ADDOP_I(c, BUILD_TUPLE, n);
3634 }
3635 break;
3636 default:
3637 PyErr_Format(PyExc_SystemError,
3638 "invalid subscript kind %d", s->kind);
3639 return 0;
3640 }
3641 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642}
3643
Thomas Wouters89f507f2006-12-13 04:49:30 +00003644/* End of the compiler section, beginning of the assembler section */
3645
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003646/* do depth-first search of basic block graph, starting with block.
3647 post records the block indices in post-order.
3648
3649 XXX must handle implicit jumps from one block to next
3650*/
3651
Thomas Wouters89f507f2006-12-13 04:49:30 +00003652struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 PyObject *a_bytecode; /* string containing bytecode */
3654 int a_offset; /* offset into bytecode */
3655 int a_nblocks; /* number of reachable blocks */
3656 basicblock **a_postorder; /* list of blocks in dfs postorder */
3657 PyObject *a_lnotab; /* string containing lnotab */
3658 int a_lnotab_off; /* offset into lnotab */
3659 int a_lineno; /* last lineno of emitted instruction */
3660 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003661};
3662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663static void
3664dfs(struct compiler *c, basicblock *b, struct assembler *a)
3665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 int i;
3667 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 if (b->b_seen)
3670 return;
3671 b->b_seen = 1;
3672 if (b->b_next != NULL)
3673 dfs(c, b->b_next, a);
3674 for (i = 0; i < b->b_iused; i++) {
3675 instr = &b->b_instr[i];
3676 if (instr->i_jrel || instr->i_jabs)
3677 dfs(c, instr->i_target, a);
3678 }
3679 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680}
3681
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003682static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 int i, target_depth;
3686 struct instr *instr;
3687 if (b->b_seen || b->b_startdepth >= depth)
3688 return maxdepth;
3689 b->b_seen = 1;
3690 b->b_startdepth = depth;
3691 for (i = 0; i < b->b_iused; i++) {
3692 instr = &b->b_instr[i];
3693 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3694 if (depth > maxdepth)
3695 maxdepth = depth;
3696 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3697 if (instr->i_jrel || instr->i_jabs) {
3698 target_depth = depth;
3699 if (instr->i_opcode == FOR_ITER) {
3700 target_depth = depth-2;
3701 } else if (instr->i_opcode == SETUP_FINALLY ||
3702 instr->i_opcode == SETUP_EXCEPT) {
3703 target_depth = depth+3;
3704 if (target_depth > maxdepth)
3705 maxdepth = target_depth;
3706 }
3707 maxdepth = stackdepth_walk(c, instr->i_target,
3708 target_depth, maxdepth);
3709 if (instr->i_opcode == JUMP_ABSOLUTE ||
3710 instr->i_opcode == JUMP_FORWARD) {
3711 goto out; /* remaining code is dead */
3712 }
3713 }
3714 }
3715 if (b->b_next)
3716 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 b->b_seen = 0;
3719 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720}
3721
3722/* Find the flow path that needs the largest stack. We assume that
3723 * cycles in the flow graph have no net effect on the stack depth.
3724 */
3725static int
3726stackdepth(struct compiler *c)
3727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 basicblock *b, *entryblock;
3729 entryblock = NULL;
3730 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3731 b->b_seen = 0;
3732 b->b_startdepth = INT_MIN;
3733 entryblock = b;
3734 }
3735 if (!entryblock)
3736 return 0;
3737 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738}
3739
3740static int
3741assemble_init(struct assembler *a, int nblocks, int firstlineno)
3742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 memset(a, 0, sizeof(struct assembler));
3744 a->a_lineno = firstlineno;
3745 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3746 if (!a->a_bytecode)
3747 return 0;
3748 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3749 if (!a->a_lnotab)
3750 return 0;
3751 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3752 PyErr_NoMemory();
3753 return 0;
3754 }
3755 a->a_postorder = (basicblock **)PyObject_Malloc(
3756 sizeof(basicblock *) * nblocks);
3757 if (!a->a_postorder) {
3758 PyErr_NoMemory();
3759 return 0;
3760 }
3761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762}
3763
3764static void
3765assemble_free(struct assembler *a)
3766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 Py_XDECREF(a->a_bytecode);
3768 Py_XDECREF(a->a_lnotab);
3769 if (a->a_postorder)
3770 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771}
3772
3773/* Return the size of a basic block in bytes. */
3774
3775static int
3776instrsize(struct instr *instr)
3777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 if (!instr->i_hasarg)
3779 return 1; /* 1 byte for the opcode*/
3780 if (instr->i_oparg > 0xffff)
3781 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3782 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783}
3784
3785static int
3786blocksize(basicblock *b)
3787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 int i;
3789 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 for (i = 0; i < b->b_iused; i++)
3792 size += instrsize(&b->b_instr[i]);
3793 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794}
3795
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003796/* Appends a pair to the end of the line number table, a_lnotab, representing
3797 the instruction's bytecode offset and line number. See
3798 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003799
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003800static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 int d_bytecode, d_lineno;
3804 int len;
3805 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 d_bytecode = a->a_offset - a->a_lineno_off;
3808 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 assert(d_bytecode >= 0);
3811 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 if(d_bytecode == 0 && d_lineno == 0)
3814 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 if (d_bytecode > 255) {
3817 int j, nbytes, ncodes = d_bytecode / 255;
3818 nbytes = a->a_lnotab_off + 2 * ncodes;
3819 len = PyBytes_GET_SIZE(a->a_lnotab);
3820 if (nbytes >= len) {
3821 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3822 len = nbytes;
3823 else if (len <= INT_MAX / 2)
3824 len *= 2;
3825 else {
3826 PyErr_NoMemory();
3827 return 0;
3828 }
3829 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3830 return 0;
3831 }
3832 lnotab = (unsigned char *)
3833 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3834 for (j = 0; j < ncodes; j++) {
3835 *lnotab++ = 255;
3836 *lnotab++ = 0;
3837 }
3838 d_bytecode -= ncodes * 255;
3839 a->a_lnotab_off += ncodes * 2;
3840 }
3841 assert(d_bytecode <= 255);
3842 if (d_lineno > 255) {
3843 int j, nbytes, ncodes = d_lineno / 255;
3844 nbytes = a->a_lnotab_off + 2 * ncodes;
3845 len = PyBytes_GET_SIZE(a->a_lnotab);
3846 if (nbytes >= len) {
3847 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3848 len = nbytes;
3849 else if (len <= INT_MAX / 2)
3850 len *= 2;
3851 else {
3852 PyErr_NoMemory();
3853 return 0;
3854 }
3855 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3856 return 0;
3857 }
3858 lnotab = (unsigned char *)
3859 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3860 *lnotab++ = d_bytecode;
3861 *lnotab++ = 255;
3862 d_bytecode = 0;
3863 for (j = 1; j < ncodes; j++) {
3864 *lnotab++ = 0;
3865 *lnotab++ = 255;
3866 }
3867 d_lineno -= ncodes * 255;
3868 a->a_lnotab_off += ncodes * 2;
3869 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 len = PyBytes_GET_SIZE(a->a_lnotab);
3872 if (a->a_lnotab_off + 2 >= len) {
3873 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3874 return 0;
3875 }
3876 lnotab = (unsigned char *)
3877 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 a->a_lnotab_off += 2;
3880 if (d_bytecode) {
3881 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003882 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 }
3884 else { /* First line of a block; def stmt, etc. */
3885 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003886 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 }
3888 a->a_lineno = i->i_lineno;
3889 a->a_lineno_off = a->a_offset;
3890 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003891}
3892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893/* assemble_emit()
3894 Extend the bytecode with a new instruction.
3895 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003896*/
3897
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003898static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 int size, arg = 0, ext = 0;
3902 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3903 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 size = instrsize(i);
3906 if (i->i_hasarg) {
3907 arg = i->i_oparg;
3908 ext = arg >> 16;
3909 }
3910 if (i->i_lineno && !assemble_lnotab(a, i))
3911 return 0;
3912 if (a->a_offset + size >= len) {
3913 if (len > PY_SSIZE_T_MAX / 2)
3914 return 0;
3915 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3916 return 0;
3917 }
3918 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3919 a->a_offset += size;
3920 if (size == 6) {
3921 assert(i->i_hasarg);
3922 *code++ = (char)EXTENDED_ARG;
3923 *code++ = ext & 0xff;
3924 *code++ = ext >> 8;
3925 arg &= 0xffff;
3926 }
3927 *code++ = i->i_opcode;
3928 if (i->i_hasarg) {
3929 assert(size == 3 || size == 6);
3930 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003931 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 }
3933 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003934}
3935
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003936static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003937assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 basicblock *b;
3940 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3941 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 /* Compute the size of each block and fixup jump args.
3944 Replace block pointer with position in bytecode. */
3945 do {
3946 totsize = 0;
3947 for (i = a->a_nblocks - 1; i >= 0; i--) {
3948 b = a->a_postorder[i];
3949 bsize = blocksize(b);
3950 b->b_offset = totsize;
3951 totsize += bsize;
3952 }
3953 last_extended_arg_count = extended_arg_count;
3954 extended_arg_count = 0;
3955 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3956 bsize = b->b_offset;
3957 for (i = 0; i < b->b_iused; i++) {
3958 struct instr *instr = &b->b_instr[i];
3959 /* Relative jumps are computed relative to
3960 the instruction pointer after fetching
3961 the jump instruction.
3962 */
3963 bsize += instrsize(instr);
3964 if (instr->i_jabs)
3965 instr->i_oparg = instr->i_target->b_offset;
3966 else if (instr->i_jrel) {
3967 int delta = instr->i_target->b_offset - bsize;
3968 instr->i_oparg = delta;
3969 }
3970 else
3971 continue;
3972 if (instr->i_oparg > 0xffff)
3973 extended_arg_count++;
3974 }
3975 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 /* XXX: This is an awful hack that could hurt performance, but
3978 on the bright side it should work until we come up
3979 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 The issue is that in the first loop blocksize() is called
3982 which calls instrsize() which requires i_oparg be set
3983 appropriately. There is a bootstrap problem because
3984 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 So we loop until we stop seeing new EXTENDED_ARGs.
3987 The only EXTENDED_ARGs that could be popping up are
3988 ones in jump instructions. So this should converge
3989 fairly quickly.
3990 */
3991 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003992}
3993
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003994static PyObject *
3995dict_keys_inorder(PyObject *dict, int offset)
3996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 PyObject *tuple, *k, *v;
3998 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 tuple = PyTuple_New(size);
4001 if (tuple == NULL)
4002 return NULL;
4003 while (PyDict_Next(dict, &pos, &k, &v)) {
4004 i = PyLong_AS_LONG(v);
4005 /* The keys of the dictionary are tuples. (see compiler_add_o)
4006 The object we want is always first, though. */
4007 k = PyTuple_GET_ITEM(k, 0);
4008 Py_INCREF(k);
4009 assert((i - offset) < size);
4010 assert((i - offset) >= 0);
4011 PyTuple_SET_ITEM(tuple, i - offset, k);
4012 }
4013 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004014}
4015
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004016static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 PySTEntryObject *ste = c->u->u_ste;
4020 int flags = 0, n;
4021 if (ste->ste_type != ModuleBlock)
4022 flags |= CO_NEWLOCALS;
4023 if (ste->ste_type == FunctionBlock) {
4024 if (!ste->ste_unoptimized)
4025 flags |= CO_OPTIMIZED;
4026 if (ste->ste_nested)
4027 flags |= CO_NESTED;
4028 if (ste->ste_generator)
4029 flags |= CO_GENERATOR;
4030 if (ste->ste_varargs)
4031 flags |= CO_VARARGS;
4032 if (ste->ste_varkeywords)
4033 flags |= CO_VARKEYWORDS;
4034 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 /* (Only) inherit compilerflags in PyCF_MASK */
4037 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 n = PyDict_Size(c->u->u_freevars);
4040 if (n < 0)
4041 return -1;
4042 if (n == 0) {
4043 n = PyDict_Size(c->u->u_cellvars);
4044 if (n < 0)
4045 return -1;
4046 if (n == 0) {
4047 flags |= CO_NOFREE;
4048 }
4049 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004052}
4053
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004054static PyCodeObject *
4055makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 PyObject *tmp;
4058 PyCodeObject *co = NULL;
4059 PyObject *consts = NULL;
4060 PyObject *names = NULL;
4061 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 PyObject *name = NULL;
4063 PyObject *freevars = NULL;
4064 PyObject *cellvars = NULL;
4065 PyObject *bytecode = NULL;
4066 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 tmp = dict_keys_inorder(c->u->u_consts, 0);
4069 if (!tmp)
4070 goto error;
4071 consts = PySequence_List(tmp); /* optimize_code requires a list */
4072 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 names = dict_keys_inorder(c->u->u_names, 0);
4075 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4076 if (!consts || !names || !varnames)
4077 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4080 if (!cellvars)
4081 goto error;
4082 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4083 if (!freevars)
4084 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 nlocals = PyDict_Size(c->u->u_varnames);
4086 flags = compute_code_flags(c);
4087 if (flags < 0)
4088 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4091 if (!bytecode)
4092 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4095 if (!tmp)
4096 goto error;
4097 Py_DECREF(consts);
4098 consts = tmp;
4099
4100 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4101 nlocals, stackdepth(c), flags,
4102 bytecode, consts, names, varnames,
4103 freevars, cellvars,
Benjamin Peterson43b06862011-05-27 09:08:01 -05004104 c->c_filename_obj, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 c->u->u_firstlineno,
4106 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004107 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 Py_XDECREF(consts);
4109 Py_XDECREF(names);
4110 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 Py_XDECREF(name);
4112 Py_XDECREF(freevars);
4113 Py_XDECREF(cellvars);
4114 Py_XDECREF(bytecode);
4115 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004116}
4117
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004118
4119/* For debugging purposes only */
4120#if 0
4121static void
4122dump_instr(const struct instr *i)
4123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 const char *jrel = i->i_jrel ? "jrel " : "";
4125 const char *jabs = i->i_jabs ? "jabs " : "";
4126 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 *arg = '\0';
4129 if (i->i_hasarg)
4130 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4133 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004134}
4135
4136static void
4137dump_basicblock(const basicblock *b)
4138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 const char *seen = b->b_seen ? "seen " : "";
4140 const char *b_return = b->b_return ? "return " : "";
4141 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4142 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4143 if (b->b_instr) {
4144 int i;
4145 for (i = 0; i < b->b_iused; i++) {
4146 fprintf(stderr, " [%02d] ", i);
4147 dump_instr(b->b_instr + i);
4148 }
4149 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004150}
4151#endif
4152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153static PyCodeObject *
4154assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 basicblock *b, *entryblock;
4157 struct assembler a;
4158 int i, j, nblocks;
4159 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 /* Make sure every block that falls off the end returns None.
4162 XXX NEXT_BLOCK() isn't quite right, because if the last
4163 block ends with a jump or return b_next shouldn't set.
4164 */
4165 if (!c->u->u_curblock->b_return) {
4166 NEXT_BLOCK(c);
4167 if (addNone)
4168 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4169 ADDOP(c, RETURN_VALUE);
4170 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 nblocks = 0;
4173 entryblock = NULL;
4174 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4175 nblocks++;
4176 entryblock = b;
4177 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 /* Set firstlineno if it wasn't explicitly set. */
4180 if (!c->u->u_firstlineno) {
4181 if (entryblock && entryblock->b_instr)
4182 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4183 else
4184 c->u->u_firstlineno = 1;
4185 }
4186 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4187 goto error;
4188 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 /* Can't modify the bytecode after computing jump offsets. */
4191 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 /* Emit code in reverse postorder from dfs. */
4194 for (i = a.a_nblocks - 1; i >= 0; i--) {
4195 b = a.a_postorder[i];
4196 for (j = 0; j < b->b_iused; j++)
4197 if (!assemble_emit(&a, &b->b_instr[j]))
4198 goto error;
4199 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4202 goto error;
4203 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4204 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004207 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 assemble_free(&a);
4209 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004210}
Georg Brandl8334fd92010-12-04 10:26:46 +00004211
4212#undef PyAST_Compile
4213PyAPI_FUNC(PyCodeObject *)
4214PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4215 PyArena *arena)
4216{
4217 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4218}
4219
4220