blob: 1a12b42c9be2bc5f2b328a9e602e08917d7676f5 [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
Jeremy Hyltone9357b22006-03-01 15:47:05 +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
Guido van Rossumd8faa362007-04-27 19:54:29 +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"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Nick Coghlan650f0d02007-04-15 12:05:43 +000042#define COMP_GENEXP 0
43#define COMP_LISTCOMP 1
44#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000045#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
50 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000072 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000073 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
88enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
89
90struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000091 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092 basicblock *fb_block;
93};
94
95/* The following items change on entry and exit of code blocks.
96 They must be saved and restored when returning to a block.
97*/
98struct compiler_unit {
99 PySTEntryObject *u_ste;
100
101 PyObject *u_name;
102 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000103 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000104 the argument for opcodes that refer to those collections.
105 */
106 PyObject *u_consts; /* all constants */
107 PyObject *u_names; /* all names */
108 PyObject *u_varnames; /* local variables */
109 PyObject *u_cellvars; /* cell variables */
110 PyObject *u_freevars; /* free variables */
111
112 PyObject *u_private; /* for private name mangling */
113
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000114 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000115 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 /* Pointer to the most recently allocated block. By following b_list
117 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
122 int u_nfblocks;
123 struct fblockinfo u_fblock[CO_MAXBLOCKS];
124
125 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000126 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000127 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128 has been generated with current lineno */
129};
130
131/* This struct captures the global state of a compilation.
132
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133The u pointer points to the current compilation unit, while units
134for enclosing blocks are stored in c_stack. The u and c_stack are
135managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136*/
137
138struct compiler {
139 const char *c_filename;
140 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142 PyCompilerFlags *c_flags;
143
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 struct compiler_unit *u; /* compiler state for current block */
148 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151};
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153static int compiler_enter_scope(struct compiler *, identifier, void *, int);
154static void compiler_free(struct compiler *);
155static basicblock *compiler_new_block(struct compiler *);
156static int compiler_next_instr(struct compiler *, basicblock *);
157static int compiler_addop(struct compiler *, int);
158static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
159static int compiler_addop_i(struct compiler *, int, int);
160static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161static basicblock *compiler_use_new_block(struct compiler *);
162static int compiler_error(struct compiler *, const char *);
163static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
164
165static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
166static int compiler_visit_stmt(struct compiler *, stmt_ty);
167static int compiler_visit_keyword(struct compiler *, keyword_ty);
168static int compiler_visit_expr(struct compiler *, expr_ty);
169static int compiler_augassign(struct compiler *, stmt_ty);
170static int compiler_visit_slice(struct compiler *, slice_ty,
171 expr_context_ty);
172
173static int compiler_push_fblock(struct compiler *, enum fblocktype,
174 basicblock *);
175static void compiler_pop_fblock(struct compiler *, enum fblocktype,
176 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177/* Returns true if there is a loop on the fblock stack. */
178static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179
180static int inplace_binop(struct compiler *, operator_ty);
181static int expr_constant(expr_ty e);
182
Guido van Rossumc2e20742006-02-27 22:32:47 +0000183static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000184static int compiler_call_helper(struct compiler *c, int n,
185 asdl_seq *args,
186 asdl_seq *keywords,
187 expr_ty starargs,
188 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static PyCodeObject *assemble(struct compiler *, int addNone);
191static PyObject *__doc__;
192
Benjamin Petersonb173f782009-05-05 22:31:58 +0000193#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000197{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198 /* Name mangling: __private becomes _classname__private.
199 This is independent from how the name is used. */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000200 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
201 Py_UNICODE *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 size_t nlen, plen;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000203 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000204 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000207 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000208 p = PyUnicode_AS_UNICODE(privateobj);
209 nlen = Py_UNICODE_strlen(name);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 /* Don't mangle __id__ or names with dots.
211
212 The only time a name with a dot can occur is when
213 we are compiling an import statement that has a
214 package name.
215
216 TODO(jhylton): Decide whether we want to support
217 mangling of the module name, e.g. __M.X.
218 */
219 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Martin v. Löwis5b222132007-06-10 09:51:05 +0000220 || Py_UNICODE_strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224 /* Strip leading underscores from class name */
225 while (*p == '_')
226 p++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000227 if (*p == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000231 plen = Py_UNICODE_strlen(p);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000232
233 assert(1 <= PY_SSIZE_T_MAX - nlen);
234 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
235
Martin v. Löwis5b222132007-06-10 09:51:05 +0000236 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000237 if (!ident)
238 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000240 buffer = PyUnicode_AS_UNICODE(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000241 buffer[0] = '_';
Martin v. Löwis5b222132007-06-10 09:51:05 +0000242 Py_UNICODE_strncpy(buffer+1, p, plen);
243 Py_UNICODE_strcpy(buffer+1+plen, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000245}
246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000247static int
248compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000249{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000251
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252 c->c_stack = PyList_New(0);
253 if (!c->c_stack)
254 return 0;
255
256 return 1;
257}
258
259PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000260PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000261 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000262{
263 struct compiler c;
264 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000265 PyCompilerFlags local_flags;
266 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000268 if (!__doc__) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000269 __doc__ = PyUnicode_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000270 if (!__doc__)
271 return NULL;
272 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273
274 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000275 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000276 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000277 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278 c.c_future = PyFuture_FromAST(mod, filename);
279 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000280 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000281 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000282 local_flags.cf_flags = 0;
283 flags = &local_flags;
284 }
285 merged = c.c_future->ff_features | flags->cf_flags;
286 c.c_future->ff_features = merged;
287 flags->cf_flags = merged;
288 c.c_flags = flags;
289 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
291 c.c_st = PySymtable_Build(mod, filename, c.c_future);
292 if (c.c_st == NULL) {
293 if (!PyErr_Occurred())
294 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000295 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 }
297
298 /* XXX initialize to NULL for now, need to handle */
299 c.c_encoding = NULL;
300
301 co = compiler_mod(&c, mod);
302
Thomas Wouters1175c432006-02-27 22:49:54 +0000303 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000305 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000306 return co;
307}
308
309PyCodeObject *
310PyNode_Compile(struct _node *n, const char *filename)
311{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000312 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000313 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000314 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000315 if (!arena)
316 return NULL;
317 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000318 if (mod)
319 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000320 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000321 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000322}
323
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000324static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000326{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327 if (c->c_st)
328 PySymtable_Free(c->c_st);
329 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000330 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000332}
333
Guido van Rossum79f25d91997-04-29 20:08:16 +0000334static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000335list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000336{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000337 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338 PyObject *v, *k;
339 PyObject *dict = PyDict_New();
340 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000341
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 n = PyList_Size(list);
343 for (i = 0; i < n; i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000344 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 if (!v) {
346 Py_DECREF(dict);
347 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000348 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000349 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000350 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
352 Py_XDECREF(k);
353 Py_DECREF(v);
354 Py_DECREF(dict);
355 return NULL;
356 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000357 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000359 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360 return dict;
361}
362
363/* Return new dict containing names from src that match scope(s).
364
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000365src is a symbol table dictionary. If the scope of a name matches
366either scope_type or flag is set, insert it into the new dict. The
367values are integers, starting at offset and increasing by one for
368each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369*/
370
371static PyObject *
372dictbytype(PyObject *src, int scope_type, int flag, int offset)
373{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000374 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375 PyObject *k, *v, *dest = PyDict_New();
376
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 assert(offset >= 0);
378 if (dest == NULL)
379 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380
381 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000382 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000383 long vi;
Christian Heimes217cfd12007-12-02 14:31:20 +0000384 assert(PyLong_Check(v));
385 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000386 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000388 if (scope == scope_type || vi & flag) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000389 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000390 if (item == NULL) {
391 Py_DECREF(dest);
392 return NULL;
393 }
394 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000395 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000396 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
397 Py_DECREF(item);
398 Py_DECREF(dest);
399 Py_XDECREF(tuple);
400 return NULL;
401 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000403 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405 }
406 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000407}
408
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409static void
410compiler_unit_check(struct compiler_unit *u)
411{
412 basicblock *block;
413 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Christian Heimes77c02eb2008-02-09 02:18:51 +0000414 assert((void *)block != (void *)0xcbcbcbcb);
415 assert((void *)block != (void *)0xfbfbfbfb);
416 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417 if (block->b_instr != NULL) {
418 assert(block->b_ialloc > 0);
419 assert(block->b_iused > 0);
420 assert(block->b_ialloc >= block->b_iused);
421 }
422 else {
423 assert (block->b_iused == 0);
424 assert (block->b_ialloc == 0);
425 }
426 }
427}
428
429static void
430compiler_unit_free(struct compiler_unit *u)
431{
432 basicblock *b, *next;
433
434 compiler_unit_check(u);
435 b = u->u_blocks;
436 while (b != NULL) {
437 if (b->b_instr)
438 PyObject_Free((void *)b->b_instr);
439 next = b->b_list;
440 PyObject_Free((void *)b);
441 b = next;
442 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000443 Py_CLEAR(u->u_ste);
444 Py_CLEAR(u->u_name);
445 Py_CLEAR(u->u_consts);
446 Py_CLEAR(u->u_names);
447 Py_CLEAR(u->u_varnames);
448 Py_CLEAR(u->u_freevars);
449 Py_CLEAR(u->u_cellvars);
450 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451 PyObject_Free(u);
452}
453
454static int
455compiler_enter_scope(struct compiler *c, identifier name, void *key,
456 int lineno)
457{
458 struct compiler_unit *u;
459
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000460 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000461 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000462 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000463 PyErr_NoMemory();
464 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000465 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000466 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000468 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469 u->u_ste = PySymtable_Lookup(c->c_st, key);
470 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000471 compiler_unit_free(u);
472 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473 }
474 Py_INCREF(name);
475 u->u_name = name;
476 u->u_varnames = list2dict(u->u_ste->ste_varnames);
477 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000478 if (!u->u_varnames || !u->u_cellvars) {
479 compiler_unit_free(u);
480 return 0;
481 }
482
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000484 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485 if (!u->u_freevars) {
486 compiler_unit_free(u);
487 return 0;
488 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000489
490 u->u_blocks = NULL;
491 u->u_tmpname = 0;
492 u->u_nfblocks = 0;
493 u->u_firstlineno = lineno;
494 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000495 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496 u->u_consts = PyDict_New();
497 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499 return 0;
500 }
501 u->u_names = PyDict_New();
502 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000503 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504 return 0;
505 }
506
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000507 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000508
509 /* Push the old compiler_unit on the stack. */
510 if (c->u) {
Benjamin Petersonb173f782009-05-05 22:31:58 +0000511 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
512 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
513 Py_XDECREF(capsule);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000514 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515 return 0;
516 }
Benjamin Petersonb173f782009-05-05 22:31:58 +0000517 Py_DECREF(capsule);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000518 u->u_private = c->u->u_private;
519 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520 }
521 c->u = u;
522
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000523 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000524 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525 return 0;
526
527 return 1;
528}
529
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000530static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531compiler_exit_scope(struct compiler *c)
532{
533 int n;
Benjamin Petersonb173f782009-05-05 22:31:58 +0000534 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000536 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537 compiler_unit_free(c->u);
538 /* Restore c->u to the parent unit. */
539 n = PyList_GET_SIZE(c->c_stack) - 1;
540 if (n >= 0) {
Benjamin Petersonb173f782009-05-05 22:31:58 +0000541 capsule = PyList_GET_ITEM(c->c_stack, n);
542 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000543 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000544 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000546 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547 compiler_unit_check(c->u);
548 }
549 else
550 c->u = NULL;
551
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552}
553
Benjamin Peterson32123372009-06-28 22:36:18 +0000554/* Allocate a new "anonymous" local variable. Used by with statements. */
555
556static PyObject *
557compiler_new_tmpname(struct compiler *c)
558{
559 char tmpname[256];
560 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
561 return PyUnicode_FromString(tmpname);
562}
563
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564/* Allocate a new block and return a pointer to it.
565 Returns NULL on error.
566*/
567
568static basicblock *
569compiler_new_block(struct compiler *c)
570{
571 basicblock *b;
572 struct compiler_unit *u;
573
574 u = c->u;
575 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000576 if (b == NULL) {
577 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582 b->b_list = u->u_blocks;
583 u->u_blocks = b;
584 return b;
585}
586
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587static basicblock *
588compiler_use_new_block(struct compiler *c)
589{
590 basicblock *block = compiler_new_block(c);
591 if (block == NULL)
592 return NULL;
593 c->u->u_curblock = block;
594 return block;
595}
596
597static basicblock *
598compiler_next_block(struct compiler *c)
599{
600 basicblock *block = compiler_new_block(c);
601 if (block == NULL)
602 return NULL;
603 c->u->u_curblock->b_next = block;
604 c->u->u_curblock = block;
605 return block;
606}
607
608static basicblock *
609compiler_use_next_block(struct compiler *c, basicblock *block)
610{
611 assert(block != NULL);
612 c->u->u_curblock->b_next = block;
613 c->u->u_curblock = block;
614 return block;
615}
616
617/* Returns the offset of the next instruction in the current block's
618 b_instr array. Resizes the b_instr as necessary.
619 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000620*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
622static int
623compiler_next_instr(struct compiler *c, basicblock *b)
624{
625 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000626 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000628 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629 if (b->b_instr == NULL) {
630 PyErr_NoMemory();
631 return -1;
632 }
633 b->b_ialloc = DEFAULT_BLOCK_SIZE;
634 memset((char *)b->b_instr, 0,
635 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000636 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639 size_t oldsize, newsize;
640 oldsize = b->b_ialloc * sizeof(struct instr);
641 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000642
643 if (oldsize > (PY_SIZE_MAX >> 1)) {
644 PyErr_NoMemory();
645 return -1;
646 }
647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648 if (newsize == 0) {
649 PyErr_NoMemory();
650 return -1;
651 }
652 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655 if (tmp == NULL) {
656 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658 }
659 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
661 }
662 return b->b_iused++;
663}
664
Christian Heimes2202f872008-02-06 14:31:34 +0000665/* Set the i_lineno member of the instruction at offset off if the
666 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000667 already been set. If it has been set, the call has no effect.
668
Christian Heimes2202f872008-02-06 14:31:34 +0000669 The line number is reset in the following cases:
670 - when entering a new scope
671 - on each statement
672 - on each expression that start a new line
673 - before the "except" clause
674 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677static void
678compiler_set_lineno(struct compiler *c, int off)
679{
680 basicblock *b;
681 if (c->u->u_lineno_set)
682 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000683 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000685 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686}
687
688static int
689opcode_stack_effect(int opcode, int oparg)
690{
691 switch (opcode) {
692 case POP_TOP:
693 return -1;
694 case ROT_TWO:
695 case ROT_THREE:
696 return 0;
697 case DUP_TOP:
698 return 1;
699 case ROT_FOUR:
700 return 0;
701
702 case UNARY_POSITIVE:
703 case UNARY_NEGATIVE:
704 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705 case UNARY_INVERT:
706 return 0;
707
Nick Coghlan650f0d02007-04-15 12:05:43 +0000708 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000709 case LIST_APPEND:
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000710 return -1;
711 case MAP_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000712 return -2;
713
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714 case BINARY_POWER:
715 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716 case BINARY_MODULO:
717 case BINARY_ADD:
718 case BINARY_SUBTRACT:
719 case BINARY_SUBSCR:
720 case BINARY_FLOOR_DIVIDE:
721 case BINARY_TRUE_DIVIDE:
722 return -1;
723 case INPLACE_FLOOR_DIVIDE:
724 case INPLACE_TRUE_DIVIDE:
725 return -1;
726
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000727 case INPLACE_ADD:
728 case INPLACE_SUBTRACT:
729 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 case INPLACE_MODULO:
731 return -1;
732 case STORE_SUBSCR:
733 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000734 case STORE_MAP:
735 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736 case DELETE_SUBSCR:
737 return -2;
738
739 case BINARY_LSHIFT:
740 case BINARY_RSHIFT:
741 case BINARY_AND:
742 case BINARY_XOR:
743 case BINARY_OR:
744 return -1;
745 case INPLACE_POWER:
746 return -1;
747 case GET_ITER:
748 return 0;
749
750 case PRINT_EXPR:
751 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000752 case LOAD_BUILD_CLASS:
753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754 case INPLACE_LSHIFT:
755 case INPLACE_RSHIFT:
756 case INPLACE_AND:
757 case INPLACE_XOR:
758 case INPLACE_OR:
759 return -1;
760 case BREAK_LOOP:
761 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000762 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000763 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000764 case STORE_LOCALS:
765 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766 case RETURN_VALUE:
767 return -1;
768 case IMPORT_STAR:
769 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770 case YIELD_VALUE:
771 return 0;
772
773 case POP_BLOCK:
774 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000775 case POP_EXCEPT:
776 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777 case END_FINALLY:
778 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779
780 case STORE_NAME:
781 return -1;
782 case DELETE_NAME:
783 return 0;
784 case UNPACK_SEQUENCE:
785 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000786 case UNPACK_EX:
787 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788 case FOR_ITER:
789 return 1;
790
791 case STORE_ATTR:
792 return -2;
793 case DELETE_ATTR:
794 return -1;
795 case STORE_GLOBAL:
796 return -1;
797 case DELETE_GLOBAL:
798 return 0;
799 case DUP_TOPX:
800 return oparg;
801 case LOAD_CONST:
802 return 1;
803 case LOAD_NAME:
804 return 1;
805 case BUILD_TUPLE:
806 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000807 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808 return 1-oparg;
809 case BUILD_MAP:
810 return 1;
811 case LOAD_ATTR:
812 return 0;
813 case COMPARE_OP:
814 return -1;
815 case IMPORT_NAME:
816 return 0;
817 case IMPORT_FROM:
818 return 1;
819
820 case JUMP_FORWARD:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000821 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
822 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000823 case JUMP_ABSOLUTE:
824 return 0;
825
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000826 case POP_JUMP_IF_FALSE:
827 case POP_JUMP_IF_TRUE:
828 return -1;
829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830 case LOAD_GLOBAL:
831 return 1;
832
833 case CONTINUE_LOOP:
834 return 0;
835 case SETUP_LOOP:
836 return 0;
837 case SETUP_EXCEPT:
838 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000839 return 6; /* can push 3 values for the new exception
840 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
842 case LOAD_FAST:
843 return 1;
844 case STORE_FAST:
845 return -1;
846 case DELETE_FAST:
847 return 0;
848
849 case RAISE_VARARGS:
850 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000851#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852 case CALL_FUNCTION:
853 return -NARGS(oparg);
854 case CALL_FUNCTION_VAR:
855 case CALL_FUNCTION_KW:
856 return -NARGS(oparg)-1;
857 case CALL_FUNCTION_VAR_KW:
858 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000860 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000861 case MAKE_CLOSURE:
862 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000863#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864 case BUILD_SLICE:
865 if (oparg == 3)
866 return -2;
867 else
868 return -1;
869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870 case LOAD_CLOSURE:
871 return 1;
872 case LOAD_DEREF:
873 return 1;
874 case STORE_DEREF:
875 return -1;
876 default:
877 fprintf(stderr, "opcode = %d\n", opcode);
878 Py_FatalError("opcode_stack_effect()");
879
880 }
881 return 0; /* not reachable */
882}
883
884/* Add an opcode with no argument.
885 Returns 0 on failure, 1 on success.
886*/
887
888static int
889compiler_addop(struct compiler *c, int opcode)
890{
891 basicblock *b;
892 struct instr *i;
893 int off;
894 off = compiler_next_instr(c, c->u->u_curblock);
895 if (off < 0)
896 return 0;
897 b = c->u->u_curblock;
898 i = &b->b_instr[off];
899 i->i_opcode = opcode;
900 i->i_hasarg = 0;
901 if (opcode == RETURN_VALUE)
902 b->b_return = 1;
903 compiler_set_lineno(c, off);
904 return 1;
905}
906
907static int
908compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
909{
910 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000911 Py_ssize_t arg;
Mark Dickinsonb42dab52009-10-27 17:31:26 +0000912 unsigned char *p;
Christian Heimes400adb02008-02-01 08:12:03 +0000913 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000915 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000916 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
917 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000918 d = PyFloat_AS_DOUBLE(o);
919 p = (unsigned char*) &d;
920 /* all we need is to make the tuple different in either the 0.0
921 * or -0.0 case from all others, just to avoid the "coercion".
922 */
923 if (*p==0 && p[sizeof(double)-1]==0)
924 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
925 else
926 t = PyTuple_Pack(2, o, o->ob_type);
927 }
Mark Dickinsonb42dab52009-10-27 17:31:26 +0000928#ifndef WITHOUT_COMPLEX
Christian Heimes400adb02008-02-01 08:12:03 +0000929 else if (PyComplex_Check(o)) {
Mark Dickinsonb42dab52009-10-27 17:31:26 +0000930 Py_complex z;
931 int real_part_zero, imag_part_zero;
932 unsigned char *q;
Christian Heimes400adb02008-02-01 08:12:03 +0000933 /* complex case is even messier: we need to make complex(x,
934 0.) different from complex(x, -0.) and complex(0., y)
935 different from complex(-0., y), for any x and y. In
936 particular, all four complex zeros should be
937 distinguished.*/
938 z = PyComplex_AsCComplex(o);
939 p = (unsigned char*) &(z.real);
940 q = (unsigned char*) &(z.imag);
941 /* all that matters here is that on IEEE platforms
942 real_part_zero will be true if z.real == 0., and false if
943 z.real == -0. In fact, real_part_zero will also be true
944 for some other rarely occurring nonzero floats, but this
945 doesn't matter. Similar comments apply to
946 imag_part_zero. */
947 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
948 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
949 if (real_part_zero && imag_part_zero) {
950 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
951 }
952 else if (real_part_zero && !imag_part_zero) {
953 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
954 }
955 else if (!real_part_zero && imag_part_zero) {
956 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
957 }
958 else {
959 t = PyTuple_Pack(2, o, o->ob_type);
960 }
961 }
Mark Dickinsonb42dab52009-10-27 17:31:26 +0000962#endif /* WITHOUT_COMPLEX */
Christian Heimes400adb02008-02-01 08:12:03 +0000963 else {
964 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000965 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000966 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000967 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968
969 v = PyDict_GetItem(dict, t);
970 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000971 if (PyErr_Occurred())
972 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000973 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000974 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000975 if (!v) {
976 Py_DECREF(t);
977 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000978 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979 if (PyDict_SetItem(dict, t, v) < 0) {
980 Py_DECREF(t);
981 Py_DECREF(v);
982 return -1;
983 }
984 Py_DECREF(v);
985 }
986 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000987 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000989 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990}
991
992static int
993compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
994 PyObject *o)
995{
996 int arg = compiler_add_o(c, dict, o);
997 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999 return compiler_addop_i(c, opcode, arg);
1000}
1001
1002static int
1003compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005{
1006 int arg;
1007 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1008 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001009 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010 arg = compiler_add_o(c, dict, mangled);
1011 Py_DECREF(mangled);
1012 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001013 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001014 return compiler_addop_i(c, opcode, arg);
1015}
1016
1017/* Add an opcode with an integer argument.
1018 Returns 0 on failure, 1 on success.
1019*/
1020
1021static int
1022compiler_addop_i(struct compiler *c, int opcode, int oparg)
1023{
1024 struct instr *i;
1025 int off;
1026 off = compiler_next_instr(c, c->u->u_curblock);
1027 if (off < 0)
1028 return 0;
1029 i = &c->u->u_curblock->b_instr[off];
1030 i->i_opcode = opcode;
1031 i->i_oparg = oparg;
1032 i->i_hasarg = 1;
1033 compiler_set_lineno(c, off);
1034 return 1;
1035}
1036
1037static int
1038compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1039{
1040 struct instr *i;
1041 int off;
1042
1043 assert(b != NULL);
1044 off = compiler_next_instr(c, c->u->u_curblock);
1045 if (off < 0)
1046 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047 i = &c->u->u_curblock->b_instr[off];
1048 i->i_opcode = opcode;
1049 i->i_target = b;
1050 i->i_hasarg = 1;
1051 if (absolute)
1052 i->i_jabs = 1;
1053 else
1054 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001055 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056 return 1;
1057}
1058
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001059/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1060 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061 it as the current block. NEXT_BLOCK() also creates an implicit jump
1062 from the current block to the new block.
1063*/
1064
Thomas Wouters89f507f2006-12-13 04:49:30 +00001065/* The returns inside these macros make it impossible to decref objects
1066 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067*/
1068
1069
1070#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001071 if (compiler_use_new_block((C)) == NULL) \
1072 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
1075#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001076 if (compiler_next_block((C)) == NULL) \
1077 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078}
1079
1080#define ADDOP(C, OP) { \
1081 if (!compiler_addop((C), (OP))) \
1082 return 0; \
1083}
1084
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001085#define ADDOP_IN_SCOPE(C, OP) { \
1086 if (!compiler_addop((C), (OP))) { \
1087 compiler_exit_scope(c); \
1088 return 0; \
1089 } \
1090}
1091
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092#define ADDOP_O(C, OP, O, TYPE) { \
1093 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1094 return 0; \
1095}
1096
1097#define ADDOP_NAME(C, OP, O, TYPE) { \
1098 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1099 return 0; \
1100}
1101
1102#define ADDOP_I(C, OP, O) { \
1103 if (!compiler_addop_i((C), (OP), (O))) \
1104 return 0; \
1105}
1106
1107#define ADDOP_JABS(C, OP, O) { \
1108 if (!compiler_addop_j((C), (OP), (O), 1)) \
1109 return 0; \
1110}
1111
1112#define ADDOP_JREL(C, OP, O) { \
1113 if (!compiler_addop_j((C), (OP), (O), 0)) \
1114 return 0; \
1115}
1116
1117/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1118 the ASDL name to synthesize the name of the C type and the visit function.
1119*/
1120
1121#define VISIT(C, TYPE, V) {\
1122 if (!compiler_visit_ ## TYPE((C), (V))) \
1123 return 0; \
1124}
1125
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001126#define VISIT_IN_SCOPE(C, TYPE, V) {\
1127 if (!compiler_visit_ ## TYPE((C), (V))) { \
1128 compiler_exit_scope(c); \
1129 return 0; \
1130 } \
1131}
1132
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133#define VISIT_SLICE(C, V, CTX) {\
1134 if (!compiler_visit_slice((C), (V), (CTX))) \
1135 return 0; \
1136}
1137
1138#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001139 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001141 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001142 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143 if (!compiler_visit_ ## TYPE((C), elt)) \
1144 return 0; \
1145 } \
1146}
1147
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001148#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001149 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001150 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001151 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001152 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001153 if (!compiler_visit_ ## TYPE((C), elt)) { \
1154 compiler_exit_scope(c); \
1155 return 0; \
1156 } \
1157 } \
1158}
1159
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160static int
1161compiler_isdocstring(stmt_ty s)
1162{
1163 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 return s->v.Expr.value->kind == Str_kind;
1166}
1167
1168/* Compile a sequence of statements, checking for a docstring. */
1169
1170static int
1171compiler_body(struct compiler *c, asdl_seq *stmts)
1172{
1173 int i = 0;
1174 stmt_ty st;
1175
1176 if (!asdl_seq_LEN(stmts))
1177 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001178 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001179 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1180 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181 i = 1;
1182 VISIT(c, expr, st->v.Expr.value);
1183 if (!compiler_nameop(c, __doc__, Store))
1184 return 0;
1185 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001186 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001187 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188 return 1;
1189}
1190
1191static PyCodeObject *
1192compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001193{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001194 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001195 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 static PyObject *module;
1197 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001198 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 if (!module)
1200 return NULL;
1201 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001202 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1203 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001204 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 switch (mod->kind) {
1206 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001207 if (!compiler_body(c, mod->v.Module.body)) {
1208 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 break;
1212 case Interactive_kind:
1213 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001214 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216 break;
1217 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001218 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001219 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220 break;
1221 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001222 PyErr_SetString(PyExc_SystemError,
1223 "suite should not be possible");
1224 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001225 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001226 PyErr_Format(PyExc_SystemError,
1227 "module kind %d should not be possible",
1228 mod->kind);
1229 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001230 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231 co = assemble(c, addNone);
1232 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001233 return co;
1234}
1235
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236/* The test for LOCAL must come before the test for FREE in order to
1237 handle classes where name is both local and free. The local var is
1238 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001239*/
1240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241static int
1242get_ref_type(struct compiler *c, PyObject *name)
1243{
1244 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 if (scope == 0) {
1246 char buf[350];
1247 PyOS_snprintf(buf, sizeof(buf),
1248 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001249 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001250 PyBytes_AS_STRING(name),
1251 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001252 PyObject_REPR(c->u->u_ste->ste_id),
1253 c->c_filename,
1254 PyObject_REPR(c->u->u_ste->ste_symbols),
1255 PyObject_REPR(c->u->u_varnames),
1256 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001258 Py_FatalError(buf);
1259 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001260
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001261 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262}
1263
1264static int
1265compiler_lookup_arg(PyObject *dict, PyObject *name)
1266{
1267 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001270 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001272 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001274 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001275 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
1278static int
1279compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1280{
1281 int i, free = PyCode_GetNumFree(co);
1282 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001283 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1284 ADDOP_I(c, MAKE_FUNCTION, args);
1285 return 1;
1286 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287 for (i = 0; i < free; ++i) {
1288 /* Bypass com_addop_varname because it will generate
1289 LOAD_DEREF but LOAD_CLOSURE is needed.
1290 */
1291 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1292 int arg, reftype;
1293
1294 /* Special case: If a class contains a method with a
1295 free variable that has the same name as a method,
1296 the name will be considered free *and* local in the
1297 class. It should be handled by the closure, as
1298 well as by the normal name loookup logic.
1299 */
1300 reftype = get_ref_type(c, name);
1301 if (reftype == CELL)
1302 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1303 else /* (reftype == FREE) */
1304 arg = compiler_lookup_arg(c->u->u_freevars, name);
1305 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001306 fprintf(stderr,
1307 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 "freevars of %s: %s\n",
1309 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001310 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001312 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313 PyObject_REPR(co->co_freevars));
1314 Py_FatalError("compiler_make_closure()");
1315 }
1316 ADDOP_I(c, LOAD_CLOSURE, arg);
1317 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001318 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001320 ADDOP_I(c, MAKE_CLOSURE, args);
1321 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324static int
1325compiler_decorators(struct compiler *c, asdl_seq* decos)
1326{
1327 int i;
1328
1329 if (!decos)
1330 return 1;
1331
1332 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001333 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 }
1335 return 1;
1336}
1337
1338static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001339compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1340 asdl_seq *kw_defaults)
1341{
1342 int i, default_count = 0;
1343 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001344 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001345 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1346 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001347 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001348 if (!compiler_visit_expr(c, default_)) {
1349 return -1;
1350 }
1351 default_count++;
1352 }
1353 }
1354 return default_count;
1355}
1356
1357static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001358compiler_visit_argannotation(struct compiler *c, identifier id,
1359 expr_ty annotation, PyObject *names)
1360{
1361 if (annotation) {
1362 VISIT(c, expr, annotation);
1363 if (PyList_Append(names, id))
1364 return -1;
1365 }
1366 return 0;
1367}
1368
1369static int
1370compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1371 PyObject *names)
1372{
1373 int i, error;
1374 for (i = 0; i < asdl_seq_LEN(args); i++) {
1375 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001376 error = compiler_visit_argannotation(
1377 c,
1378 arg->arg,
1379 arg->annotation,
1380 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001381 if (error)
1382 return error;
1383 }
1384 return 0;
1385}
1386
1387static int
1388compiler_visit_annotations(struct compiler *c, arguments_ty args,
1389 expr_ty returns)
1390{
Guido van Rossum0240b922007-02-26 21:23:50 +00001391 /* Push arg annotations and a list of the argument names. Return the #
1392 of items pushed. The expressions are evaluated out-of-order wrt the
1393 source code.
1394
1395 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1396 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001397 static identifier return_str;
1398 PyObject *names;
1399 int len;
1400 names = PyList_New(0);
1401 if (!names)
1402 return -1;
1403
1404 if (compiler_visit_argannotations(c, args->args, names))
1405 goto error;
1406 if (args->varargannotation &&
1407 compiler_visit_argannotation(c, args->vararg,
1408 args->varargannotation, names))
1409 goto error;
1410 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1411 goto error;
1412 if (args->kwargannotation &&
1413 compiler_visit_argannotation(c, args->kwarg,
1414 args->kwargannotation, names))
1415 goto error;
1416
1417 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001418 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001419 if (!return_str)
1420 goto error;
1421 }
1422 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1423 goto error;
1424 }
1425
1426 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001427 if (len > 65534) {
1428 /* len must fit in 16 bits, and len is incremented below */
1429 PyErr_SetString(PyExc_SyntaxError,
1430 "too many annotations");
1431 goto error;
1432 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001433 if (len) {
1434 /* convert names to a tuple and place on stack */
1435 PyObject *elt;
1436 int i;
1437 PyObject *s = PyTuple_New(len);
1438 if (!s)
1439 goto error;
1440 for (i = 0; i < len; i++) {
1441 elt = PyList_GET_ITEM(names, i);
1442 Py_INCREF(elt);
1443 PyTuple_SET_ITEM(s, i, elt);
1444 }
1445 ADDOP_O(c, LOAD_CONST, s, consts);
1446 Py_DECREF(s);
1447 len++; /* include the just-pushed tuple */
1448 }
1449 Py_DECREF(names);
1450 return len;
1451
1452error:
1453 Py_DECREF(names);
1454 return -1;
1455}
1456
1457static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458compiler_function(struct compiler *c, stmt_ty s)
1459{
1460 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001461 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001463 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001464 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001465 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001466 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001467 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468
1469 assert(s->kind == FunctionDef_kind);
1470
1471 if (!compiler_decorators(c, decos))
1472 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001473 if (args->kwonlyargs) {
1474 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1475 args->kw_defaults);
1476 if (res < 0)
1477 return 0;
1478 kw_default_count = res;
1479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480 if (args->defaults)
1481 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001482 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001483 if (num_annotations < 0)
1484 return 0;
1485 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001486
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1488 s->lineno))
1489 return 0;
1490
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001491 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001492 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001493 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001494 first_const = st->v.Expr.value->v.Str.s;
1495 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001496 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001497 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001501 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001503 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001505 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1506 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507 }
1508 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001509 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510 if (co == NULL)
1511 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512
Guido van Rossum4f72a782006-10-27 23:31:49 +00001513 arglength = asdl_seq_LEN(args->defaults);
1514 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001515 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001516 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001517 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518
Neal Norwitzc1505362006-12-28 06:47:50 +00001519 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1521 ADDOP_I(c, CALL_FUNCTION, 1);
1522 }
1523
1524 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1525}
1526
1527static int
1528compiler_class(struct compiler *c, stmt_ty s)
1529{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001531 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001532 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001533 asdl_seq* decos = s->v.ClassDef.decorator_list;
1534
1535 if (!compiler_decorators(c, decos))
1536 return 0;
1537
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001538 /* ultimately generate code for:
1539 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1540 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001541 <func> is a function/closure created from the class body;
1542 it has a single argument (__locals__) where the dict
1543 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001544 <name> is the class name
1545 <bases> is the positional arguments and *varargs argument
1546 <keywords> is the keyword arguments and **kwds argument
1547 This borrows from compiler_call.
1548 */
1549
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001550 /* 1. compile the class body into a code object */
1551 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1552 return 0;
1553 /* this block represents what we do in the new scope */
1554 {
1555 /* use the class name for name mangling */
1556 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001557 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001558 c->u->u_private = s->v.ClassDef.name;
1559 /* force it to have one mandatory argument */
1560 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001561 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001562 ADDOP_I(c, LOAD_FAST, 0);
1563 /* ... and store it into f_locals */
1564 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001565 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001566 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001567 if (!str || !compiler_nameop(c, str, Load)) {
1568 Py_XDECREF(str);
1569 compiler_exit_scope(c);
1570 return 0;
1571 }
1572 Py_DECREF(str);
1573 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001574 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001575 if (!str || !compiler_nameop(c, str, Store)) {
1576 Py_XDECREF(str);
1577 compiler_exit_scope(c);
1578 return 0;
1579 }
1580 Py_DECREF(str);
1581 /* compile the body proper */
1582 if (!compiler_body(c, s->v.ClassDef.body)) {
1583 compiler_exit_scope(c);
1584 return 0;
1585 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001586 /* return the (empty) __class__ cell */
1587 str = PyUnicode_InternFromString("__class__");
1588 if (str == NULL) {
1589 compiler_exit_scope(c);
1590 return 0;
1591 }
1592 i = compiler_lookup_arg(c->u->u_cellvars, str);
1593 Py_DECREF(str);
1594 if (i == -1) {
1595 /* This happens when nobody references the cell */
1596 PyErr_Clear();
1597 /* Return None */
1598 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1599 }
1600 else {
1601 /* Return the cell where to store __class__ */
1602 ADDOP_I(c, LOAD_CLOSURE, i);
1603 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001604 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1605 /* create the code object */
1606 co = assemble(c, 1);
1607 }
1608 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001609 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001610 if (co == NULL)
1611 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001612
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001613 /* 2. load the 'build_class' function */
1614 ADDOP(c, LOAD_BUILD_CLASS);
1615
1616 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001617 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001618 Py_DECREF(co);
1619
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001620 /* 4. load class name */
1621 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1622
1623 /* 5. generate the rest of the code for the call */
1624 if (!compiler_call_helper(c, 2,
1625 s->v.ClassDef.bases,
1626 s->v.ClassDef.keywords,
1627 s->v.ClassDef.starargs,
1628 s->v.ClassDef.kwargs))
1629 return 0;
1630
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001631 /* 6. apply decorators */
1632 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1633 ADDOP_I(c, CALL_FUNCTION, 1);
1634 }
1635
1636 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1638 return 0;
1639 return 1;
1640}
1641
1642static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001643compiler_ifexp(struct compiler *c, expr_ty e)
1644{
1645 basicblock *end, *next;
1646
1647 assert(e->kind == IfExp_kind);
1648 end = compiler_new_block(c);
1649 if (end == NULL)
1650 return 0;
1651 next = compiler_new_block(c);
1652 if (next == NULL)
1653 return 0;
1654 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001655 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001656 VISIT(c, expr, e->v.IfExp.body);
1657 ADDOP_JREL(c, JUMP_FORWARD, end);
1658 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001659 VISIT(c, expr, e->v.IfExp.orelse);
1660 compiler_use_next_block(c, end);
1661 return 1;
1662}
1663
1664static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001665compiler_lambda(struct compiler *c, expr_ty e)
1666{
1667 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001668 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001669 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670 arguments_ty args = e->v.Lambda.args;
1671 assert(e->kind == Lambda_kind);
1672
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001673 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001674 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001675 if (!name)
1676 return 0;
1677 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678
Guido van Rossum4f72a782006-10-27 23:31:49 +00001679 if (args->kwonlyargs) {
1680 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1681 args->kw_defaults);
1682 if (res < 0) return 0;
1683 kw_default_count = res;
1684 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001685 if (args->defaults)
1686 VISIT_SEQ(c, expr, args->defaults);
1687 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1688 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001689
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001691 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001692 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001693 if (c->u->u_ste->ste_generator) {
1694 ADDOP_IN_SCOPE(c, POP_TOP);
1695 }
1696 else {
1697 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1698 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001700 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701 if (co == NULL)
1702 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703
Guido van Rossum4f72a782006-10-27 23:31:49 +00001704 arglength = asdl_seq_LEN(args->defaults);
1705 arglength |= kw_default_count << 8;
1706 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001707 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708
1709 return 1;
1710}
1711
1712static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713compiler_if(struct compiler *c, stmt_ty s)
1714{
1715 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001716 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717 assert(s->kind == If_kind);
1718 end = compiler_new_block(c);
1719 if (end == NULL)
1720 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001721
1722 constant = expr_constant(s->v.If.test);
1723 /* constant = 0: "if 0"
1724 * constant = 1: "if 1", "if 2", ...
1725 * constant = -1: rest */
1726 if (constant == 0) {
1727 if (s->v.If.orelse)
1728 VISIT_SEQ(c, stmt, s->v.If.orelse);
1729 } else if (constant == 1) {
1730 VISIT_SEQ(c, stmt, s->v.If.body);
1731 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001732 if (s->v.If.orelse) {
1733 next = compiler_new_block(c);
1734 if (next == NULL)
1735 return 0;
1736 }
1737 else
1738 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001739 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001740 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001741 VISIT_SEQ(c, stmt, s->v.If.body);
1742 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001743 if (s->v.If.orelse) {
1744 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001745 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001746 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001747 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001748 compiler_use_next_block(c, end);
1749 return 1;
1750}
1751
1752static int
1753compiler_for(struct compiler *c, stmt_ty s)
1754{
1755 basicblock *start, *cleanup, *end;
1756
1757 start = compiler_new_block(c);
1758 cleanup = compiler_new_block(c);
1759 end = compiler_new_block(c);
1760 if (start == NULL || end == NULL || cleanup == NULL)
1761 return 0;
1762 ADDOP_JREL(c, SETUP_LOOP, end);
1763 if (!compiler_push_fblock(c, LOOP, start))
1764 return 0;
1765 VISIT(c, expr, s->v.For.iter);
1766 ADDOP(c, GET_ITER);
1767 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001768 /* for expressions must be traced on each iteration,
1769 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001770 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001771 ADDOP_JREL(c, FOR_ITER, cleanup);
1772 VISIT(c, expr, s->v.For.target);
1773 VISIT_SEQ(c, stmt, s->v.For.body);
1774 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1775 compiler_use_next_block(c, cleanup);
1776 ADDOP(c, POP_BLOCK);
1777 compiler_pop_fblock(c, LOOP, start);
1778 VISIT_SEQ(c, stmt, s->v.For.orelse);
1779 compiler_use_next_block(c, end);
1780 return 1;
1781}
1782
1783static int
1784compiler_while(struct compiler *c, stmt_ty s)
1785{
1786 basicblock *loop, *orelse, *end, *anchor = NULL;
1787 int constant = expr_constant(s->v.While.test);
1788
Christian Heimes969fe572008-01-25 11:23:10 +00001789 if (constant == 0) {
1790 if (s->v.While.orelse)
1791 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001793 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794 loop = compiler_new_block(c);
1795 end = compiler_new_block(c);
1796 if (constant == -1) {
1797 anchor = compiler_new_block(c);
1798 if (anchor == NULL)
1799 return 0;
1800 }
1801 if (loop == NULL || end == NULL)
1802 return 0;
1803 if (s->v.While.orelse) {
1804 orelse = compiler_new_block(c);
1805 if (orelse == NULL)
1806 return 0;
1807 }
1808 else
1809 orelse = NULL;
1810
1811 ADDOP_JREL(c, SETUP_LOOP, end);
1812 compiler_use_next_block(c, loop);
1813 if (!compiler_push_fblock(c, LOOP, loop))
1814 return 0;
1815 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001816 /* while expressions must be traced on each iteration,
1817 so we need to set an extra line number. */
1818 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001820 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821 }
1822 VISIT_SEQ(c, stmt, s->v.While.body);
1823 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1824
1825 /* XXX should the two POP instructions be in a separate block
1826 if there is no else clause ?
1827 */
1828
1829 if (constant == -1) {
1830 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 ADDOP(c, POP_BLOCK);
1832 }
1833 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001834 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001835 VISIT_SEQ(c, stmt, s->v.While.orelse);
1836 compiler_use_next_block(c, end);
1837
1838 return 1;
1839}
1840
1841static int
1842compiler_continue(struct compiler *c)
1843{
1844 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001845 static const char IN_FINALLY_ERROR_MSG[] =
1846 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 int i;
1848
1849 if (!c->u->u_nfblocks)
1850 return compiler_error(c, LOOP_ERROR_MSG);
1851 i = c->u->u_nfblocks - 1;
1852 switch (c->u->u_fblock[i].fb_type) {
1853 case LOOP:
1854 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1855 break;
1856 case EXCEPT:
1857 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001858 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1859 /* Prevent continue anywhere under a finally
1860 even if hidden in a sub-try or except. */
1861 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1862 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1863 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 if (i == -1)
1865 return compiler_error(c, LOOP_ERROR_MSG);
1866 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1867 break;
1868 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001869 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870 }
1871
1872 return 1;
1873}
1874
1875/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1876
1877 SETUP_FINALLY L
1878 <code for body>
1879 POP_BLOCK
1880 LOAD_CONST <None>
1881 L: <code for finalbody>
1882 END_FINALLY
1883
1884 The special instructions use the block stack. Each block
1885 stack entry contains the instruction that created it (here
1886 SETUP_FINALLY), the level of the value stack at the time the
1887 block stack entry was created, and a label (here L).
1888
1889 SETUP_FINALLY:
1890 Pushes the current value stack level and the label
1891 onto the block stack.
1892 POP_BLOCK:
1893 Pops en entry from the block stack, and pops the value
1894 stack until its level is the same as indicated on the
1895 block stack. (The label is ignored.)
1896 END_FINALLY:
1897 Pops a variable number of entries from the *value* stack
1898 and re-raises the exception they specify. The number of
1899 entries popped depends on the (pseudo) exception type.
1900
1901 The block stack is unwound when an exception is raised:
1902 when a SETUP_FINALLY entry is found, the exception is pushed
1903 onto the value stack (and the exception condition is cleared),
1904 and the interpreter jumps to the label gotten from the block
1905 stack.
1906*/
1907
1908static int
1909compiler_try_finally(struct compiler *c, stmt_ty s)
1910{
1911 basicblock *body, *end;
1912 body = compiler_new_block(c);
1913 end = compiler_new_block(c);
1914 if (body == NULL || end == NULL)
1915 return 0;
1916
1917 ADDOP_JREL(c, SETUP_FINALLY, end);
1918 compiler_use_next_block(c, body);
1919 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1920 return 0;
1921 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1922 ADDOP(c, POP_BLOCK);
1923 compiler_pop_fblock(c, FINALLY_TRY, body);
1924
1925 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1926 compiler_use_next_block(c, end);
1927 if (!compiler_push_fblock(c, FINALLY_END, end))
1928 return 0;
1929 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1930 ADDOP(c, END_FINALLY);
1931 compiler_pop_fblock(c, FINALLY_END, end);
1932
1933 return 1;
1934}
1935
1936/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001937 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 (The contents of the value stack is shown in [], with the top
1939 at the right; 'tb' is trace-back info, 'val' the exception's
1940 associated value, and 'exc' the exception.)
1941
1942 Value stack Label Instruction Argument
1943 [] SETUP_EXCEPT L1
1944 [] <code for S>
1945 [] POP_BLOCK
1946 [] JUMP_FORWARD L0
1947
1948 [tb, val, exc] L1: DUP )
1949 [tb, val, exc, exc] <evaluate E1> )
1950 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001951 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952 [tb, val, exc] POP
1953 [tb, val] <assign to V1> (or POP if no V1)
1954 [tb] POP
1955 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001956 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001958 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 .............................etc.......................
1960
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001961 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962
1963 [] L0: <next statement>
1964
1965 Of course, parts are not generated if Vi or Ei is not present.
1966*/
1967static int
1968compiler_try_except(struct compiler *c, stmt_ty s)
1969{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001970 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971 int i, n;
1972
1973 body = compiler_new_block(c);
1974 except = compiler_new_block(c);
1975 orelse = compiler_new_block(c);
1976 end = compiler_new_block(c);
1977 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1978 return 0;
1979 ADDOP_JREL(c, SETUP_EXCEPT, except);
1980 compiler_use_next_block(c, body);
1981 if (!compiler_push_fblock(c, EXCEPT, body))
1982 return 0;
1983 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1984 ADDOP(c, POP_BLOCK);
1985 compiler_pop_fblock(c, EXCEPT, body);
1986 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1987 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1988 compiler_use_next_block(c, except);
1989 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001990 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001992 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001994 c->u->u_lineno_set = 0;
1995 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996 except = compiler_new_block(c);
1997 if (except == NULL)
1998 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001999 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002001 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002003 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 }
2005 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002006 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00002007 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002008
2009 cleanup_end = compiler_new_block(c);
2010 cleanup_body = compiler_new_block(c);
2011 if(!(cleanup_end || cleanup_body))
2012 return 0;
2013
Neal Norwitzad74aa82008-03-31 05:14:30 +00002014 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002015 ADDOP(c, POP_TOP);
2016
2017 /*
2018 try:
2019 # body
2020 except type as name:
2021 try:
2022 # body
2023 finally:
2024 name = None
2025 del name
2026 */
2027
2028 /* second try: */
2029 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2030 compiler_use_next_block(c, cleanup_body);
2031 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2032 return 0;
2033
2034 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002035 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002036 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002037 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002038 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2039
2040 /* finally: */
2041 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2042 compiler_use_next_block(c, cleanup_end);
2043 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2044 return 0;
2045
2046 /* name = None */
2047 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002048 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002049
Guido van Rossum16be03e2007-01-10 18:51:35 +00002050 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002051 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002052
2053 ADDOP(c, END_FINALLY);
2054 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 }
2056 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002057 basicblock *cleanup_body;
2058
2059 cleanup_body = compiler_new_block(c);
2060 if(!cleanup_body)
2061 return 0;
2062
2063 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002064 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002065 compiler_use_next_block(c, cleanup_body);
2066 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2067 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002068 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002069 ADDOP(c, POP_EXCEPT);
2070 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 ADDOP_JREL(c, JUMP_FORWARD, end);
2073 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 }
2075 ADDOP(c, END_FINALLY);
2076 compiler_use_next_block(c, orelse);
2077 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2078 compiler_use_next_block(c, end);
2079 return 1;
2080}
2081
2082static int
2083compiler_import_as(struct compiler *c, identifier name, identifier asname)
2084{
2085 /* The IMPORT_NAME opcode was already generated. This function
2086 merely needs to bind the result to a name.
2087
2088 If there is a dot in name, we need to split it and emit a
2089 LOAD_ATTR for each name.
2090 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002091 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2092 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 if (dot) {
2094 /* Consume the base module name to get the first attribute */
2095 src = dot + 1;
2096 while (dot) {
2097 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002098 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002099 dot = Py_UNICODE_strchr(src, '.');
2100 attr = PyUnicode_FromUnicode(src,
2101 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002102 if (!attr)
2103 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002105 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 src = dot + 1;
2107 }
2108 }
2109 return compiler_nameop(c, asname, Store);
2110}
2111
2112static int
2113compiler_import(struct compiler *c, stmt_ty s)
2114{
2115 /* The Import node stores a module name like a.b.c as a single
2116 string. This is convenient for all cases except
2117 import a.b.c as d
2118 where we need to parse that string to extract the individual
2119 module names.
2120 XXX Perhaps change the representation to make this case simpler?
2121 */
2122 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002125 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002127 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128
Christian Heimes217cfd12007-12-02 14:31:20 +00002129 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002130 if (level == NULL)
2131 return 0;
2132
2133 ADDOP_O(c, LOAD_CONST, level, consts);
2134 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2136 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2137
2138 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002139 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002140 if (!r)
2141 return r;
2142 }
2143 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002145 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2146 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002147 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002148 tmp = PyUnicode_FromUnicode(base,
2149 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150 r = compiler_nameop(c, tmp, Store);
2151 if (dot) {
2152 Py_DECREF(tmp);
2153 }
2154 if (!r)
2155 return r;
2156 }
2157 }
2158 return 1;
2159}
2160
2161static int
2162compiler_from_import(struct compiler *c, stmt_ty s)
2163{
2164 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165
2166 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002167 PyObject *level;
2168
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169 if (!names)
2170 return 0;
2171
Christian Heimes217cfd12007-12-02 14:31:20 +00002172 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002173 if (!level) {
2174 Py_DECREF(names);
2175 return 0;
2176 }
2177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 /* build up the names */
2179 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002180 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002181 Py_INCREF(alias->name);
2182 PyTuple_SET_ITEM(names, i, alias->name);
2183 }
2184
2185 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002186 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2187 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002188 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189 Py_DECREF(names);
2190 return compiler_error(c,
2191 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002192 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193
2194 }
2195 }
2196
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002197 ADDOP_O(c, LOAD_CONST, level, consts);
2198 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002200 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2202 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002203 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002204 identifier store_name;
2205
Martin v. Löwis5b222132007-06-10 09:51:05 +00002206 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002207 assert(n == 1);
2208 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002209 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210 }
2211
2212 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2213 store_name = alias->name;
2214 if (alias->asname)
2215 store_name = alias->asname;
2216
2217 if (!compiler_nameop(c, store_name, Store)) {
2218 Py_DECREF(names);
2219 return 0;
2220 }
2221 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002222 /* remove imported module */
2223 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224 return 1;
2225}
2226
2227static int
2228compiler_assert(struct compiler *c, stmt_ty s)
2229{
2230 static PyObject *assertion_error = NULL;
2231 basicblock *end;
2232
2233 if (Py_OptimizeFlag)
2234 return 1;
2235 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002236 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237 if (assertion_error == NULL)
2238 return 0;
2239 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002240 if (s->v.Assert.test->kind == Tuple_kind &&
2241 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2242 const char* msg =
2243 "assertion is always true, perhaps remove parentheses?";
2244 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2245 c->u->u_lineno, NULL, NULL) == -1)
2246 return 0;
2247 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248 VISIT(c, expr, s->v.Assert.test);
2249 end = compiler_new_block(c);
2250 if (end == NULL)
2251 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002252 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2254 if (s->v.Assert.msg) {
2255 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002256 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257 }
Collin Winter828f04a2007-08-31 00:04:24 +00002258 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002259 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 return 1;
2261}
2262
2263static int
2264compiler_visit_stmt(struct compiler *c, stmt_ty s)
2265{
2266 int i, n;
2267
Thomas Wouters89f507f2006-12-13 04:49:30 +00002268 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002270 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002271
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002273 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002275 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002277 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 if (c->u->u_ste->ste_type != FunctionBlock)
2279 return compiler_error(c, "'return' outside function");
2280 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281 VISIT(c, expr, s->v.Return.value);
2282 }
2283 else
2284 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2285 ADDOP(c, RETURN_VALUE);
2286 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002287 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 VISIT_SEQ(c, expr, s->v.Delete.targets)
2289 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002290 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 n = asdl_seq_LEN(s->v.Assign.targets);
2292 VISIT(c, expr, s->v.Assign.value);
2293 for (i = 0; i < n; i++) {
2294 if (i < n - 1)
2295 ADDOP(c, DUP_TOP);
2296 VISIT(c, expr,
2297 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2298 }
2299 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002300 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002302 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002304 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002306 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002308 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002310 if (s->v.Raise.exc) {
2311 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002313 if (s->v.Raise.cause) {
2314 VISIT(c, expr, s->v.Raise.cause);
2315 n++;
2316 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317 }
2318 ADDOP_I(c, RAISE_VARARGS, n);
2319 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002320 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002322 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002324 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002326 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002328 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002330 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002331 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002333 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002335 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336 ADDOP(c, PRINT_EXPR);
2337 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002338 else if (s->v.Expr.value->kind != Str_kind &&
2339 s->v.Expr.value->kind != Num_kind) {
2340 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 ADDOP(c, POP_TOP);
2342 }
2343 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002344 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002346 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002347 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348 return compiler_error(c, "'break' outside loop");
2349 ADDOP(c, BREAK_LOOP);
2350 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002351 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002353 case With_kind:
2354 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 }
2356 return 1;
2357}
2358
2359static int
2360unaryop(unaryop_ty op)
2361{
2362 switch (op) {
2363 case Invert:
2364 return UNARY_INVERT;
2365 case Not:
2366 return UNARY_NOT;
2367 case UAdd:
2368 return UNARY_POSITIVE;
2369 case USub:
2370 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002371 default:
2372 PyErr_Format(PyExc_SystemError,
2373 "unary op %d should not be possible", op);
2374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376}
2377
2378static int
2379binop(struct compiler *c, operator_ty op)
2380{
2381 switch (op) {
2382 case Add:
2383 return BINARY_ADD;
2384 case Sub:
2385 return BINARY_SUBTRACT;
2386 case Mult:
2387 return BINARY_MULTIPLY;
2388 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002389 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390 case Mod:
2391 return BINARY_MODULO;
2392 case Pow:
2393 return BINARY_POWER;
2394 case LShift:
2395 return BINARY_LSHIFT;
2396 case RShift:
2397 return BINARY_RSHIFT;
2398 case BitOr:
2399 return BINARY_OR;
2400 case BitXor:
2401 return BINARY_XOR;
2402 case BitAnd:
2403 return BINARY_AND;
2404 case FloorDiv:
2405 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002406 default:
2407 PyErr_Format(PyExc_SystemError,
2408 "binary op %d should not be possible", op);
2409 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411}
2412
2413static int
2414cmpop(cmpop_ty op)
2415{
2416 switch (op) {
2417 case Eq:
2418 return PyCmp_EQ;
2419 case NotEq:
2420 return PyCmp_NE;
2421 case Lt:
2422 return PyCmp_LT;
2423 case LtE:
2424 return PyCmp_LE;
2425 case Gt:
2426 return PyCmp_GT;
2427 case GtE:
2428 return PyCmp_GE;
2429 case Is:
2430 return PyCmp_IS;
2431 case IsNot:
2432 return PyCmp_IS_NOT;
2433 case In:
2434 return PyCmp_IN;
2435 case NotIn:
2436 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002437 default:
2438 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440}
2441
2442static int
2443inplace_binop(struct compiler *c, operator_ty op)
2444{
2445 switch (op) {
2446 case Add:
2447 return INPLACE_ADD;
2448 case Sub:
2449 return INPLACE_SUBTRACT;
2450 case Mult:
2451 return INPLACE_MULTIPLY;
2452 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002453 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 case Mod:
2455 return INPLACE_MODULO;
2456 case Pow:
2457 return INPLACE_POWER;
2458 case LShift:
2459 return INPLACE_LSHIFT;
2460 case RShift:
2461 return INPLACE_RSHIFT;
2462 case BitOr:
2463 return INPLACE_OR;
2464 case BitXor:
2465 return INPLACE_XOR;
2466 case BitAnd:
2467 return INPLACE_AND;
2468 case FloorDiv:
2469 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002470 default:
2471 PyErr_Format(PyExc_SystemError,
2472 "inplace binary op %d should not be possible", op);
2473 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475}
2476
2477static int
2478compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2479{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002480 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2482
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002483 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002484 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 /* XXX AugStore isn't used anywhere! */
2486
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002487 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002488 if (!mangled)
2489 return 0;
2490
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 op = 0;
2492 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002493 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494 switch (scope) {
2495 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002496 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497 optype = OP_DEREF;
2498 break;
2499 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002500 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 optype = OP_DEREF;
2502 break;
2503 case LOCAL:
2504 if (c->u->u_ste->ste_type == FunctionBlock)
2505 optype = OP_FAST;
2506 break;
2507 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002508 if (c->u->u_ste->ste_type == FunctionBlock &&
2509 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510 optype = OP_GLOBAL;
2511 break;
2512 case GLOBAL_EXPLICIT:
2513 optype = OP_GLOBAL;
2514 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002515 default:
2516 /* scope can be 0 */
2517 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518 }
2519
2520 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002521 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002522
2523 switch (optype) {
2524 case OP_DEREF:
2525 switch (ctx) {
2526 case Load: op = LOAD_DEREF; break;
2527 case Store: op = STORE_DEREF; break;
2528 case AugLoad:
2529 case AugStore:
2530 break;
2531 case Del:
2532 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002533 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002535 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002536 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002539 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002540 PyErr_SetString(PyExc_SystemError,
2541 "param invalid for deref variable");
2542 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 }
2544 break;
2545 case OP_FAST:
2546 switch (ctx) {
2547 case Load: op = LOAD_FAST; break;
2548 case Store: op = STORE_FAST; break;
2549 case Del: op = DELETE_FAST; break;
2550 case AugLoad:
2551 case AugStore:
2552 break;
2553 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002554 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002555 PyErr_SetString(PyExc_SystemError,
2556 "param invalid for local variable");
2557 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002559 ADDOP_O(c, op, mangled, varnames);
2560 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561 return 1;
2562 case OP_GLOBAL:
2563 switch (ctx) {
2564 case Load: op = LOAD_GLOBAL; break;
2565 case Store: op = STORE_GLOBAL; break;
2566 case Del: op = DELETE_GLOBAL; break;
2567 case AugLoad:
2568 case AugStore:
2569 break;
2570 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002571 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002572 PyErr_SetString(PyExc_SystemError,
2573 "param invalid for global variable");
2574 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575 }
2576 break;
2577 case OP_NAME:
2578 switch (ctx) {
2579 case Load: op = LOAD_NAME; break;
2580 case Store: op = STORE_NAME; break;
2581 case Del: op = DELETE_NAME; break;
2582 case AugLoad:
2583 case AugStore:
2584 break;
2585 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002586 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002587 PyErr_SetString(PyExc_SystemError,
2588 "param invalid for name variable");
2589 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590 }
2591 break;
2592 }
2593
2594 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002595 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002596 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002597 if (arg < 0)
2598 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002599 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600}
2601
2602static int
2603compiler_boolop(struct compiler *c, expr_ty e)
2604{
2605 basicblock *end;
2606 int jumpi, i, n;
2607 asdl_seq *s;
2608
2609 assert(e->kind == BoolOp_kind);
2610 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002611 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002613 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002615 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 return 0;
2617 s = e->v.BoolOp.values;
2618 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002619 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002621 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002622 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002624 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 compiler_use_next_block(c, end);
2626 return 1;
2627}
2628
2629static int
2630compiler_list(struct compiler *c, expr_ty e)
2631{
2632 int n = asdl_seq_LEN(e->v.List.elts);
2633 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002634 int i, seen_star = 0;
2635 for (i = 0; i < n; i++) {
2636 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2637 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002638 if ((i >= (1 << 8)) ||
2639 (n-i-1 >= (INT_MAX >> 8)))
2640 return compiler_error(c,
2641 "too many expressions in "
2642 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002643 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2644 seen_star = 1;
2645 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2646 } else if (elt->kind == Starred_kind) {
2647 return compiler_error(c,
2648 "two starred expressions in assignment");
2649 }
2650 }
2651 if (!seen_star) {
2652 ADDOP_I(c, UNPACK_SEQUENCE, n);
2653 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 }
2655 VISIT_SEQ(c, expr, e->v.List.elts);
2656 if (e->v.List.ctx == Load) {
2657 ADDOP_I(c, BUILD_LIST, n);
2658 }
2659 return 1;
2660}
2661
2662static int
2663compiler_tuple(struct compiler *c, expr_ty e)
2664{
2665 int n = asdl_seq_LEN(e->v.Tuple.elts);
2666 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002667 int i, seen_star = 0;
2668 for (i = 0; i < n; i++) {
2669 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2670 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002671 if ((i >= (1 << 8)) ||
2672 (n-i-1 >= (INT_MAX >> 8)))
2673 return compiler_error(c,
2674 "too many expressions in "
2675 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002676 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2677 seen_star = 1;
2678 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2679 } else if (elt->kind == Starred_kind) {
2680 return compiler_error(c,
2681 "two starred expressions in assignment");
2682 }
2683 }
2684 if (!seen_star) {
2685 ADDOP_I(c, UNPACK_SEQUENCE, n);
2686 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687 }
2688 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2689 if (e->v.Tuple.ctx == Load) {
2690 ADDOP_I(c, BUILD_TUPLE, n);
2691 }
2692 return 1;
2693}
2694
2695static int
2696compiler_compare(struct compiler *c, expr_ty e)
2697{
2698 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002699 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700
2701 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2702 VISIT(c, expr, e->v.Compare.left);
2703 n = asdl_seq_LEN(e->v.Compare.ops);
2704 assert(n > 0);
2705 if (n > 1) {
2706 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002707 if (cleanup == NULL)
2708 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002709 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002710 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 }
2712 for (i = 1; i < n; i++) {
2713 ADDOP(c, DUP_TOP);
2714 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002716 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002717 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002718 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002721 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002722 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002724 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002725 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002726 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727 if (n > 1) {
2728 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002729 if (end == NULL)
2730 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731 ADDOP_JREL(c, JUMP_FORWARD, end);
2732 compiler_use_next_block(c, cleanup);
2733 ADDOP(c, ROT_TWO);
2734 ADDOP(c, POP_TOP);
2735 compiler_use_next_block(c, end);
2736 }
2737 return 1;
2738}
2739
2740static int
2741compiler_call(struct compiler *c, expr_ty e)
2742{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002744 return compiler_call_helper(c, 0,
2745 e->v.Call.args,
2746 e->v.Call.keywords,
2747 e->v.Call.starargs,
2748 e->v.Call.kwargs);
2749}
2750
2751/* shared code between compiler_call and compiler_class */
2752static int
2753compiler_call_helper(struct compiler *c,
2754 int n, /* Args already pushed */
2755 asdl_seq *args,
2756 asdl_seq *keywords,
2757 expr_ty starargs,
2758 expr_ty kwargs)
2759{
2760 int code = 0;
2761
2762 n += asdl_seq_LEN(args);
2763 VISIT_SEQ(c, expr, args);
2764 if (keywords) {
2765 VISIT_SEQ(c, keyword, keywords);
2766 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002768 if (starargs) {
2769 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770 code |= 1;
2771 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002772 if (kwargs) {
2773 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774 code |= 2;
2775 }
2776 switch (code) {
2777 case 0:
2778 ADDOP_I(c, CALL_FUNCTION, n);
2779 break;
2780 case 1:
2781 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2782 break;
2783 case 2:
2784 ADDOP_I(c, CALL_FUNCTION_KW, n);
2785 break;
2786 case 3:
2787 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2788 break;
2789 }
2790 return 1;
2791}
2792
Nick Coghlan650f0d02007-04-15 12:05:43 +00002793
2794/* List and set comprehensions and generator expressions work by creating a
2795 nested function to perform the actual iteration. This means that the
2796 iteration variables don't leak into the current scope.
2797 The defined function is called immediately following its definition, with the
2798 result of that call being the result of the expression.
2799 The LC/SC version returns the populated container, while the GE version is
2800 flagged in symtable.c as a generator, so it returns the generator object
2801 when the function is called.
2802 This code *knows* that the loop cannot contain break, continue, or return,
2803 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2804
2805 Possible cleanups:
2806 - iterate over the generator sequence instead of using recursion
2807*/
2808
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002810compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002811 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002812 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002813{
2814 /* generate code for the iterator, then each of the ifs,
2815 and then write to the element */
2816
Nick Coghlan650f0d02007-04-15 12:05:43 +00002817 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002819 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
2821 start = compiler_new_block(c);
2822 skip = compiler_new_block(c);
2823 if_cleanup = compiler_new_block(c);
2824 anchor = compiler_new_block(c);
2825
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002826 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002827 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829
Nick Coghlan650f0d02007-04-15 12:05:43 +00002830 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832 if (gen_index == 0) {
2833 /* Receive outermost iter as an implicit argument */
2834 c->u->u_argcount = 1;
2835 ADDOP_I(c, LOAD_FAST, 0);
2836 }
2837 else {
2838 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002839 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 ADDOP(c, GET_ITER);
2841 }
2842 compiler_use_next_block(c, start);
2843 ADDOP_JREL(c, FOR_ITER, anchor);
2844 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002845 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002848 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002850 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002852 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002854 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002856 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002857 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002858 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002859 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002860 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861
Nick Coghlan650f0d02007-04-15 12:05:43 +00002862 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002864 /* comprehension specific code */
2865 switch (type) {
2866 case COMP_GENEXP:
2867 VISIT(c, expr, elt);
2868 ADDOP(c, YIELD_VALUE);
2869 ADDOP(c, POP_TOP);
2870 break;
2871 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002872 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002873 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002874 break;
2875 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002876 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002877 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002878 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002879 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002880 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002881 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002882 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002883 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002884 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002885 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002886 default:
2887 return 0;
2888 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889
2890 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002891 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002892 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2894 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895
2896 return 1;
2897}
2898
2899static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002900compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002901 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002902{
2903 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002904 expr_ty outermost_iter;
2905
2906 outermost_iter = ((comprehension_ty)
2907 asdl_seq_GET(generators, 0))->iter;
2908
2909 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2910 goto error;
2911
2912 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002913 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002914 switch (type) {
2915 case COMP_LISTCOMP:
2916 op = BUILD_LIST;
2917 break;
2918 case COMP_SETCOMP:
2919 op = BUILD_SET;
2920 break;
2921 case COMP_DICTCOMP:
2922 op = BUILD_MAP;
2923 break;
2924 default:
2925 PyErr_Format(PyExc_SystemError,
2926 "unknown comprehension type %d", type);
2927 goto error_in_scope;
2928 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002929
Guido van Rossum992d4a32007-07-11 13:09:30 +00002930 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002931 }
2932
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002933 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002934 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002935 goto error_in_scope;
2936
2937 if (type != COMP_GENEXP) {
2938 ADDOP(c, RETURN_VALUE);
2939 }
2940
2941 co = assemble(c, 1);
2942 compiler_exit_scope(c);
2943 if (co == NULL)
2944 goto error;
2945
2946 if (!compiler_make_closure(c, co, 0))
2947 goto error;
2948 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002949
2950 VISIT(c, expr, outermost_iter);
2951 ADDOP(c, GET_ITER);
2952 ADDOP_I(c, CALL_FUNCTION, 1);
2953 return 1;
2954error_in_scope:
2955 compiler_exit_scope(c);
2956error:
2957 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002958 return 0;
2959}
2960
2961static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962compiler_genexp(struct compiler *c, expr_ty e)
2963{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002964 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002965 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002966 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002967 if (!name)
2968 return 0;
2969 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002970 assert(e->kind == GeneratorExp_kind);
2971 return compiler_comprehension(c, e, COMP_GENEXP, name,
2972 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002973 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974}
2975
2976static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002977compiler_listcomp(struct compiler *c, expr_ty e)
2978{
2979 static identifier name;
2980 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002981 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002982 if (!name)
2983 return 0;
2984 }
2985 assert(e->kind == ListComp_kind);
2986 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2987 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002988 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002989}
2990
2991static int
2992compiler_setcomp(struct compiler *c, expr_ty e)
2993{
2994 static identifier name;
2995 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002996 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002997 if (!name)
2998 return 0;
2999 }
3000 assert(e->kind == SetComp_kind);
3001 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3002 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003003 e->v.SetComp.elt, NULL);
3004}
3005
3006
3007static int
3008compiler_dictcomp(struct compiler *c, expr_ty e)
3009{
3010 static identifier name;
3011 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003012 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003013 if (!name)
3014 return 0;
3015 }
3016 assert(e->kind == DictComp_kind);
3017 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3018 e->v.DictComp.generators,
3019 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003020}
3021
3022
3023static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024compiler_visit_keyword(struct compiler *c, keyword_ty k)
3025{
3026 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3027 VISIT(c, expr, k->value);
3028 return 1;
3029}
3030
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003031/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032 whether they are true or false.
3033
3034 Return values: 1 for true, 0 for false, -1 for non-constant.
3035 */
3036
3037static int
3038expr_constant(expr_ty e)
3039{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003040 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003042 case Ellipsis_kind:
3043 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 case Num_kind:
3045 return PyObject_IsTrue(e->v.Num.n);
3046 case Str_kind:
3047 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003048 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003049 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003050 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003051 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003052 if (strcmp(id, "True") == 0) return 1;
3053 if (strcmp(id, "False") == 0) return 0;
3054 if (strcmp(id, "None") == 0) return 0;
3055 if (strcmp(id, "__debug__") == 0)
3056 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003057 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058 default:
3059 return -1;
3060 }
3061}
3062
Guido van Rossumc2e20742006-02-27 22:32:47 +00003063/*
3064 Implements the with statement from PEP 343.
3065
3066 The semantics outlined in that PEP are as follows:
3067
3068 with EXPR as VAR:
3069 BLOCK
3070
3071 It is implemented roughly as:
3072
Thomas Wouters477c8d52006-05-27 19:21:47 +00003073 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003074 exit = context.__exit__ # not calling it
3075 value = context.__enter__()
3076 try:
3077 VAR = value # if VAR present in the syntax
3078 BLOCK
3079 finally:
3080 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003081 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003082 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003083 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003084 exit(*exc)
3085 */
3086static int
3087compiler_with(struct compiler *c, stmt_ty s)
3088{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003089 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003090 basicblock *block, *finally;
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003091 identifier tmpvalue = NULL, tmpexit = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003092
3093 assert(s->kind == With_kind);
3094
Guido van Rossumc2e20742006-02-27 22:32:47 +00003095 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003096 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003097 if (!enter_attr)
3098 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003099 }
3100 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003101 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003102 if (!exit_attr)
3103 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003104 }
3105
3106 block = compiler_new_block(c);
3107 finally = compiler_new_block(c);
3108 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003109 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003110
Guido van Rossumc2e20742006-02-27 22:32:47 +00003111 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003112 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003113 We need to do this rather than preserving it on the stack
3114 because SETUP_FINALLY remembers the stack level.
3115 We need to do the assignment *inside* the try/finally
3116 so that context.__exit__() is called when the assignment
3117 fails. But we need to call context.__enter__() *before*
3118 the try/finally so that if it fails we won't call
3119 context.__exit__().
3120 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003121 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003122 if (tmpvalue == NULL)
3123 return 0;
3124 PyArena_AddPyObject(c->c_arena, tmpvalue);
3125 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003126 tmpexit = compiler_new_tmpname(c);
3127 if (tmpexit == NULL)
3128 return 0;
3129 PyArena_AddPyObject(c->c_arena, tmpexit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003130
Thomas Wouters477c8d52006-05-27 19:21:47 +00003131 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003132 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003133
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003134 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003135 ADDOP(c, DUP_TOP);
3136 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003137 if (!compiler_nameop(c, tmpexit, Store))
3138 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003139
3140 /* Call context.__enter__() */
3141 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3142 ADDOP_I(c, CALL_FUNCTION, 0);
3143
3144 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003145 /* Store it in tmpvalue */
3146 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003147 return 0;
3148 }
3149 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 /* Discard result from context.__enter__() */
3151 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003152 }
3153
3154 /* Start the try block */
3155 ADDOP_JREL(c, SETUP_FINALLY, finally);
3156
3157 compiler_use_next_block(c, block);
3158 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003159 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003160 }
3161
3162 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003163 /* Bind saved result of context.__enter__() to VAR */
3164 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003165 !compiler_nameop(c, tmpvalue, Del))
3166 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003168 }
3169
3170 /* BLOCK code */
3171 VISIT_SEQ(c, stmt, s->v.With.body);
3172
3173 /* End of try block; start the finally block */
3174 ADDOP(c, POP_BLOCK);
3175 compiler_pop_fblock(c, FINALLY_TRY, block);
3176
3177 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3178 compiler_use_next_block(c, finally);
3179 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003180 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003181
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003182 /* Finally block starts; context.__exit__ is on the stack under
3183 the exception or return information. Just issue our magic
3184 opcode. */
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003185 if (!compiler_nameop(c, tmpexit, Load) ||
3186 !compiler_nameop(c, tmpexit, Del))
3187 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003188 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003189
3190 /* Finally block ends. */
3191 ADDOP(c, END_FINALLY);
3192 compiler_pop_fblock(c, FINALLY_END, finally);
3193 return 1;
3194}
3195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196static int
3197compiler_visit_expr(struct compiler *c, expr_ty e)
3198{
3199 int i, n;
3200
Thomas Wouters89f507f2006-12-13 04:49:30 +00003201 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003202 set a new line number for the next instruction.
3203 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 if (e->lineno > c->u->u_lineno) {
3205 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003206 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207 }
3208 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212 VISIT(c, expr, e->v.BinOp.left);
3213 VISIT(c, expr, e->v.BinOp.right);
3214 ADDOP(c, binop(c, e->v.BinOp.op));
3215 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003216 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217 VISIT(c, expr, e->v.UnaryOp.operand);
3218 ADDOP(c, unaryop(e->v.UnaryOp.op));
3219 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003220 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003222 case IfExp_kind:
3223 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003224 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003226 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003228 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003229 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003230 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003231 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003232 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003233 }
3234 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003235 case Set_kind:
3236 n = asdl_seq_LEN(e->v.Set.elts);
3237 VISIT_SEQ(c, expr, e->v.Set.elts);
3238 ADDOP_I(c, BUILD_SET, n);
3239 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003240 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003241 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003242 case ListComp_kind:
3243 return compiler_listcomp(c, e);
3244 case SetComp_kind:
3245 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003246 case DictComp_kind:
3247 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248 case Yield_kind:
3249 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003250 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251 if (e->v.Yield.value) {
3252 VISIT(c, expr, e->v.Yield.value);
3253 }
3254 else {
3255 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3256 }
3257 ADDOP(c, YIELD_VALUE);
3258 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003259 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003261 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3265 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003266 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3268 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003269 case Bytes_kind:
3270 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003271 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003272 case Ellipsis_kind:
3273 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3274 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003276 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 if (e->v.Attribute.ctx != AugStore)
3278 VISIT(c, expr, e->v.Attribute.value);
3279 switch (e->v.Attribute.ctx) {
3280 case AugLoad:
3281 ADDOP(c, DUP_TOP);
3282 /* Fall through to load */
3283 case Load:
3284 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3285 break;
3286 case AugStore:
3287 ADDOP(c, ROT_TWO);
3288 /* Fall through to save */
3289 case Store:
3290 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3291 break;
3292 case Del:
3293 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3294 break;
3295 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003296 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003297 PyErr_SetString(PyExc_SystemError,
3298 "param invalid in attribute expression");
3299 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 }
3301 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003302 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 switch (e->v.Subscript.ctx) {
3304 case AugLoad:
3305 VISIT(c, expr, e->v.Subscript.value);
3306 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3307 break;
3308 case Load:
3309 VISIT(c, expr, e->v.Subscript.value);
3310 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3311 break;
3312 case AugStore:
3313 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3314 break;
3315 case Store:
3316 VISIT(c, expr, e->v.Subscript.value);
3317 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3318 break;
3319 case Del:
3320 VISIT(c, expr, e->v.Subscript.value);
3321 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3322 break;
3323 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003324 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003325 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003326 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003327 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328 }
3329 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003330 case Starred_kind:
3331 switch (e->v.Starred.ctx) {
3332 case Store:
3333 /* In all legitimate cases, the Starred node was already replaced
3334 * by compiler_list/compiler_tuple. XXX: is that okay? */
3335 return compiler_error(c,
3336 "starred assignment target must be in a list or tuple");
3337 default:
3338 return compiler_error(c,
3339 "can use starred expression only as assignment target");
3340 }
3341 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003342 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3344 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003345 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003347 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003348 return compiler_tuple(c, e);
3349 }
3350 return 1;
3351}
3352
3353static int
3354compiler_augassign(struct compiler *c, stmt_ty s)
3355{
3356 expr_ty e = s->v.AugAssign.target;
3357 expr_ty auge;
3358
3359 assert(s->kind == AugAssign_kind);
3360
3361 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003362 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003364 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003365 if (auge == NULL)
3366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003367 VISIT(c, expr, auge);
3368 VISIT(c, expr, s->v.AugAssign.value);
3369 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3370 auge->v.Attribute.ctx = AugStore;
3371 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003372 break;
3373 case Subscript_kind:
3374 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003375 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003376 if (auge == NULL)
3377 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003378 VISIT(c, expr, auge);
3379 VISIT(c, expr, s->v.AugAssign.value);
3380 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003381 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003383 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003385 if (!compiler_nameop(c, e->v.Name.id, Load))
3386 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387 VISIT(c, expr, s->v.AugAssign.value);
3388 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3389 return compiler_nameop(c, e->v.Name.id, Store);
3390 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003391 PyErr_Format(PyExc_SystemError,
3392 "invalid node type (%d) for augmented assignment",
3393 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003394 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003395 }
3396 return 1;
3397}
3398
3399static int
3400compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3401{
3402 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003403 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3404 PyErr_SetString(PyExc_SystemError,
3405 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003406 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003407 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408 f = &c->u->u_fblock[c->u->u_nfblocks++];
3409 f->fb_type = t;
3410 f->fb_block = b;
3411 return 1;
3412}
3413
3414static void
3415compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3416{
3417 struct compiler_unit *u = c->u;
3418 assert(u->u_nfblocks > 0);
3419 u->u_nfblocks--;
3420 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3421 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3422}
3423
Thomas Wouters89f507f2006-12-13 04:49:30 +00003424static int
3425compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003426 int i;
3427 struct compiler_unit *u = c->u;
3428 for (i = 0; i < u->u_nfblocks; ++i) {
3429 if (u->u_fblock[i].fb_type == LOOP)
3430 return 1;
3431 }
3432 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003433}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434/* Raises a SyntaxError and returns 0.
3435 If something goes wrong, a different exception may be raised.
3436*/
3437
3438static int
3439compiler_error(struct compiler *c, const char *errstr)
3440{
3441 PyObject *loc;
3442 PyObject *u = NULL, *v = NULL;
3443
3444 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3445 if (!loc) {
3446 Py_INCREF(Py_None);
3447 loc = Py_None;
3448 }
3449 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3450 Py_None, loc);
3451 if (!u)
3452 goto exit;
3453 v = Py_BuildValue("(zO)", errstr, u);
3454 if (!v)
3455 goto exit;
3456 PyErr_SetObject(PyExc_SyntaxError, v);
3457 exit:
3458 Py_DECREF(loc);
3459 Py_XDECREF(u);
3460 Py_XDECREF(v);
3461 return 0;
3462}
3463
3464static int
3465compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003466 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 /* XXX this code is duplicated */
3471 switch (ctx) {
3472 case AugLoad: /* fall through to Load */
3473 case Load: op = BINARY_SUBSCR; break;
3474 case AugStore:/* fall through to Store */
3475 case Store: op = STORE_SUBSCR; break;
3476 case Del: op = DELETE_SUBSCR; break;
3477 case Param:
3478 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003479 "invalid %s kind %d in subscript\n",
3480 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003481 return 0;
3482 }
3483 if (ctx == AugLoad) {
3484 ADDOP_I(c, DUP_TOPX, 2);
3485 }
3486 else if (ctx == AugStore) {
3487 ADDOP(c, ROT_THREE);
3488 }
3489 ADDOP(c, op);
3490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491}
3492
3493static int
3494compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3495{
3496 int n = 2;
3497 assert(s->kind == Slice_kind);
3498
3499 /* only handles the cases where BUILD_SLICE is emitted */
3500 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003501 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502 }
3503 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003504 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003508 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509 }
3510 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003511 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512 }
3513
3514 if (s->v.Slice.step) {
3515 n++;
3516 VISIT(c, expr, s->v.Slice.step);
3517 }
3518 ADDOP_I(c, BUILD_SLICE, n);
3519 return 1;
3520}
3521
3522static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3524 expr_context_ty ctx)
3525{
3526 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 case Slice_kind:
3528 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 case Index_kind:
3530 VISIT(c, expr, s->v.Index.value);
3531 break;
3532 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003533 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003534 PyErr_SetString(PyExc_SystemError,
3535 "extended slice invalid in nested slice");
3536 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537 }
3538 return 1;
3539}
3540
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541static int
3542compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3543{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003544 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003546 case Index_kind:
3547 kindname = "index";
3548 if (ctx != AugStore) {
3549 VISIT(c, expr, s->v.Index.value);
3550 }
3551 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003553 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003554 if (ctx != AugStore) {
3555 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 return 0;
3557 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003558 break;
3559 case ExtSlice_kind:
3560 kindname = "extended slice";
3561 if (ctx != AugStore) {
3562 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3563 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003564 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003565 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003566 if (!compiler_visit_nested_slice(c, sub, ctx))
3567 return 0;
3568 }
3569 ADDOP_I(c, BUILD_TUPLE, n);
3570 }
3571 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003572 default:
3573 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003574 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003575 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003577 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578}
3579
Thomas Wouters89f507f2006-12-13 04:49:30 +00003580/* End of the compiler section, beginning of the assembler section */
3581
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582/* do depth-first search of basic block graph, starting with block.
3583 post records the block indices in post-order.
3584
3585 XXX must handle implicit jumps from one block to next
3586*/
3587
Thomas Wouters89f507f2006-12-13 04:49:30 +00003588struct assembler {
3589 PyObject *a_bytecode; /* string containing bytecode */
3590 int a_offset; /* offset into bytecode */
3591 int a_nblocks; /* number of reachable blocks */
3592 basicblock **a_postorder; /* list of blocks in dfs postorder */
3593 PyObject *a_lnotab; /* string containing lnotab */
3594 int a_lnotab_off; /* offset into lnotab */
3595 int a_lineno; /* last lineno of emitted instruction */
3596 int a_lineno_off; /* bytecode offset of last lineno */
3597};
3598
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599static void
3600dfs(struct compiler *c, basicblock *b, struct assembler *a)
3601{
3602 int i;
3603 struct instr *instr = NULL;
3604
3605 if (b->b_seen)
3606 return;
3607 b->b_seen = 1;
3608 if (b->b_next != NULL)
3609 dfs(c, b->b_next, a);
3610 for (i = 0; i < b->b_iused; i++) {
3611 instr = &b->b_instr[i];
3612 if (instr->i_jrel || instr->i_jabs)
3613 dfs(c, instr->i_target, a);
3614 }
3615 a->a_postorder[a->a_nblocks++] = b;
3616}
3617
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003618static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3620{
3621 int i;
3622 struct instr *instr;
3623 if (b->b_seen || b->b_startdepth >= depth)
3624 return maxdepth;
3625 b->b_seen = 1;
3626 b->b_startdepth = depth;
3627 for (i = 0; i < b->b_iused; i++) {
3628 instr = &b->b_instr[i];
3629 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3630 if (depth > maxdepth)
3631 maxdepth = depth;
3632 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3633 if (instr->i_jrel || instr->i_jabs) {
3634 maxdepth = stackdepth_walk(c, instr->i_target,
3635 depth, maxdepth);
3636 if (instr->i_opcode == JUMP_ABSOLUTE ||
3637 instr->i_opcode == JUMP_FORWARD) {
3638 goto out; /* remaining code is dead */
3639 }
3640 }
3641 }
3642 if (b->b_next)
3643 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3644out:
3645 b->b_seen = 0;
3646 return maxdepth;
3647}
3648
3649/* Find the flow path that needs the largest stack. We assume that
3650 * cycles in the flow graph have no net effect on the stack depth.
3651 */
3652static int
3653stackdepth(struct compiler *c)
3654{
3655 basicblock *b, *entryblock;
3656 entryblock = NULL;
3657 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3658 b->b_seen = 0;
3659 b->b_startdepth = INT_MIN;
3660 entryblock = b;
3661 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003662 if (!entryblock)
3663 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664 return stackdepth_walk(c, entryblock, 0, 0);
3665}
3666
3667static int
3668assemble_init(struct assembler *a, int nblocks, int firstlineno)
3669{
3670 memset(a, 0, sizeof(struct assembler));
3671 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003672 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673 if (!a->a_bytecode)
3674 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003675 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676 if (!a->a_lnotab)
3677 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003678 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3679 PyErr_NoMemory();
3680 return 0;
3681 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003683 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003684 if (!a->a_postorder) {
3685 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003686 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003687 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688 return 1;
3689}
3690
3691static void
3692assemble_free(struct assembler *a)
3693{
3694 Py_XDECREF(a->a_bytecode);
3695 Py_XDECREF(a->a_lnotab);
3696 if (a->a_postorder)
3697 PyObject_Free(a->a_postorder);
3698}
3699
3700/* Return the size of a basic block in bytes. */
3701
3702static int
3703instrsize(struct instr *instr)
3704{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003705 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003706 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003707 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003708 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3709 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710}
3711
3712static int
3713blocksize(basicblock *b)
3714{
3715 int i;
3716 int size = 0;
3717
3718 for (i = 0; i < b->b_iused; i++)
3719 size += instrsize(&b->b_instr[i]);
3720 return size;
3721}
3722
3723/* All about a_lnotab.
3724
3725c_lnotab is an array of unsigned bytes disguised as a Python string.
3726It is used to map bytecode offsets to source code line #s (when needed
3727for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003728
Tim Peters2a7f3842001-06-09 09:26:21 +00003729The array is conceptually a list of
3730 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003731pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003732
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003733 byte code offset source code line number
3734 0 1
3735 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003736 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003737 350 307
3738 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003739
3740The first trick is that these numbers aren't stored, only the increments
3741from one row to the next (this doesn't really work, but it's a start):
3742
3743 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3744
3745The second trick is that an unsigned byte can't hold negative values, or
3746values larger than 255, so (a) there's a deep assumption that byte code
3747offsets and their corresponding line #s both increase monotonically, and (b)
3748if at least one column jumps by more than 255 from one row to the next, more
3749than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003750from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003751part. A user of c_lnotab desiring to find the source line number
3752corresponding to a bytecode address A should do something like this
3753
3754 lineno = addr = 0
3755 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003756 addr += addr_incr
3757 if addr > A:
3758 return lineno
3759 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003760
3761In order for this to work, when the addr field increments by more than 255,
3762the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003763increment is < 256. So, in the example above, assemble_lnotab (it used
3764to be called com_set_lineno) should not (as was actually done until 2.2)
3765expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003766 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003767*/
3768
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003769static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003771{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 int d_bytecode, d_lineno;
3773 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003774 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775
3776 d_bytecode = a->a_offset - a->a_lineno_off;
3777 d_lineno = i->i_lineno - a->a_lineno;
3778
3779 assert(d_bytecode >= 0);
3780 assert(d_lineno >= 0);
3781
Christian Heimes2202f872008-02-06 14:31:34 +00003782 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003783 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003786 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003788 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003790 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003792 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003794 else {
3795 PyErr_NoMemory();
3796 return 0;
3797 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003798 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003800 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003801 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003802 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003803 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 *lnotab++ = 255;
3805 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003806 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807 d_bytecode -= ncodes * 255;
3808 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003809 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 assert(d_bytecode <= 255);
3811 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003812 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003814 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003816 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003818 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003820 else {
3821 PyErr_NoMemory();
3822 return 0;
3823 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003824 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003826 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003827 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003828 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003830 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003831 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003832 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003834 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836 d_lineno -= ncodes * 255;
3837 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003838 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003839
Christian Heimes72b710a2008-05-26 13:28:38 +00003840 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003842 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003843 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003844 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003845 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003846 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 a->a_lnotab_off += 2;
3849 if (d_bytecode) {
3850 *lnotab++ = d_bytecode;
3851 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003852 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003853 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 *lnotab++ = 0;
3855 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 a->a_lineno = i->i_lineno;
3858 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003859 return 1;
3860}
3861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862/* assemble_emit()
3863 Extend the bytecode with a new instruction.
3864 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003865*/
3866
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003867static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003869{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003870 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003871 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872 char *code;
3873
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003874 size = instrsize(i);
3875 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003877 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003878 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003879 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003880 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003882 if (len > PY_SSIZE_T_MAX / 2)
3883 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003884 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003885 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003886 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003887 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003889 if (size == 6) {
3890 assert(i->i_hasarg);
3891 *code++ = (char)EXTENDED_ARG;
3892 *code++ = ext & 0xff;
3893 *code++ = ext >> 8;
3894 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003895 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003896 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003897 if (i->i_hasarg) {
3898 assert(size == 3 || size == 6);
3899 *code++ = arg & 0xff;
3900 *code++ = arg >> 8;
3901 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003903}
3904
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003905static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003907{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003909 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003910 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003911
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003912 /* Compute the size of each block and fixup jump args.
3913 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003914start:
3915 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003917 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 bsize = blocksize(b);
3919 b->b_offset = totsize;
3920 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003921 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003922 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3924 bsize = b->b_offset;
3925 for (i = 0; i < b->b_iused; i++) {
3926 struct instr *instr = &b->b_instr[i];
3927 /* Relative jumps are computed relative to
3928 the instruction pointer after fetching
3929 the jump instruction.
3930 */
3931 bsize += instrsize(instr);
3932 if (instr->i_jabs)
3933 instr->i_oparg = instr->i_target->b_offset;
3934 else if (instr->i_jrel) {
3935 int delta = instr->i_target->b_offset - bsize;
3936 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003937 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003938 else
3939 continue;
3940 if (instr->i_oparg > 0xffff)
3941 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003942 }
3943 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003944
3945 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003946 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003947 with a better solution.
3948
3949 In the meantime, should the goto be dropped in favor
3950 of a loop?
3951
3952 The issue is that in the first loop blocksize() is called
3953 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003954 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003955 i_oparg is calculated in the second loop above.
3956
3957 So we loop until we stop seeing new EXTENDED_ARGs.
3958 The only EXTENDED_ARGs that could be popping up are
3959 ones in jump instructions. So this should converge
3960 fairly quickly.
3961 */
3962 if (last_extended_arg_count != extended_arg_count) {
3963 last_extended_arg_count = extended_arg_count;
3964 goto start;
3965 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003966}
3967
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003968static PyObject *
3969dict_keys_inorder(PyObject *dict, int offset)
3970{
3971 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003972 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003973
3974 tuple = PyTuple_New(size);
3975 if (tuple == NULL)
3976 return NULL;
3977 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003978 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003979 /* The keys of the dictionary are tuples. (see compiler_add_o)
3980 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003981 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003982 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003983 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003984 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003985 PyTuple_SET_ITEM(tuple, i - offset, k);
3986 }
3987 return tuple;
3988}
3989
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003990static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003992{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003993 PySTEntryObject *ste = c->u->u_ste;
3994 int flags = 0, n;
3995 if (ste->ste_type != ModuleBlock)
3996 flags |= CO_NEWLOCALS;
3997 if (ste->ste_type == FunctionBlock) {
3998 if (!ste->ste_unoptimized)
3999 flags |= CO_OPTIMIZED;
4000 if (ste->ste_nested)
4001 flags |= CO_NESTED;
4002 if (ste->ste_generator)
4003 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00004004 if (ste->ste_varargs)
4005 flags |= CO_VARARGS;
4006 if (ste->ste_varkeywords)
4007 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004008 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004009
4010 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004011 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004013 n = PyDict_Size(c->u->u_freevars);
4014 if (n < 0)
4015 return -1;
4016 if (n == 0) {
4017 n = PyDict_Size(c->u->u_cellvars);
4018 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004019 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020 if (n == 0) {
4021 flags |= CO_NOFREE;
4022 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004023 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004024
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004025 return flags;
4026}
4027
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028static PyCodeObject *
4029makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004030{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004031 PyObject *tmp;
4032 PyCodeObject *co = NULL;
4033 PyObject *consts = NULL;
4034 PyObject *names = NULL;
4035 PyObject *varnames = NULL;
4036 PyObject *filename = NULL;
4037 PyObject *name = NULL;
4038 PyObject *freevars = NULL;
4039 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004040 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004041 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004043 tmp = dict_keys_inorder(c->u->u_consts, 0);
4044 if (!tmp)
4045 goto error;
4046 consts = PySequence_List(tmp); /* optimize_code requires a list */
4047 Py_DECREF(tmp);
4048
4049 names = dict_keys_inorder(c->u->u_names, 0);
4050 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4051 if (!consts || !names || !varnames)
4052 goto error;
4053
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004054 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4055 if (!cellvars)
4056 goto error;
4057 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4058 if (!freevars)
4059 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004060 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061 if (!filename)
4062 goto error;
4063
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004064 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065 flags = compute_code_flags(c);
4066 if (flags < 0)
4067 goto error;
4068
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004069 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070 if (!bytecode)
4071 goto error;
4072
4073 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4074 if (!tmp)
4075 goto error;
4076 Py_DECREF(consts);
4077 consts = tmp;
4078
Guido van Rossum4f72a782006-10-27 23:31:49 +00004079 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4080 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004081 bytecode, consts, names, varnames,
4082 freevars, cellvars,
4083 filename, c->u->u_name,
4084 c->u->u_firstlineno,
4085 a->a_lnotab);
4086 error:
4087 Py_XDECREF(consts);
4088 Py_XDECREF(names);
4089 Py_XDECREF(varnames);
4090 Py_XDECREF(filename);
4091 Py_XDECREF(name);
4092 Py_XDECREF(freevars);
4093 Py_XDECREF(cellvars);
4094 Py_XDECREF(bytecode);
4095 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004096}
4097
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004098
4099/* For debugging purposes only */
4100#if 0
4101static void
4102dump_instr(const struct instr *i)
4103{
4104 const char *jrel = i->i_jrel ? "jrel " : "";
4105 const char *jabs = i->i_jabs ? "jabs " : "";
4106 char arg[128];
4107
4108 *arg = '\0';
4109 if (i->i_hasarg)
4110 sprintf(arg, "arg: %d ", i->i_oparg);
4111
4112 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4113 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4114}
4115
4116static void
4117dump_basicblock(const basicblock *b)
4118{
4119 const char *seen = b->b_seen ? "seen " : "";
4120 const char *b_return = b->b_return ? "return " : "";
4121 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4122 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4123 if (b->b_instr) {
4124 int i;
4125 for (i = 0; i < b->b_iused; i++) {
4126 fprintf(stderr, " [%02d] ", i);
4127 dump_instr(b->b_instr + i);
4128 }
4129 }
4130}
4131#endif
4132
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133static PyCodeObject *
4134assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004135{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004136 basicblock *b, *entryblock;
4137 struct assembler a;
4138 int i, j, nblocks;
4139 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141 /* Make sure every block that falls off the end returns None.
4142 XXX NEXT_BLOCK() isn't quite right, because if the last
4143 block ends with a jump or return b_next shouldn't set.
4144 */
4145 if (!c->u->u_curblock->b_return) {
4146 NEXT_BLOCK(c);
4147 if (addNone)
4148 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4149 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004150 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152 nblocks = 0;
4153 entryblock = NULL;
4154 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4155 nblocks++;
4156 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004157 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004158
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004159 /* Set firstlineno if it wasn't explicitly set. */
4160 if (!c->u->u_firstlineno) {
4161 if (entryblock && entryblock->b_instr)
4162 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4163 else
4164 c->u->u_firstlineno = 1;
4165 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4167 goto error;
4168 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004169
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004171 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173 /* Emit code in reverse postorder from dfs. */
4174 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004175 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176 for (j = 0; j < b->b_iused; j++)
4177 if (!assemble_emit(&a, &b->b_instr[j]))
4178 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004179 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004180
Christian Heimes72b710a2008-05-26 13:28:38 +00004181 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004182 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004183 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004185
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186 co = makecode(c, &a);
4187 error:
4188 assemble_free(&a);
4189 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004190}