blob: 490137f3db104779d78f0ddf9b5971fcc1cc90d8 [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
Guido van Rossumc2e20742006-02-27 22:32:47 +0000554/* Allocate a new "anonymous" local variable.
555 Used by list comprehensions and with statements.
556*/
557
558static PyObject *
559compiler_new_tmpname(struct compiler *c)
560{
561 char tmpname[256];
562 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000563 return PyUnicode_FromString(tmpname);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000564}
565
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566/* Allocate a new block and return a pointer to it.
567 Returns NULL on error.
568*/
569
570static basicblock *
571compiler_new_block(struct compiler *c)
572{
573 basicblock *b;
574 struct compiler_unit *u;
575
576 u = c->u;
577 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000578 if (b == NULL) {
579 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000581 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000583 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000584 b->b_list = u->u_blocks;
585 u->u_blocks = b;
586 return b;
587}
588
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000589static basicblock *
590compiler_use_new_block(struct compiler *c)
591{
592 basicblock *block = compiler_new_block(c);
593 if (block == NULL)
594 return NULL;
595 c->u->u_curblock = block;
596 return block;
597}
598
599static basicblock *
600compiler_next_block(struct compiler *c)
601{
602 basicblock *block = compiler_new_block(c);
603 if (block == NULL)
604 return NULL;
605 c->u->u_curblock->b_next = block;
606 c->u->u_curblock = block;
607 return block;
608}
609
610static basicblock *
611compiler_use_next_block(struct compiler *c, basicblock *block)
612{
613 assert(block != NULL);
614 c->u->u_curblock->b_next = block;
615 c->u->u_curblock = block;
616 return block;
617}
618
619/* Returns the offset of the next instruction in the current block's
620 b_instr array. Resizes the b_instr as necessary.
621 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000622*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623
624static int
625compiler_next_instr(struct compiler *c, basicblock *b)
626{
627 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000628 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000629 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000630 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000631 if (b->b_instr == NULL) {
632 PyErr_NoMemory();
633 return -1;
634 }
635 b->b_ialloc = DEFAULT_BLOCK_SIZE;
636 memset((char *)b->b_instr, 0,
637 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000638 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000640 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000641 size_t oldsize, newsize;
642 oldsize = b->b_ialloc * sizeof(struct instr);
643 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000644
645 if (oldsize > (PY_SIZE_MAX >> 1)) {
646 PyErr_NoMemory();
647 return -1;
648 }
649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650 if (newsize == 0) {
651 PyErr_NoMemory();
652 return -1;
653 }
654 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000656 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000657 if (tmp == NULL) {
658 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000660 }
661 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
663 }
664 return b->b_iused++;
665}
666
Christian Heimes2202f872008-02-06 14:31:34 +0000667/* Set the i_lineno member of the instruction at offset off if the
668 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000669 already been set. If it has been set, the call has no effect.
670
Christian Heimes2202f872008-02-06 14:31:34 +0000671 The line number is reset in the following cases:
672 - when entering a new scope
673 - on each statement
674 - on each expression that start a new line
675 - before the "except" clause
676 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000679static void
680compiler_set_lineno(struct compiler *c, int off)
681{
682 basicblock *b;
683 if (c->u->u_lineno_set)
684 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000685 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000687 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000688}
689
690static int
691opcode_stack_effect(int opcode, int oparg)
692{
693 switch (opcode) {
694 case POP_TOP:
695 return -1;
696 case ROT_TWO:
697 case ROT_THREE:
698 return 0;
699 case DUP_TOP:
700 return 1;
701 case ROT_FOUR:
702 return 0;
703
704 case UNARY_POSITIVE:
705 case UNARY_NEGATIVE:
706 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000707 case UNARY_INVERT:
708 return 0;
709
Nick Coghlan650f0d02007-04-15 12:05:43 +0000710 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000711 case LIST_APPEND:
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000712 return -1;
713 case MAP_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000714 return -2;
715
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716 case BINARY_POWER:
717 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000718 case BINARY_MODULO:
719 case BINARY_ADD:
720 case BINARY_SUBTRACT:
721 case BINARY_SUBSCR:
722 case BINARY_FLOOR_DIVIDE:
723 case BINARY_TRUE_DIVIDE:
724 return -1;
725 case INPLACE_FLOOR_DIVIDE:
726 case INPLACE_TRUE_DIVIDE:
727 return -1;
728
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000729 case INPLACE_ADD:
730 case INPLACE_SUBTRACT:
731 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732 case INPLACE_MODULO:
733 return -1;
734 case STORE_SUBSCR:
735 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000736 case STORE_MAP:
737 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000738 case DELETE_SUBSCR:
739 return -2;
740
741 case BINARY_LSHIFT:
742 case BINARY_RSHIFT:
743 case BINARY_AND:
744 case BINARY_XOR:
745 case BINARY_OR:
746 return -1;
747 case INPLACE_POWER:
748 return -1;
749 case GET_ITER:
750 return 0;
751
752 case PRINT_EXPR:
753 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000754 case LOAD_BUILD_CLASS:
755 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756 case INPLACE_LSHIFT:
757 case INPLACE_RSHIFT:
758 case INPLACE_AND:
759 case INPLACE_XOR:
760 case INPLACE_OR:
761 return -1;
762 case BREAK_LOOP:
763 return 0;
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000764 case SETUP_WITH:
765 return 7;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000766 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000767 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000768 case STORE_LOCALS:
769 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770 case RETURN_VALUE:
771 return -1;
772 case IMPORT_STAR:
773 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774 case YIELD_VALUE:
775 return 0;
776
777 case POP_BLOCK:
778 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000779 case POP_EXCEPT:
780 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781 case END_FINALLY:
782 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783
784 case STORE_NAME:
785 return -1;
786 case DELETE_NAME:
787 return 0;
788 case UNPACK_SEQUENCE:
789 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000790 case UNPACK_EX:
791 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000792 case FOR_ITER:
793 return 1;
794
795 case STORE_ATTR:
796 return -2;
797 case DELETE_ATTR:
798 return -1;
799 case STORE_GLOBAL:
800 return -1;
801 case DELETE_GLOBAL:
802 return 0;
803 case DUP_TOPX:
804 return oparg;
805 case LOAD_CONST:
806 return 1;
807 case LOAD_NAME:
808 return 1;
809 case BUILD_TUPLE:
810 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000811 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000812 return 1-oparg;
813 case BUILD_MAP:
814 return 1;
815 case LOAD_ATTR:
816 return 0;
817 case COMPARE_OP:
818 return -1;
819 case IMPORT_NAME:
820 return 0;
821 case IMPORT_FROM:
822 return 1;
823
824 case JUMP_FORWARD:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000825 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
826 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827 case JUMP_ABSOLUTE:
828 return 0;
829
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000830 case POP_JUMP_IF_FALSE:
831 case POP_JUMP_IF_TRUE:
832 return -1;
833
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000834 case LOAD_GLOBAL:
835 return 1;
836
837 case CONTINUE_LOOP:
838 return 0;
839 case SETUP_LOOP:
840 return 0;
841 case SETUP_EXCEPT:
842 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000843 return 6; /* can push 3 values for the new exception
844 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845
846 case LOAD_FAST:
847 return 1;
848 case STORE_FAST:
849 return -1;
850 case DELETE_FAST:
851 return 0;
852
853 case RAISE_VARARGS:
854 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000855#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856 case CALL_FUNCTION:
857 return -NARGS(oparg);
858 case CALL_FUNCTION_VAR:
859 case CALL_FUNCTION_KW:
860 return -NARGS(oparg)-1;
861 case CALL_FUNCTION_VAR_KW:
862 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000863 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000864 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000865 case MAKE_CLOSURE:
866 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000867#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000868 case BUILD_SLICE:
869 if (oparg == 3)
870 return -2;
871 else
872 return -1;
873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000874 case LOAD_CLOSURE:
875 return 1;
876 case LOAD_DEREF:
877 return 1;
878 case STORE_DEREF:
879 return -1;
880 default:
881 fprintf(stderr, "opcode = %d\n", opcode);
882 Py_FatalError("opcode_stack_effect()");
883
884 }
885 return 0; /* not reachable */
886}
887
888/* Add an opcode with no argument.
889 Returns 0 on failure, 1 on success.
890*/
891
892static int
893compiler_addop(struct compiler *c, int opcode)
894{
895 basicblock *b;
896 struct instr *i;
897 int off;
898 off = compiler_next_instr(c, c->u->u_curblock);
899 if (off < 0)
900 return 0;
901 b = c->u->u_curblock;
902 i = &b->b_instr[off];
903 i->i_opcode = opcode;
904 i->i_hasarg = 0;
905 if (opcode == RETURN_VALUE)
906 b->b_return = 1;
907 compiler_set_lineno(c, off);
908 return 1;
909}
910
911static int
912compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
913{
914 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000915 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000916 unsigned char *p, *q;
917 Py_complex z;
918 double d;
919 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000921 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000922 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
923 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000924 d = PyFloat_AS_DOUBLE(o);
925 p = (unsigned char*) &d;
926 /* all we need is to make the tuple different in either the 0.0
927 * or -0.0 case from all others, just to avoid the "coercion".
928 */
929 if (*p==0 && p[sizeof(double)-1]==0)
930 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
931 else
932 t = PyTuple_Pack(2, o, o->ob_type);
933 }
934 else if (PyComplex_Check(o)) {
935 /* complex case is even messier: we need to make complex(x,
936 0.) different from complex(x, -0.) and complex(0., y)
937 different from complex(-0., y), for any x and y. In
938 particular, all four complex zeros should be
939 distinguished.*/
940 z = PyComplex_AsCComplex(o);
941 p = (unsigned char*) &(z.real);
942 q = (unsigned char*) &(z.imag);
943 /* all that matters here is that on IEEE platforms
944 real_part_zero will be true if z.real == 0., and false if
945 z.real == -0. In fact, real_part_zero will also be true
946 for some other rarely occurring nonzero floats, but this
947 doesn't matter. Similar comments apply to
948 imag_part_zero. */
949 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
950 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
951 if (real_part_zero && imag_part_zero) {
952 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
953 }
954 else if (real_part_zero && !imag_part_zero) {
955 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
956 }
957 else if (!real_part_zero && imag_part_zero) {
958 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
959 }
960 else {
961 t = PyTuple_Pack(2, o, o->ob_type);
962 }
963 }
964 else {
965 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000966 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000967 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000968 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969
970 v = PyDict_GetItem(dict, t);
971 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000972 if (PyErr_Occurred())
973 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000975 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976 if (!v) {
977 Py_DECREF(t);
978 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000979 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980 if (PyDict_SetItem(dict, t, v) < 0) {
981 Py_DECREF(t);
982 Py_DECREF(v);
983 return -1;
984 }
985 Py_DECREF(v);
986 }
987 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000988 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000990 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991}
992
993static int
994compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
995 PyObject *o)
996{
997 int arg = compiler_add_o(c, dict, o);
998 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000999 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000 return compiler_addop_i(c, opcode, arg);
1001}
1002
1003static int
1004compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001005 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006{
1007 int arg;
1008 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1009 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001010 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011 arg = compiler_add_o(c, dict, mangled);
1012 Py_DECREF(mangled);
1013 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001014 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015 return compiler_addop_i(c, opcode, arg);
1016}
1017
1018/* Add an opcode with an integer argument.
1019 Returns 0 on failure, 1 on success.
1020*/
1021
1022static int
1023compiler_addop_i(struct compiler *c, int opcode, int oparg)
1024{
1025 struct instr *i;
1026 int off;
1027 off = compiler_next_instr(c, c->u->u_curblock);
1028 if (off < 0)
1029 return 0;
1030 i = &c->u->u_curblock->b_instr[off];
1031 i->i_opcode = opcode;
1032 i->i_oparg = oparg;
1033 i->i_hasarg = 1;
1034 compiler_set_lineno(c, off);
1035 return 1;
1036}
1037
1038static int
1039compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1040{
1041 struct instr *i;
1042 int off;
1043
1044 assert(b != NULL);
1045 off = compiler_next_instr(c, c->u->u_curblock);
1046 if (off < 0)
1047 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048 i = &c->u->u_curblock->b_instr[off];
1049 i->i_opcode = opcode;
1050 i->i_target = b;
1051 i->i_hasarg = 1;
1052 if (absolute)
1053 i->i_jabs = 1;
1054 else
1055 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001056 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057 return 1;
1058}
1059
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001060/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1061 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062 it as the current block. NEXT_BLOCK() also creates an implicit jump
1063 from the current block to the new block.
1064*/
1065
Thomas Wouters89f507f2006-12-13 04:49:30 +00001066/* The returns inside these macros make it impossible to decref objects
1067 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068*/
1069
1070
1071#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001072 if (compiler_use_new_block((C)) == NULL) \
1073 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074}
1075
1076#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001077 if (compiler_next_block((C)) == NULL) \
1078 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079}
1080
1081#define ADDOP(C, OP) { \
1082 if (!compiler_addop((C), (OP))) \
1083 return 0; \
1084}
1085
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001086#define ADDOP_IN_SCOPE(C, OP) { \
1087 if (!compiler_addop((C), (OP))) { \
1088 compiler_exit_scope(c); \
1089 return 0; \
1090 } \
1091}
1092
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093#define ADDOP_O(C, OP, O, TYPE) { \
1094 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1095 return 0; \
1096}
1097
1098#define ADDOP_NAME(C, OP, O, TYPE) { \
1099 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1100 return 0; \
1101}
1102
1103#define ADDOP_I(C, OP, O) { \
1104 if (!compiler_addop_i((C), (OP), (O))) \
1105 return 0; \
1106}
1107
1108#define ADDOP_JABS(C, OP, O) { \
1109 if (!compiler_addop_j((C), (OP), (O), 1)) \
1110 return 0; \
1111}
1112
1113#define ADDOP_JREL(C, OP, O) { \
1114 if (!compiler_addop_j((C), (OP), (O), 0)) \
1115 return 0; \
1116}
1117
1118/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1119 the ASDL name to synthesize the name of the C type and the visit function.
1120*/
1121
1122#define VISIT(C, TYPE, V) {\
1123 if (!compiler_visit_ ## TYPE((C), (V))) \
1124 return 0; \
1125}
1126
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001127#define VISIT_IN_SCOPE(C, TYPE, V) {\
1128 if (!compiler_visit_ ## TYPE((C), (V))) { \
1129 compiler_exit_scope(c); \
1130 return 0; \
1131 } \
1132}
1133
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134#define VISIT_SLICE(C, V, CTX) {\
1135 if (!compiler_visit_slice((C), (V), (CTX))) \
1136 return 0; \
1137}
1138
1139#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144 if (!compiler_visit_ ## TYPE((C), elt)) \
1145 return 0; \
1146 } \
1147}
1148
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001149#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001150 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001151 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001152 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001153 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001154 if (!compiler_visit_ ## TYPE((C), elt)) { \
1155 compiler_exit_scope(c); \
1156 return 0; \
1157 } \
1158 } \
1159}
1160
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161static int
1162compiler_isdocstring(stmt_ty s)
1163{
1164 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001165 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166 return s->v.Expr.value->kind == Str_kind;
1167}
1168
1169/* Compile a sequence of statements, checking for a docstring. */
1170
1171static int
1172compiler_body(struct compiler *c, asdl_seq *stmts)
1173{
1174 int i = 0;
1175 stmt_ty st;
1176
1177 if (!asdl_seq_LEN(stmts))
1178 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001179 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001180 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1181 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182 i = 1;
1183 VISIT(c, expr, st->v.Expr.value);
1184 if (!compiler_nameop(c, __doc__, Store))
1185 return 0;
1186 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001187 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001188 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 return 1;
1190}
1191
1192static PyCodeObject *
1193compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001194{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001195 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001196 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 static PyObject *module;
1198 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001199 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 if (!module)
1201 return NULL;
1202 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001203 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1204 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001205 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 switch (mod->kind) {
1207 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001208 if (!compiler_body(c, mod->v.Module.body)) {
1209 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001211 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 break;
1213 case Interactive_kind:
1214 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001215 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001216 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217 break;
1218 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001219 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001220 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 break;
1222 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001223 PyErr_SetString(PyExc_SystemError,
1224 "suite should not be possible");
1225 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001226 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001227 PyErr_Format(PyExc_SystemError,
1228 "module kind %d should not be possible",
1229 mod->kind);
1230 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001231 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001232 co = assemble(c, addNone);
1233 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001234 return co;
1235}
1236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001237/* The test for LOCAL must come before the test for FREE in order to
1238 handle classes where name is both local and free. The local var is
1239 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001240*/
1241
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242static int
1243get_ref_type(struct compiler *c, PyObject *name)
1244{
1245 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001246 if (scope == 0) {
1247 char buf[350];
1248 PyOS_snprintf(buf, sizeof(buf),
1249 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001250 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001251 PyBytes_AS_STRING(name),
1252 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001253 PyObject_REPR(c->u->u_ste->ste_id),
1254 c->c_filename,
1255 PyObject_REPR(c->u->u_ste->ste_symbols),
1256 PyObject_REPR(c->u->u_varnames),
1257 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 Py_FatalError(buf);
1260 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001261
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001262 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263}
1264
1265static int
1266compiler_lookup_arg(PyObject *dict, PyObject *name)
1267{
1268 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001269 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001271 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001273 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001275 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001276 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279static int
1280compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1281{
1282 int i, free = PyCode_GetNumFree(co);
1283 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001284 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1285 ADDOP_I(c, MAKE_FUNCTION, args);
1286 return 1;
1287 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288 for (i = 0; i < free; ++i) {
1289 /* Bypass com_addop_varname because it will generate
1290 LOAD_DEREF but LOAD_CLOSURE is needed.
1291 */
1292 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1293 int arg, reftype;
1294
1295 /* Special case: If a class contains a method with a
1296 free variable that has the same name as a method,
1297 the name will be considered free *and* local in the
1298 class. It should be handled by the closure, as
1299 well as by the normal name loookup logic.
1300 */
1301 reftype = get_ref_type(c, name);
1302 if (reftype == CELL)
1303 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1304 else /* (reftype == FREE) */
1305 arg = compiler_lookup_arg(c->u->u_freevars, name);
1306 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001307 fprintf(stderr,
1308 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309 "freevars of %s: %s\n",
1310 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001311 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001313 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314 PyObject_REPR(co->co_freevars));
1315 Py_FatalError("compiler_make_closure()");
1316 }
1317 ADDOP_I(c, LOAD_CLOSURE, arg);
1318 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001319 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001321 ADDOP_I(c, MAKE_CLOSURE, args);
1322 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323}
1324
1325static int
1326compiler_decorators(struct compiler *c, asdl_seq* decos)
1327{
1328 int i;
1329
1330 if (!decos)
1331 return 1;
1332
1333 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001334 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 }
1336 return 1;
1337}
1338
1339static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001340compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1341 asdl_seq *kw_defaults)
1342{
1343 int i, default_count = 0;
1344 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001345 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001346 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1347 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001348 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001349 if (!compiler_visit_expr(c, default_)) {
1350 return -1;
1351 }
1352 default_count++;
1353 }
1354 }
1355 return default_count;
1356}
1357
1358static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001359compiler_visit_argannotation(struct compiler *c, identifier id,
1360 expr_ty annotation, PyObject *names)
1361{
1362 if (annotation) {
1363 VISIT(c, expr, annotation);
1364 if (PyList_Append(names, id))
1365 return -1;
1366 }
1367 return 0;
1368}
1369
1370static int
1371compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1372 PyObject *names)
1373{
1374 int i, error;
1375 for (i = 0; i < asdl_seq_LEN(args); i++) {
1376 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001377 error = compiler_visit_argannotation(
1378 c,
1379 arg->arg,
1380 arg->annotation,
1381 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001382 if (error)
1383 return error;
1384 }
1385 return 0;
1386}
1387
1388static int
1389compiler_visit_annotations(struct compiler *c, arguments_ty args,
1390 expr_ty returns)
1391{
Guido van Rossum0240b922007-02-26 21:23:50 +00001392 /* Push arg annotations and a list of the argument names. Return the #
1393 of items pushed. The expressions are evaluated out-of-order wrt the
1394 source code.
1395
1396 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1397 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001398 static identifier return_str;
1399 PyObject *names;
1400 int len;
1401 names = PyList_New(0);
1402 if (!names)
1403 return -1;
1404
1405 if (compiler_visit_argannotations(c, args->args, names))
1406 goto error;
1407 if (args->varargannotation &&
1408 compiler_visit_argannotation(c, args->vararg,
1409 args->varargannotation, names))
1410 goto error;
1411 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1412 goto error;
1413 if (args->kwargannotation &&
1414 compiler_visit_argannotation(c, args->kwarg,
1415 args->kwargannotation, names))
1416 goto error;
1417
1418 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001419 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001420 if (!return_str)
1421 goto error;
1422 }
1423 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1424 goto error;
1425 }
1426
1427 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001428 if (len > 65534) {
1429 /* len must fit in 16 bits, and len is incremented below */
1430 PyErr_SetString(PyExc_SyntaxError,
1431 "too many annotations");
1432 goto error;
1433 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001434 if (len) {
1435 /* convert names to a tuple and place on stack */
1436 PyObject *elt;
1437 int i;
1438 PyObject *s = PyTuple_New(len);
1439 if (!s)
1440 goto error;
1441 for (i = 0; i < len; i++) {
1442 elt = PyList_GET_ITEM(names, i);
1443 Py_INCREF(elt);
1444 PyTuple_SET_ITEM(s, i, elt);
1445 }
1446 ADDOP_O(c, LOAD_CONST, s, consts);
1447 Py_DECREF(s);
1448 len++; /* include the just-pushed tuple */
1449 }
1450 Py_DECREF(names);
1451 return len;
1452
1453error:
1454 Py_DECREF(names);
1455 return -1;
1456}
1457
1458static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459compiler_function(struct compiler *c, stmt_ty s)
1460{
1461 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001462 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001464 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001465 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001466 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001467 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001468 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469
1470 assert(s->kind == FunctionDef_kind);
1471
1472 if (!compiler_decorators(c, decos))
1473 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001474 if (args->kwonlyargs) {
1475 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1476 args->kw_defaults);
1477 if (res < 0)
1478 return 0;
1479 kw_default_count = res;
1480 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481 if (args->defaults)
1482 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001483 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001484 if (num_annotations < 0)
1485 return 0;
1486 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001487
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1489 s->lineno))
1490 return 0;
1491
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001492 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001493 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001494 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001495 first_const = st->v.Expr.value->v.Str.s;
1496 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001497 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001498 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001502 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001504 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001506 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1507 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508 }
1509 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001510 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511 if (co == NULL)
1512 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513
Guido van Rossum4f72a782006-10-27 23:31:49 +00001514 arglength = asdl_seq_LEN(args->defaults);
1515 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001516 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001517 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001518 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519
Neal Norwitzc1505362006-12-28 06:47:50 +00001520 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1522 ADDOP_I(c, CALL_FUNCTION, 1);
1523 }
1524
1525 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1526}
1527
1528static int
1529compiler_class(struct compiler *c, stmt_ty s)
1530{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001532 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001533 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001534 asdl_seq* decos = s->v.ClassDef.decorator_list;
1535
1536 if (!compiler_decorators(c, decos))
1537 return 0;
1538
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001539 /* ultimately generate code for:
1540 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1541 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001542 <func> is a function/closure created from the class body;
1543 it has a single argument (__locals__) where the dict
1544 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001545 <name> is the class name
1546 <bases> is the positional arguments and *varargs argument
1547 <keywords> is the keyword arguments and **kwds argument
1548 This borrows from compiler_call.
1549 */
1550
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001551 /* 1. compile the class body into a code object */
1552 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1553 return 0;
1554 /* this block represents what we do in the new scope */
1555 {
1556 /* use the class name for name mangling */
1557 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001558 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001559 c->u->u_private = s->v.ClassDef.name;
1560 /* force it to have one mandatory argument */
1561 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001562 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001563 ADDOP_I(c, LOAD_FAST, 0);
1564 /* ... and store it into f_locals */
1565 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001566 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001567 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001568 if (!str || !compiler_nameop(c, str, Load)) {
1569 Py_XDECREF(str);
1570 compiler_exit_scope(c);
1571 return 0;
1572 }
1573 Py_DECREF(str);
1574 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001575 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001576 if (!str || !compiler_nameop(c, str, Store)) {
1577 Py_XDECREF(str);
1578 compiler_exit_scope(c);
1579 return 0;
1580 }
1581 Py_DECREF(str);
1582 /* compile the body proper */
1583 if (!compiler_body(c, s->v.ClassDef.body)) {
1584 compiler_exit_scope(c);
1585 return 0;
1586 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001587 /* return the (empty) __class__ cell */
1588 str = PyUnicode_InternFromString("__class__");
1589 if (str == NULL) {
1590 compiler_exit_scope(c);
1591 return 0;
1592 }
1593 i = compiler_lookup_arg(c->u->u_cellvars, str);
1594 Py_DECREF(str);
1595 if (i == -1) {
1596 /* This happens when nobody references the cell */
1597 PyErr_Clear();
1598 /* Return None */
1599 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1600 }
1601 else {
1602 /* Return the cell where to store __class__ */
1603 ADDOP_I(c, LOAD_CLOSURE, i);
1604 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001605 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1606 /* create the code object */
1607 co = assemble(c, 1);
1608 }
1609 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001610 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611 if (co == NULL)
1612 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001613
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001614 /* 2. load the 'build_class' function */
1615 ADDOP(c, LOAD_BUILD_CLASS);
1616
1617 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001618 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001619 Py_DECREF(co);
1620
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001621 /* 4. load class name */
1622 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1623
1624 /* 5. generate the rest of the code for the call */
1625 if (!compiler_call_helper(c, 2,
1626 s->v.ClassDef.bases,
1627 s->v.ClassDef.keywords,
1628 s->v.ClassDef.starargs,
1629 s->v.ClassDef.kwargs))
1630 return 0;
1631
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001632 /* 6. apply decorators */
1633 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1634 ADDOP_I(c, CALL_FUNCTION, 1);
1635 }
1636
1637 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1639 return 0;
1640 return 1;
1641}
1642
1643static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001644compiler_ifexp(struct compiler *c, expr_ty e)
1645{
1646 basicblock *end, *next;
1647
1648 assert(e->kind == IfExp_kind);
1649 end = compiler_new_block(c);
1650 if (end == NULL)
1651 return 0;
1652 next = compiler_new_block(c);
1653 if (next == NULL)
1654 return 0;
1655 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001656 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001657 VISIT(c, expr, e->v.IfExp.body);
1658 ADDOP_JREL(c, JUMP_FORWARD, end);
1659 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001660 VISIT(c, expr, e->v.IfExp.orelse);
1661 compiler_use_next_block(c, end);
1662 return 1;
1663}
1664
1665static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001666compiler_lambda(struct compiler *c, expr_ty e)
1667{
1668 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001669 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001670 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001671 arguments_ty args = e->v.Lambda.args;
1672 assert(e->kind == Lambda_kind);
1673
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001674 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001675 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001676 if (!name)
1677 return 0;
1678 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679
Guido van Rossum4f72a782006-10-27 23:31:49 +00001680 if (args->kwonlyargs) {
1681 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1682 args->kw_defaults);
1683 if (res < 0) return 0;
1684 kw_default_count = res;
1685 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686 if (args->defaults)
1687 VISIT_SEQ(c, expr, args->defaults);
1688 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1689 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001690
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001692 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001693 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001694 if (c->u->u_ste->ste_generator) {
1695 ADDOP_IN_SCOPE(c, POP_TOP);
1696 }
1697 else {
1698 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1699 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001701 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702 if (co == NULL)
1703 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704
Guido van Rossum4f72a782006-10-27 23:31:49 +00001705 arglength = asdl_seq_LEN(args->defaults);
1706 arglength |= kw_default_count << 8;
1707 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001708 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001709
1710 return 1;
1711}
1712
1713static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714compiler_if(struct compiler *c, stmt_ty s)
1715{
1716 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001717 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001718 assert(s->kind == If_kind);
1719 end = compiler_new_block(c);
1720 if (end == NULL)
1721 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001722
1723 constant = expr_constant(s->v.If.test);
1724 /* constant = 0: "if 0"
1725 * constant = 1: "if 1", "if 2", ...
1726 * constant = -1: rest */
1727 if (constant == 0) {
1728 if (s->v.If.orelse)
1729 VISIT_SEQ(c, stmt, s->v.If.orelse);
1730 } else if (constant == 1) {
1731 VISIT_SEQ(c, stmt, s->v.If.body);
1732 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001733 if (s->v.If.orelse) {
1734 next = compiler_new_block(c);
1735 if (next == NULL)
1736 return 0;
1737 }
1738 else
1739 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001740 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001741 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001742 VISIT_SEQ(c, stmt, s->v.If.body);
1743 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001744 if (s->v.If.orelse) {
1745 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001746 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001747 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001748 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001749 compiler_use_next_block(c, end);
1750 return 1;
1751}
1752
1753static int
1754compiler_for(struct compiler *c, stmt_ty s)
1755{
1756 basicblock *start, *cleanup, *end;
1757
1758 start = compiler_new_block(c);
1759 cleanup = compiler_new_block(c);
1760 end = compiler_new_block(c);
1761 if (start == NULL || end == NULL || cleanup == NULL)
1762 return 0;
1763 ADDOP_JREL(c, SETUP_LOOP, end);
1764 if (!compiler_push_fblock(c, LOOP, start))
1765 return 0;
1766 VISIT(c, expr, s->v.For.iter);
1767 ADDOP(c, GET_ITER);
1768 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001769 /* for expressions must be traced on each iteration,
1770 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001771 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 ADDOP_JREL(c, FOR_ITER, cleanup);
1773 VISIT(c, expr, s->v.For.target);
1774 VISIT_SEQ(c, stmt, s->v.For.body);
1775 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1776 compiler_use_next_block(c, cleanup);
1777 ADDOP(c, POP_BLOCK);
1778 compiler_pop_fblock(c, LOOP, start);
1779 VISIT_SEQ(c, stmt, s->v.For.orelse);
1780 compiler_use_next_block(c, end);
1781 return 1;
1782}
1783
1784static int
1785compiler_while(struct compiler *c, stmt_ty s)
1786{
1787 basicblock *loop, *orelse, *end, *anchor = NULL;
1788 int constant = expr_constant(s->v.While.test);
1789
Christian Heimes969fe572008-01-25 11:23:10 +00001790 if (constant == 0) {
1791 if (s->v.While.orelse)
1792 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001794 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795 loop = compiler_new_block(c);
1796 end = compiler_new_block(c);
1797 if (constant == -1) {
1798 anchor = compiler_new_block(c);
1799 if (anchor == NULL)
1800 return 0;
1801 }
1802 if (loop == NULL || end == NULL)
1803 return 0;
1804 if (s->v.While.orelse) {
1805 orelse = compiler_new_block(c);
1806 if (orelse == NULL)
1807 return 0;
1808 }
1809 else
1810 orelse = NULL;
1811
1812 ADDOP_JREL(c, SETUP_LOOP, end);
1813 compiler_use_next_block(c, loop);
1814 if (!compiler_push_fblock(c, LOOP, loop))
1815 return 0;
1816 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001817 /* while expressions must be traced on each iteration,
1818 so we need to set an extra line number. */
1819 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001821 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822 }
1823 VISIT_SEQ(c, stmt, s->v.While.body);
1824 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1825
1826 /* XXX should the two POP instructions be in a separate block
1827 if there is no else clause ?
1828 */
1829
1830 if (constant == -1) {
1831 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 ADDOP(c, POP_BLOCK);
1833 }
1834 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001835 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 VISIT_SEQ(c, stmt, s->v.While.orelse);
1837 compiler_use_next_block(c, end);
1838
1839 return 1;
1840}
1841
1842static int
1843compiler_continue(struct compiler *c)
1844{
1845 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001846 static const char IN_FINALLY_ERROR_MSG[] =
1847 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848 int i;
1849
1850 if (!c->u->u_nfblocks)
1851 return compiler_error(c, LOOP_ERROR_MSG);
1852 i = c->u->u_nfblocks - 1;
1853 switch (c->u->u_fblock[i].fb_type) {
1854 case LOOP:
1855 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1856 break;
1857 case EXCEPT:
1858 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001859 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1860 /* Prevent continue anywhere under a finally
1861 even if hidden in a sub-try or except. */
1862 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1863 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1864 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 if (i == -1)
1866 return compiler_error(c, LOOP_ERROR_MSG);
1867 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1868 break;
1869 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001870 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871 }
1872
1873 return 1;
1874}
1875
1876/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1877
1878 SETUP_FINALLY L
1879 <code for body>
1880 POP_BLOCK
1881 LOAD_CONST <None>
1882 L: <code for finalbody>
1883 END_FINALLY
1884
1885 The special instructions use the block stack. Each block
1886 stack entry contains the instruction that created it (here
1887 SETUP_FINALLY), the level of the value stack at the time the
1888 block stack entry was created, and a label (here L).
1889
1890 SETUP_FINALLY:
1891 Pushes the current value stack level and the label
1892 onto the block stack.
1893 POP_BLOCK:
1894 Pops en entry from the block stack, and pops the value
1895 stack until its level is the same as indicated on the
1896 block stack. (The label is ignored.)
1897 END_FINALLY:
1898 Pops a variable number of entries from the *value* stack
1899 and re-raises the exception they specify. The number of
1900 entries popped depends on the (pseudo) exception type.
1901
1902 The block stack is unwound when an exception is raised:
1903 when a SETUP_FINALLY entry is found, the exception is pushed
1904 onto the value stack (and the exception condition is cleared),
1905 and the interpreter jumps to the label gotten from the block
1906 stack.
1907*/
1908
1909static int
1910compiler_try_finally(struct compiler *c, stmt_ty s)
1911{
1912 basicblock *body, *end;
1913 body = compiler_new_block(c);
1914 end = compiler_new_block(c);
1915 if (body == NULL || end == NULL)
1916 return 0;
1917
1918 ADDOP_JREL(c, SETUP_FINALLY, end);
1919 compiler_use_next_block(c, body);
1920 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1921 return 0;
1922 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1923 ADDOP(c, POP_BLOCK);
1924 compiler_pop_fblock(c, FINALLY_TRY, body);
1925
1926 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1927 compiler_use_next_block(c, end);
1928 if (!compiler_push_fblock(c, FINALLY_END, end))
1929 return 0;
1930 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1931 ADDOP(c, END_FINALLY);
1932 compiler_pop_fblock(c, FINALLY_END, end);
1933
1934 return 1;
1935}
1936
1937/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001938 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939 (The contents of the value stack is shown in [], with the top
1940 at the right; 'tb' is trace-back info, 'val' the exception's
1941 associated value, and 'exc' the exception.)
1942
1943 Value stack Label Instruction Argument
1944 [] SETUP_EXCEPT L1
1945 [] <code for S>
1946 [] POP_BLOCK
1947 [] JUMP_FORWARD L0
1948
1949 [tb, val, exc] L1: DUP )
1950 [tb, val, exc, exc] <evaluate E1> )
1951 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001952 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953 [tb, val, exc] POP
1954 [tb, val] <assign to V1> (or POP if no V1)
1955 [tb] POP
1956 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001957 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001959 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 .............................etc.......................
1961
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001962 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963
1964 [] L0: <next statement>
1965
1966 Of course, parts are not generated if Vi or Ei is not present.
1967*/
1968static int
1969compiler_try_except(struct compiler *c, stmt_ty s)
1970{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001971 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972 int i, n;
1973
1974 body = compiler_new_block(c);
1975 except = compiler_new_block(c);
1976 orelse = compiler_new_block(c);
1977 end = compiler_new_block(c);
1978 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1979 return 0;
1980 ADDOP_JREL(c, SETUP_EXCEPT, except);
1981 compiler_use_next_block(c, body);
1982 if (!compiler_push_fblock(c, EXCEPT, body))
1983 return 0;
1984 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1985 ADDOP(c, POP_BLOCK);
1986 compiler_pop_fblock(c, EXCEPT, body);
1987 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1988 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1989 compiler_use_next_block(c, except);
1990 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001991 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001993 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001995 c->u->u_lineno_set = 0;
1996 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 except = compiler_new_block(c);
1998 if (except == NULL)
1999 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002000 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002002 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002003 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002004 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005 }
2006 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002007 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00002008 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002009
2010 cleanup_end = compiler_new_block(c);
2011 cleanup_body = compiler_new_block(c);
2012 if(!(cleanup_end || cleanup_body))
2013 return 0;
2014
Neal Norwitzad74aa82008-03-31 05:14:30 +00002015 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002016 ADDOP(c, POP_TOP);
2017
2018 /*
2019 try:
2020 # body
2021 except type as name:
2022 try:
2023 # body
2024 finally:
2025 name = None
2026 del name
2027 */
2028
2029 /* second try: */
2030 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2031 compiler_use_next_block(c, cleanup_body);
2032 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2033 return 0;
2034
2035 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002036 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002037 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002038 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002039 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2040
2041 /* finally: */
2042 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2043 compiler_use_next_block(c, cleanup_end);
2044 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2045 return 0;
2046
2047 /* name = None */
2048 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002049 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002050
Guido van Rossum16be03e2007-01-10 18:51:35 +00002051 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002052 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002053
2054 ADDOP(c, END_FINALLY);
2055 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056 }
2057 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002058 basicblock *cleanup_body;
2059
2060 cleanup_body = compiler_new_block(c);
2061 if(!cleanup_body)
2062 return 0;
2063
2064 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002065 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002066 compiler_use_next_block(c, cleanup_body);
2067 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2068 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002069 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002070 ADDOP(c, POP_EXCEPT);
2071 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 ADDOP_JREL(c, JUMP_FORWARD, end);
2074 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 }
2076 ADDOP(c, END_FINALLY);
2077 compiler_use_next_block(c, orelse);
2078 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2079 compiler_use_next_block(c, end);
2080 return 1;
2081}
2082
2083static int
2084compiler_import_as(struct compiler *c, identifier name, identifier asname)
2085{
2086 /* The IMPORT_NAME opcode was already generated. This function
2087 merely needs to bind the result to a name.
2088
2089 If there is a dot in name, we need to split it and emit a
2090 LOAD_ATTR for each name.
2091 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002092 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2093 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 if (dot) {
2095 /* Consume the base module name to get the first attribute */
2096 src = dot + 1;
2097 while (dot) {
2098 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002099 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002100 dot = Py_UNICODE_strchr(src, '.');
2101 attr = PyUnicode_FromUnicode(src,
2102 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002103 if (!attr)
2104 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002105 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002106 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 src = dot + 1;
2108 }
2109 }
2110 return compiler_nameop(c, asname, Store);
2111}
2112
2113static int
2114compiler_import(struct compiler *c, stmt_ty s)
2115{
2116 /* The Import node stores a module name like a.b.c as a single
2117 string. This is convenient for all cases except
2118 import a.b.c as d
2119 where we need to parse that string to extract the individual
2120 module names.
2121 XXX Perhaps change the representation to make this case simpler?
2122 */
2123 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002124
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002126 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002128 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129
Christian Heimes217cfd12007-12-02 14:31:20 +00002130 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002131 if (level == NULL)
2132 return 0;
2133
2134 ADDOP_O(c, LOAD_CONST, level, consts);
2135 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2137 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2138
2139 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002140 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002141 if (!r)
2142 return r;
2143 }
2144 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002146 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2147 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002149 tmp = PyUnicode_FromUnicode(base,
2150 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151 r = compiler_nameop(c, tmp, Store);
2152 if (dot) {
2153 Py_DECREF(tmp);
2154 }
2155 if (!r)
2156 return r;
2157 }
2158 }
2159 return 1;
2160}
2161
2162static int
2163compiler_from_import(struct compiler *c, stmt_ty s)
2164{
2165 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166
2167 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002168 PyObject *level;
2169
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 if (!names)
2171 return 0;
2172
Christian Heimes217cfd12007-12-02 14:31:20 +00002173 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002174 if (!level) {
2175 Py_DECREF(names);
2176 return 0;
2177 }
2178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179 /* build up the names */
2180 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002181 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182 Py_INCREF(alias->name);
2183 PyTuple_SET_ITEM(names, i, alias->name);
2184 }
2185
2186 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002187 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2188 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002189 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 Py_DECREF(names);
2191 return compiler_error(c,
2192 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002193 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194
2195 }
2196 }
2197
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002198 ADDOP_O(c, LOAD_CONST, level, consts);
2199 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002201 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2203 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002204 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205 identifier store_name;
2206
Martin v. Löwis5b222132007-06-10 09:51:05 +00002207 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208 assert(n == 1);
2209 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002210 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211 }
2212
2213 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2214 store_name = alias->name;
2215 if (alias->asname)
2216 store_name = alias->asname;
2217
2218 if (!compiler_nameop(c, store_name, Store)) {
2219 Py_DECREF(names);
2220 return 0;
2221 }
2222 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002223 /* remove imported module */
2224 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225 return 1;
2226}
2227
2228static int
2229compiler_assert(struct compiler *c, stmt_ty s)
2230{
2231 static PyObject *assertion_error = NULL;
2232 basicblock *end;
2233
2234 if (Py_OptimizeFlag)
2235 return 1;
2236 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002237 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 if (assertion_error == NULL)
2239 return 0;
2240 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002241 if (s->v.Assert.test->kind == Tuple_kind &&
2242 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2243 const char* msg =
2244 "assertion is always true, perhaps remove parentheses?";
2245 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2246 c->u->u_lineno, NULL, NULL) == -1)
2247 return 0;
2248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249 VISIT(c, expr, s->v.Assert.test);
2250 end = compiler_new_block(c);
2251 if (end == NULL)
2252 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002253 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2255 if (s->v.Assert.msg) {
2256 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002257 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 }
Collin Winter828f04a2007-08-31 00:04:24 +00002259 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002260 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 return 1;
2262}
2263
2264static int
2265compiler_visit_stmt(struct compiler *c, stmt_ty s)
2266{
2267 int i, n;
2268
Thomas Wouters89f507f2006-12-13 04:49:30 +00002269 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002271 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002272
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002274 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002276 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002278 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 if (c->u->u_ste->ste_type != FunctionBlock)
2280 return compiler_error(c, "'return' outside function");
2281 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 VISIT(c, expr, s->v.Return.value);
2283 }
2284 else
2285 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2286 ADDOP(c, RETURN_VALUE);
2287 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002288 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289 VISIT_SEQ(c, expr, s->v.Delete.targets)
2290 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 n = asdl_seq_LEN(s->v.Assign.targets);
2293 VISIT(c, expr, s->v.Assign.value);
2294 for (i = 0; i < n; i++) {
2295 if (i < n - 1)
2296 ADDOP(c, DUP_TOP);
2297 VISIT(c, expr,
2298 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2299 }
2300 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002301 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002303 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002305 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002307 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002309 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002311 if (s->v.Raise.exc) {
2312 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002314 if (s->v.Raise.cause) {
2315 VISIT(c, expr, s->v.Raise.cause);
2316 n++;
2317 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 }
2319 ADDOP_I(c, RAISE_VARARGS, n);
2320 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002321 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002323 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002325 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002326 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002327 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002329 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002331 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002332 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002334 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002336 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 ADDOP(c, PRINT_EXPR);
2338 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002339 else if (s->v.Expr.value->kind != Str_kind &&
2340 s->v.Expr.value->kind != Num_kind) {
2341 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342 ADDOP(c, POP_TOP);
2343 }
2344 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002345 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002346 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002347 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002348 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 return compiler_error(c, "'break' outside loop");
2350 ADDOP(c, BREAK_LOOP);
2351 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002352 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002354 case With_kind:
2355 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356 }
2357 return 1;
2358}
2359
2360static int
2361unaryop(unaryop_ty op)
2362{
2363 switch (op) {
2364 case Invert:
2365 return UNARY_INVERT;
2366 case Not:
2367 return UNARY_NOT;
2368 case UAdd:
2369 return UNARY_POSITIVE;
2370 case USub:
2371 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002372 default:
2373 PyErr_Format(PyExc_SystemError,
2374 "unary op %d should not be possible", op);
2375 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377}
2378
2379static int
2380binop(struct compiler *c, operator_ty op)
2381{
2382 switch (op) {
2383 case Add:
2384 return BINARY_ADD;
2385 case Sub:
2386 return BINARY_SUBTRACT;
2387 case Mult:
2388 return BINARY_MULTIPLY;
2389 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002390 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391 case Mod:
2392 return BINARY_MODULO;
2393 case Pow:
2394 return BINARY_POWER;
2395 case LShift:
2396 return BINARY_LSHIFT;
2397 case RShift:
2398 return BINARY_RSHIFT;
2399 case BitOr:
2400 return BINARY_OR;
2401 case BitXor:
2402 return BINARY_XOR;
2403 case BitAnd:
2404 return BINARY_AND;
2405 case FloorDiv:
2406 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002407 default:
2408 PyErr_Format(PyExc_SystemError,
2409 "binary op %d should not be possible", op);
2410 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412}
2413
2414static int
2415cmpop(cmpop_ty op)
2416{
2417 switch (op) {
2418 case Eq:
2419 return PyCmp_EQ;
2420 case NotEq:
2421 return PyCmp_NE;
2422 case Lt:
2423 return PyCmp_LT;
2424 case LtE:
2425 return PyCmp_LE;
2426 case Gt:
2427 return PyCmp_GT;
2428 case GtE:
2429 return PyCmp_GE;
2430 case Is:
2431 return PyCmp_IS;
2432 case IsNot:
2433 return PyCmp_IS_NOT;
2434 case In:
2435 return PyCmp_IN;
2436 case NotIn:
2437 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002438 default:
2439 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441}
2442
2443static int
2444inplace_binop(struct compiler *c, operator_ty op)
2445{
2446 switch (op) {
2447 case Add:
2448 return INPLACE_ADD;
2449 case Sub:
2450 return INPLACE_SUBTRACT;
2451 case Mult:
2452 return INPLACE_MULTIPLY;
2453 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002454 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 case Mod:
2456 return INPLACE_MODULO;
2457 case Pow:
2458 return INPLACE_POWER;
2459 case LShift:
2460 return INPLACE_LSHIFT;
2461 case RShift:
2462 return INPLACE_RSHIFT;
2463 case BitOr:
2464 return INPLACE_OR;
2465 case BitXor:
2466 return INPLACE_XOR;
2467 case BitAnd:
2468 return INPLACE_AND;
2469 case FloorDiv:
2470 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002471 default:
2472 PyErr_Format(PyExc_SystemError,
2473 "inplace binary op %d should not be possible", op);
2474 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476}
2477
2478static int
2479compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2480{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002481 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2483
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002484 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002485 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 /* XXX AugStore isn't used anywhere! */
2487
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002488 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002489 if (!mangled)
2490 return 0;
2491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002492 op = 0;
2493 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002494 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495 switch (scope) {
2496 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002497 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498 optype = OP_DEREF;
2499 break;
2500 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002501 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002502 optype = OP_DEREF;
2503 break;
2504 case LOCAL:
2505 if (c->u->u_ste->ste_type == FunctionBlock)
2506 optype = OP_FAST;
2507 break;
2508 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002509 if (c->u->u_ste->ste_type == FunctionBlock &&
2510 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 optype = OP_GLOBAL;
2512 break;
2513 case GLOBAL_EXPLICIT:
2514 optype = OP_GLOBAL;
2515 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002516 default:
2517 /* scope can be 0 */
2518 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519 }
2520
2521 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002522 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
2524 switch (optype) {
2525 case OP_DEREF:
2526 switch (ctx) {
2527 case Load: op = LOAD_DEREF; break;
2528 case Store: op = STORE_DEREF; break;
2529 case AugLoad:
2530 case AugStore:
2531 break;
2532 case Del:
2533 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002534 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002536 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002537 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002540 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002541 PyErr_SetString(PyExc_SystemError,
2542 "param invalid for deref variable");
2543 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544 }
2545 break;
2546 case OP_FAST:
2547 switch (ctx) {
2548 case Load: op = LOAD_FAST; break;
2549 case Store: op = STORE_FAST; break;
2550 case Del: op = DELETE_FAST; break;
2551 case AugLoad:
2552 case AugStore:
2553 break;
2554 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002555 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002556 PyErr_SetString(PyExc_SystemError,
2557 "param invalid for local variable");
2558 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002560 ADDOP_O(c, op, mangled, varnames);
2561 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 return 1;
2563 case OP_GLOBAL:
2564 switch (ctx) {
2565 case Load: op = LOAD_GLOBAL; break;
2566 case Store: op = STORE_GLOBAL; break;
2567 case Del: op = DELETE_GLOBAL; break;
2568 case AugLoad:
2569 case AugStore:
2570 break;
2571 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002572 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002573 PyErr_SetString(PyExc_SystemError,
2574 "param invalid for global variable");
2575 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576 }
2577 break;
2578 case OP_NAME:
2579 switch (ctx) {
2580 case Load: op = LOAD_NAME; break;
2581 case Store: op = STORE_NAME; break;
2582 case Del: op = DELETE_NAME; break;
2583 case AugLoad:
2584 case AugStore:
2585 break;
2586 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002587 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002588 PyErr_SetString(PyExc_SystemError,
2589 "param invalid for name variable");
2590 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591 }
2592 break;
2593 }
2594
2595 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002596 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002597 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002598 if (arg < 0)
2599 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002600 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601}
2602
2603static int
2604compiler_boolop(struct compiler *c, expr_ty e)
2605{
2606 basicblock *end;
2607 int jumpi, i, n;
2608 asdl_seq *s;
2609
2610 assert(e->kind == BoolOp_kind);
2611 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002612 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002614 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002616 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 return 0;
2618 s = e->v.BoolOp.values;
2619 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002620 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002622 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002623 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002625 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 compiler_use_next_block(c, end);
2627 return 1;
2628}
2629
2630static int
2631compiler_list(struct compiler *c, expr_ty e)
2632{
2633 int n = asdl_seq_LEN(e->v.List.elts);
2634 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002635 int i, seen_star = 0;
2636 for (i = 0; i < n; i++) {
2637 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2638 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002639 if ((i >= (1 << 8)) ||
2640 (n-i-1 >= (INT_MAX >> 8)))
2641 return compiler_error(c,
2642 "too many expressions in "
2643 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002644 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2645 seen_star = 1;
2646 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2647 } else if (elt->kind == Starred_kind) {
2648 return compiler_error(c,
2649 "two starred expressions in assignment");
2650 }
2651 }
2652 if (!seen_star) {
2653 ADDOP_I(c, UNPACK_SEQUENCE, n);
2654 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655 }
2656 VISIT_SEQ(c, expr, e->v.List.elts);
2657 if (e->v.List.ctx == Load) {
2658 ADDOP_I(c, BUILD_LIST, n);
2659 }
2660 return 1;
2661}
2662
2663static int
2664compiler_tuple(struct compiler *c, expr_ty e)
2665{
2666 int n = asdl_seq_LEN(e->v.Tuple.elts);
2667 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002668 int i, seen_star = 0;
2669 for (i = 0; i < n; i++) {
2670 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2671 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002672 if ((i >= (1 << 8)) ||
2673 (n-i-1 >= (INT_MAX >> 8)))
2674 return compiler_error(c,
2675 "too many expressions in "
2676 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002677 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2678 seen_star = 1;
2679 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2680 } else if (elt->kind == Starred_kind) {
2681 return compiler_error(c,
2682 "two starred expressions in assignment");
2683 }
2684 }
2685 if (!seen_star) {
2686 ADDOP_I(c, UNPACK_SEQUENCE, n);
2687 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 }
2689 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2690 if (e->v.Tuple.ctx == Load) {
2691 ADDOP_I(c, BUILD_TUPLE, n);
2692 }
2693 return 1;
2694}
2695
2696static int
2697compiler_compare(struct compiler *c, expr_ty e)
2698{
2699 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
2702 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2703 VISIT(c, expr, e->v.Compare.left);
2704 n = asdl_seq_LEN(e->v.Compare.ops);
2705 assert(n > 0);
2706 if (n > 1) {
2707 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 if (cleanup == NULL)
2709 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002710 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002711 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 }
2713 for (i = 1; i < n; i++) {
2714 ADDOP(c, DUP_TOP);
2715 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002717 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002718 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002719 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002722 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002723 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002725 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002727 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728 if (n > 1) {
2729 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002730 if (end == NULL)
2731 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 ADDOP_JREL(c, JUMP_FORWARD, end);
2733 compiler_use_next_block(c, cleanup);
2734 ADDOP(c, ROT_TWO);
2735 ADDOP(c, POP_TOP);
2736 compiler_use_next_block(c, end);
2737 }
2738 return 1;
2739}
2740
2741static int
2742compiler_call(struct compiler *c, expr_ty e)
2743{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002745 return compiler_call_helper(c, 0,
2746 e->v.Call.args,
2747 e->v.Call.keywords,
2748 e->v.Call.starargs,
2749 e->v.Call.kwargs);
2750}
2751
2752/* shared code between compiler_call and compiler_class */
2753static int
2754compiler_call_helper(struct compiler *c,
2755 int n, /* Args already pushed */
2756 asdl_seq *args,
2757 asdl_seq *keywords,
2758 expr_ty starargs,
2759 expr_ty kwargs)
2760{
2761 int code = 0;
2762
2763 n += asdl_seq_LEN(args);
2764 VISIT_SEQ(c, expr, args);
2765 if (keywords) {
2766 VISIT_SEQ(c, keyword, keywords);
2767 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002769 if (starargs) {
2770 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771 code |= 1;
2772 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002773 if (kwargs) {
2774 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775 code |= 2;
2776 }
2777 switch (code) {
2778 case 0:
2779 ADDOP_I(c, CALL_FUNCTION, n);
2780 break;
2781 case 1:
2782 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2783 break;
2784 case 2:
2785 ADDOP_I(c, CALL_FUNCTION_KW, n);
2786 break;
2787 case 3:
2788 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2789 break;
2790 }
2791 return 1;
2792}
2793
Nick Coghlan650f0d02007-04-15 12:05:43 +00002794
2795/* List and set comprehensions and generator expressions work by creating a
2796 nested function to perform the actual iteration. This means that the
2797 iteration variables don't leak into the current scope.
2798 The defined function is called immediately following its definition, with the
2799 result of that call being the result of the expression.
2800 The LC/SC version returns the populated container, while the GE version is
2801 flagged in symtable.c as a generator, so it returns the generator object
2802 when the function is called.
2803 This code *knows* that the loop cannot contain break, continue, or return,
2804 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2805
2806 Possible cleanups:
2807 - iterate over the generator sequence instead of using recursion
2808*/
2809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002810static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002811compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002812 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002813 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814{
2815 /* generate code for the iterator, then each of the ifs,
2816 and then write to the element */
2817
Nick Coghlan650f0d02007-04-15 12:05:43 +00002818 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821
2822 start = compiler_new_block(c);
2823 skip = compiler_new_block(c);
2824 if_cleanup = compiler_new_block(c);
2825 anchor = compiler_new_block(c);
2826
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002827 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002828 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830
Nick Coghlan650f0d02007-04-15 12:05:43 +00002831 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833 if (gen_index == 0) {
2834 /* Receive outermost iter as an implicit argument */
2835 c->u->u_argcount = 1;
2836 ADDOP_I(c, LOAD_FAST, 0);
2837 }
2838 else {
2839 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002840 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841 ADDOP(c, GET_ITER);
2842 }
2843 compiler_use_next_block(c, start);
2844 ADDOP_JREL(c, FOR_ITER, anchor);
2845 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002846 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002848 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002849 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002850 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002851 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002853 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002855 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002857 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002858 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002859 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002860 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002861 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862
Nick Coghlan650f0d02007-04-15 12:05:43 +00002863 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002864 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002865 /* comprehension specific code */
2866 switch (type) {
2867 case COMP_GENEXP:
2868 VISIT(c, expr, elt);
2869 ADDOP(c, YIELD_VALUE);
2870 ADDOP(c, POP_TOP);
2871 break;
2872 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002873 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002874 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875 break;
2876 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002877 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002878 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002879 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002880 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002881 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002882 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002883 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002884 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002885 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002886 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002887 default:
2888 return 0;
2889 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890
2891 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002892 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002893 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2895 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896
2897 return 1;
2898}
2899
2900static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002901compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002902 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002903{
2904 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002905 expr_ty outermost_iter;
2906
2907 outermost_iter = ((comprehension_ty)
2908 asdl_seq_GET(generators, 0))->iter;
2909
2910 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2911 goto error;
2912
2913 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002914 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002915 switch (type) {
2916 case COMP_LISTCOMP:
2917 op = BUILD_LIST;
2918 break;
2919 case COMP_SETCOMP:
2920 op = BUILD_SET;
2921 break;
2922 case COMP_DICTCOMP:
2923 op = BUILD_MAP;
2924 break;
2925 default:
2926 PyErr_Format(PyExc_SystemError,
2927 "unknown comprehension type %d", type);
2928 goto error_in_scope;
2929 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002930
Guido van Rossum992d4a32007-07-11 13:09:30 +00002931 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002932 }
2933
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002934 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002935 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002936 goto error_in_scope;
2937
2938 if (type != COMP_GENEXP) {
2939 ADDOP(c, RETURN_VALUE);
2940 }
2941
2942 co = assemble(c, 1);
2943 compiler_exit_scope(c);
2944 if (co == NULL)
2945 goto error;
2946
2947 if (!compiler_make_closure(c, co, 0))
2948 goto error;
2949 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002950
2951 VISIT(c, expr, outermost_iter);
2952 ADDOP(c, GET_ITER);
2953 ADDOP_I(c, CALL_FUNCTION, 1);
2954 return 1;
2955error_in_scope:
2956 compiler_exit_scope(c);
2957error:
2958 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002959 return 0;
2960}
2961
2962static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963compiler_genexp(struct compiler *c, expr_ty e)
2964{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002965 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002966 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002967 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002968 if (!name)
2969 return 0;
2970 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002971 assert(e->kind == GeneratorExp_kind);
2972 return compiler_comprehension(c, e, COMP_GENEXP, name,
2973 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002974 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975}
2976
2977static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002978compiler_listcomp(struct compiler *c, expr_ty e)
2979{
2980 static identifier name;
2981 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002982 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002983 if (!name)
2984 return 0;
2985 }
2986 assert(e->kind == ListComp_kind);
2987 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2988 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002989 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002990}
2991
2992static int
2993compiler_setcomp(struct compiler *c, expr_ty e)
2994{
2995 static identifier name;
2996 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002997 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002998 if (!name)
2999 return 0;
3000 }
3001 assert(e->kind == SetComp_kind);
3002 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3003 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00003004 e->v.SetComp.elt, NULL);
3005}
3006
3007
3008static int
3009compiler_dictcomp(struct compiler *c, expr_ty e)
3010{
3011 static identifier name;
3012 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003013 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003014 if (!name)
3015 return 0;
3016 }
3017 assert(e->kind == DictComp_kind);
3018 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3019 e->v.DictComp.generators,
3020 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003021}
3022
3023
3024static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025compiler_visit_keyword(struct compiler *c, keyword_ty k)
3026{
3027 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3028 VISIT(c, expr, k->value);
3029 return 1;
3030}
3031
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003032/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 whether they are true or false.
3034
3035 Return values: 1 for true, 0 for false, -1 for non-constant.
3036 */
3037
3038static int
3039expr_constant(expr_ty e)
3040{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003041 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003043 case Ellipsis_kind:
3044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 case Num_kind:
3046 return PyObject_IsTrue(e->v.Num.n);
3047 case Str_kind:
3048 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003049 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003050 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003051 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003052 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003053 if (strcmp(id, "True") == 0) return 1;
3054 if (strcmp(id, "False") == 0) return 0;
3055 if (strcmp(id, "None") == 0) return 0;
3056 if (strcmp(id, "__debug__") == 0)
3057 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003058 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059 default:
3060 return -1;
3061 }
3062}
3063
Guido van Rossumc2e20742006-02-27 22:32:47 +00003064/*
3065 Implements the with statement from PEP 343.
3066
3067 The semantics outlined in that PEP are as follows:
3068
3069 with EXPR as VAR:
3070 BLOCK
3071
3072 It is implemented roughly as:
3073
Thomas Wouters477c8d52006-05-27 19:21:47 +00003074 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075 exit = context.__exit__ # not calling it
3076 value = context.__enter__()
3077 try:
3078 VAR = value # if VAR present in the syntax
3079 BLOCK
3080 finally:
3081 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003082 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003083 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003084 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003085 exit(*exc)
3086 */
3087static int
3088compiler_with(struct compiler *c, stmt_ty s)
3089{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003090 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003091
3092 assert(s->kind == With_kind);
3093
Guido van Rossumc2e20742006-02-27 22:32:47 +00003094 block = compiler_new_block(c);
3095 finally = compiler_new_block(c);
3096 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003097 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003098
Thomas Wouters477c8d52006-05-27 19:21:47 +00003099 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003100 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003101 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003102
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003103 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003104 compiler_use_next_block(c, block);
3105 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003106 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003107 }
3108
3109 if (s->v.With.optional_vars) {
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003110 VISIT(c, expr, s->v.With.optional_vars);
3111 }
3112 else {
3113 /* Discard result from context.__enter__() */
3114 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003115 }
3116
3117 /* BLOCK code */
3118 VISIT_SEQ(c, stmt, s->v.With.body);
3119
3120 /* End of try block; start the finally block */
3121 ADDOP(c, POP_BLOCK);
3122 compiler_pop_fblock(c, FINALLY_TRY, block);
3123
3124 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3125 compiler_use_next_block(c, finally);
3126 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003127 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003128
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003129 /* Finally block starts; context.__exit__ is on the stack under
3130 the exception or return information. Just issue our magic
3131 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003132 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003133
3134 /* Finally block ends. */
3135 ADDOP(c, END_FINALLY);
3136 compiler_pop_fblock(c, FINALLY_END, finally);
3137 return 1;
3138}
3139
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140static int
3141compiler_visit_expr(struct compiler *c, expr_ty e)
3142{
3143 int i, n;
3144
Thomas Wouters89f507f2006-12-13 04:49:30 +00003145 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003146 set a new line number for the next instruction.
3147 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 if (e->lineno > c->u->u_lineno) {
3149 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003150 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151 }
3152 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003153 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003155 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 VISIT(c, expr, e->v.BinOp.left);
3157 VISIT(c, expr, e->v.BinOp.right);
3158 ADDOP(c, binop(c, e->v.BinOp.op));
3159 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161 VISIT(c, expr, e->v.UnaryOp.operand);
3162 ADDOP(c, unaryop(e->v.UnaryOp.op));
3163 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003166 case IfExp_kind:
3167 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003168 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003170 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003172 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003173 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003174 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003175 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003176 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177 }
3178 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003179 case Set_kind:
3180 n = asdl_seq_LEN(e->v.Set.elts);
3181 VISIT_SEQ(c, expr, e->v.Set.elts);
3182 ADDOP_I(c, BUILD_SET, n);
3183 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003184 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003186 case ListComp_kind:
3187 return compiler_listcomp(c, e);
3188 case SetComp_kind:
3189 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003190 case DictComp_kind:
3191 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192 case Yield_kind:
3193 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003194 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195 if (e->v.Yield.value) {
3196 VISIT(c, expr, e->v.Yield.value);
3197 }
3198 else {
3199 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3200 }
3201 ADDOP(c, YIELD_VALUE);
3202 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003207 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3209 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003210 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3212 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003213 case Bytes_kind:
3214 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003215 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003216 case Ellipsis_kind:
3217 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3218 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003220 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 if (e->v.Attribute.ctx != AugStore)
3222 VISIT(c, expr, e->v.Attribute.value);
3223 switch (e->v.Attribute.ctx) {
3224 case AugLoad:
3225 ADDOP(c, DUP_TOP);
3226 /* Fall through to load */
3227 case Load:
3228 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3229 break;
3230 case AugStore:
3231 ADDOP(c, ROT_TWO);
3232 /* Fall through to save */
3233 case Store:
3234 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3235 break;
3236 case Del:
3237 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3238 break;
3239 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003240 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003241 PyErr_SetString(PyExc_SystemError,
3242 "param invalid in attribute expression");
3243 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244 }
3245 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003246 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003247 switch (e->v.Subscript.ctx) {
3248 case AugLoad:
3249 VISIT(c, expr, e->v.Subscript.value);
3250 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3251 break;
3252 case Load:
3253 VISIT(c, expr, e->v.Subscript.value);
3254 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3255 break;
3256 case AugStore:
3257 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3258 break;
3259 case Store:
3260 VISIT(c, expr, e->v.Subscript.value);
3261 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3262 break;
3263 case Del:
3264 VISIT(c, expr, e->v.Subscript.value);
3265 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3266 break;
3267 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003268 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003269 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003270 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003271 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272 }
3273 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003274 case Starred_kind:
3275 switch (e->v.Starred.ctx) {
3276 case Store:
3277 /* In all legitimate cases, the Starred node was already replaced
3278 * by compiler_list/compiler_tuple. XXX: is that okay? */
3279 return compiler_error(c,
3280 "starred assignment target must be in a list or tuple");
3281 default:
3282 return compiler_error(c,
3283 "can use starred expression only as assignment target");
3284 }
3285 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003286 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3288 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003289 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003291 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 return compiler_tuple(c, e);
3293 }
3294 return 1;
3295}
3296
3297static int
3298compiler_augassign(struct compiler *c, stmt_ty s)
3299{
3300 expr_ty e = s->v.AugAssign.target;
3301 expr_ty auge;
3302
3303 assert(s->kind == AugAssign_kind);
3304
3305 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003306 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003308 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003309 if (auge == NULL)
3310 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311 VISIT(c, expr, auge);
3312 VISIT(c, expr, s->v.AugAssign.value);
3313 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3314 auge->v.Attribute.ctx = AugStore;
3315 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 break;
3317 case Subscript_kind:
3318 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003319 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003320 if (auge == NULL)
3321 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 VISIT(c, expr, auge);
3323 VISIT(c, expr, s->v.AugAssign.value);
3324 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003325 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003327 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003329 if (!compiler_nameop(c, e->v.Name.id, Load))
3330 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003331 VISIT(c, expr, s->v.AugAssign.value);
3332 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3333 return compiler_nameop(c, e->v.Name.id, Store);
3334 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003335 PyErr_Format(PyExc_SystemError,
3336 "invalid node type (%d) for augmented assignment",
3337 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003338 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339 }
3340 return 1;
3341}
3342
3343static int
3344compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3345{
3346 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003347 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3348 PyErr_SetString(PyExc_SystemError,
3349 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003350 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003351 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352 f = &c->u->u_fblock[c->u->u_nfblocks++];
3353 f->fb_type = t;
3354 f->fb_block = b;
3355 return 1;
3356}
3357
3358static void
3359compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3360{
3361 struct compiler_unit *u = c->u;
3362 assert(u->u_nfblocks > 0);
3363 u->u_nfblocks--;
3364 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3365 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3366}
3367
Thomas Wouters89f507f2006-12-13 04:49:30 +00003368static int
3369compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003370 int i;
3371 struct compiler_unit *u = c->u;
3372 for (i = 0; i < u->u_nfblocks; ++i) {
3373 if (u->u_fblock[i].fb_type == LOOP)
3374 return 1;
3375 }
3376 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003377}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003378/* Raises a SyntaxError and returns 0.
3379 If something goes wrong, a different exception may be raised.
3380*/
3381
3382static int
3383compiler_error(struct compiler *c, const char *errstr)
3384{
3385 PyObject *loc;
3386 PyObject *u = NULL, *v = NULL;
3387
3388 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3389 if (!loc) {
3390 Py_INCREF(Py_None);
3391 loc = Py_None;
3392 }
3393 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3394 Py_None, loc);
3395 if (!u)
3396 goto exit;
3397 v = Py_BuildValue("(zO)", errstr, u);
3398 if (!v)
3399 goto exit;
3400 PyErr_SetObject(PyExc_SyntaxError, v);
3401 exit:
3402 Py_DECREF(loc);
3403 Py_XDECREF(u);
3404 Py_XDECREF(v);
3405 return 0;
3406}
3407
3408static int
3409compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003410 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003411{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003412 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003413
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003414 /* XXX this code is duplicated */
3415 switch (ctx) {
3416 case AugLoad: /* fall through to Load */
3417 case Load: op = BINARY_SUBSCR; break;
3418 case AugStore:/* fall through to Store */
3419 case Store: op = STORE_SUBSCR; break;
3420 case Del: op = DELETE_SUBSCR; break;
3421 case Param:
3422 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003423 "invalid %s kind %d in subscript\n",
3424 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003425 return 0;
3426 }
3427 if (ctx == AugLoad) {
3428 ADDOP_I(c, DUP_TOPX, 2);
3429 }
3430 else if (ctx == AugStore) {
3431 ADDOP(c, ROT_THREE);
3432 }
3433 ADDOP(c, op);
3434 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003435}
3436
3437static int
3438compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3439{
3440 int n = 2;
3441 assert(s->kind == Slice_kind);
3442
3443 /* only handles the cases where BUILD_SLICE is emitted */
3444 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003445 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446 }
3447 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003448 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003449 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003451 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003452 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453 }
3454 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456 }
3457
3458 if (s->v.Slice.step) {
3459 n++;
3460 VISIT(c, expr, s->v.Slice.step);
3461 }
3462 ADDOP_I(c, BUILD_SLICE, n);
3463 return 1;
3464}
3465
3466static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3468 expr_context_ty ctx)
3469{
3470 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003471 case Slice_kind:
3472 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473 case Index_kind:
3474 VISIT(c, expr, s->v.Index.value);
3475 break;
3476 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003477 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003478 PyErr_SetString(PyExc_SystemError,
3479 "extended slice invalid in nested slice");
3480 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481 }
3482 return 1;
3483}
3484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003485static int
3486compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3487{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003488 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003490 case Index_kind:
3491 kindname = "index";
3492 if (ctx != AugStore) {
3493 VISIT(c, expr, s->v.Index.value);
3494 }
3495 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003497 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003498 if (ctx != AugStore) {
3499 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500 return 0;
3501 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003502 break;
3503 case ExtSlice_kind:
3504 kindname = "extended slice";
3505 if (ctx != AugStore) {
3506 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3507 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003508 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003509 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003510 if (!compiler_visit_nested_slice(c, sub, ctx))
3511 return 0;
3512 }
3513 ADDOP_I(c, BUILD_TUPLE, n);
3514 }
3515 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003516 default:
3517 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003518 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003519 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003520 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003521 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522}
3523
Thomas Wouters89f507f2006-12-13 04:49:30 +00003524/* End of the compiler section, beginning of the assembler section */
3525
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526/* do depth-first search of basic block graph, starting with block.
3527 post records the block indices in post-order.
3528
3529 XXX must handle implicit jumps from one block to next
3530*/
3531
Thomas Wouters89f507f2006-12-13 04:49:30 +00003532struct assembler {
3533 PyObject *a_bytecode; /* string containing bytecode */
3534 int a_offset; /* offset into bytecode */
3535 int a_nblocks; /* number of reachable blocks */
3536 basicblock **a_postorder; /* list of blocks in dfs postorder */
3537 PyObject *a_lnotab; /* string containing lnotab */
3538 int a_lnotab_off; /* offset into lnotab */
3539 int a_lineno; /* last lineno of emitted instruction */
3540 int a_lineno_off; /* bytecode offset of last lineno */
3541};
3542
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543static void
3544dfs(struct compiler *c, basicblock *b, struct assembler *a)
3545{
3546 int i;
3547 struct instr *instr = NULL;
3548
3549 if (b->b_seen)
3550 return;
3551 b->b_seen = 1;
3552 if (b->b_next != NULL)
3553 dfs(c, b->b_next, a);
3554 for (i = 0; i < b->b_iused; i++) {
3555 instr = &b->b_instr[i];
3556 if (instr->i_jrel || instr->i_jabs)
3557 dfs(c, instr->i_target, a);
3558 }
3559 a->a_postorder[a->a_nblocks++] = b;
3560}
3561
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003562static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3564{
3565 int i;
3566 struct instr *instr;
3567 if (b->b_seen || b->b_startdepth >= depth)
3568 return maxdepth;
3569 b->b_seen = 1;
3570 b->b_startdepth = depth;
3571 for (i = 0; i < b->b_iused; i++) {
3572 instr = &b->b_instr[i];
3573 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3574 if (depth > maxdepth)
3575 maxdepth = depth;
3576 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3577 if (instr->i_jrel || instr->i_jabs) {
3578 maxdepth = stackdepth_walk(c, instr->i_target,
3579 depth, maxdepth);
3580 if (instr->i_opcode == JUMP_ABSOLUTE ||
3581 instr->i_opcode == JUMP_FORWARD) {
3582 goto out; /* remaining code is dead */
3583 }
3584 }
3585 }
3586 if (b->b_next)
3587 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3588out:
3589 b->b_seen = 0;
3590 return maxdepth;
3591}
3592
3593/* Find the flow path that needs the largest stack. We assume that
3594 * cycles in the flow graph have no net effect on the stack depth.
3595 */
3596static int
3597stackdepth(struct compiler *c)
3598{
3599 basicblock *b, *entryblock;
3600 entryblock = NULL;
3601 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3602 b->b_seen = 0;
3603 b->b_startdepth = INT_MIN;
3604 entryblock = b;
3605 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003606 if (!entryblock)
3607 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608 return stackdepth_walk(c, entryblock, 0, 0);
3609}
3610
3611static int
3612assemble_init(struct assembler *a, int nblocks, int firstlineno)
3613{
3614 memset(a, 0, sizeof(struct assembler));
3615 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003616 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 if (!a->a_bytecode)
3618 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003619 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 if (!a->a_lnotab)
3621 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003622 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3623 PyErr_NoMemory();
3624 return 0;
3625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003627 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003628 if (!a->a_postorder) {
3629 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003631 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 return 1;
3633}
3634
3635static void
3636assemble_free(struct assembler *a)
3637{
3638 Py_XDECREF(a->a_bytecode);
3639 Py_XDECREF(a->a_lnotab);
3640 if (a->a_postorder)
3641 PyObject_Free(a->a_postorder);
3642}
3643
3644/* Return the size of a basic block in bytes. */
3645
3646static int
3647instrsize(struct instr *instr)
3648{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003649 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003650 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003651 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003652 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3653 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654}
3655
3656static int
3657blocksize(basicblock *b)
3658{
3659 int i;
3660 int size = 0;
3661
3662 for (i = 0; i < b->b_iused; i++)
3663 size += instrsize(&b->b_instr[i]);
3664 return size;
3665}
3666
3667/* All about a_lnotab.
3668
3669c_lnotab is an array of unsigned bytes disguised as a Python string.
3670It is used to map bytecode offsets to source code line #s (when needed
3671for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003672
Tim Peters2a7f3842001-06-09 09:26:21 +00003673The array is conceptually a list of
3674 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003675pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003676
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003677 byte code offset source code line number
3678 0 1
3679 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003680 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003681 350 307
3682 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003683
3684The first trick is that these numbers aren't stored, only the increments
3685from one row to the next (this doesn't really work, but it's a start):
3686
3687 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3688
3689The second trick is that an unsigned byte can't hold negative values, or
3690values larger than 255, so (a) there's a deep assumption that byte code
3691offsets and their corresponding line #s both increase monotonically, and (b)
3692if at least one column jumps by more than 255 from one row to the next, more
3693than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003694from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003695part. A user of c_lnotab desiring to find the source line number
3696corresponding to a bytecode address A should do something like this
3697
3698 lineno = addr = 0
3699 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003700 addr += addr_incr
3701 if addr > A:
3702 return lineno
3703 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003704
3705In order for this to work, when the addr field increments by more than 255,
3706the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003707increment is < 256. So, in the example above, assemble_lnotab (it used
3708to be called com_set_lineno) should not (as was actually done until 2.2)
3709expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003710 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003711*/
3712
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003713static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003714assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003715{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716 int d_bytecode, d_lineno;
3717 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003718 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719
3720 d_bytecode = a->a_offset - a->a_lineno_off;
3721 d_lineno = i->i_lineno - a->a_lineno;
3722
3723 assert(d_bytecode >= 0);
3724 assert(d_lineno >= 0);
3725
Christian Heimes2202f872008-02-06 14:31:34 +00003726 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003727 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003728
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003730 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003732 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003733 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003734 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003736 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003737 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003738 else {
3739 PyErr_NoMemory();
3740 return 0;
3741 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003742 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003744 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003745 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003746 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003747 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748 *lnotab++ = 255;
3749 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003750 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751 d_bytecode -= ncodes * 255;
3752 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003753 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754 assert(d_bytecode <= 255);
3755 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003756 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003758 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003760 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003762 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003764 else {
3765 PyErr_NoMemory();
3766 return 0;
3767 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003768 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003770 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003771 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003772 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003774 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003776 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003778 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003779 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 d_lineno -= ncodes * 255;
3781 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003782 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003783
Christian Heimes72b710a2008-05-26 13:28:38 +00003784 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003786 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003787 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003788 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003789 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003790 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003791
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792 a->a_lnotab_off += 2;
3793 if (d_bytecode) {
3794 *lnotab++ = d_bytecode;
3795 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003796 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003797 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798 *lnotab++ = 0;
3799 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003800 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801 a->a_lineno = i->i_lineno;
3802 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003803 return 1;
3804}
3805
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806/* assemble_emit()
3807 Extend the bytecode with a new instruction.
3808 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003809*/
3810
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003811static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003813{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003814 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003815 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003816 char *code;
3817
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003818 size = instrsize(i);
3819 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003821 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003822 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003823 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003824 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003826 if (len > PY_SSIZE_T_MAX / 2)
3827 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003828 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003829 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003830 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003831 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003833 if (size == 6) {
3834 assert(i->i_hasarg);
3835 *code++ = (char)EXTENDED_ARG;
3836 *code++ = ext & 0xff;
3837 *code++ = ext >> 8;
3838 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003839 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003841 if (i->i_hasarg) {
3842 assert(size == 3 || size == 6);
3843 *code++ = arg & 0xff;
3844 *code++ = arg >> 8;
3845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003847}
3848
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003849static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003851{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003852 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003853 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003854 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003855
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003856 /* Compute the size of each block and fixup jump args.
3857 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003858start:
3859 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003860 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003861 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862 bsize = blocksize(b);
3863 b->b_offset = totsize;
3864 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003865 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003866 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3868 bsize = b->b_offset;
3869 for (i = 0; i < b->b_iused; i++) {
3870 struct instr *instr = &b->b_instr[i];
3871 /* Relative jumps are computed relative to
3872 the instruction pointer after fetching
3873 the jump instruction.
3874 */
3875 bsize += instrsize(instr);
3876 if (instr->i_jabs)
3877 instr->i_oparg = instr->i_target->b_offset;
3878 else if (instr->i_jrel) {
3879 int delta = instr->i_target->b_offset - bsize;
3880 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003881 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003882 else
3883 continue;
3884 if (instr->i_oparg > 0xffff)
3885 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003886 }
3887 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003888
3889 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003890 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003891 with a better solution.
3892
3893 In the meantime, should the goto be dropped in favor
3894 of a loop?
3895
3896 The issue is that in the first loop blocksize() is called
3897 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003898 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003899 i_oparg is calculated in the second loop above.
3900
3901 So we loop until we stop seeing new EXTENDED_ARGs.
3902 The only EXTENDED_ARGs that could be popping up are
3903 ones in jump instructions. So this should converge
3904 fairly quickly.
3905 */
3906 if (last_extended_arg_count != extended_arg_count) {
3907 last_extended_arg_count = extended_arg_count;
3908 goto start;
3909 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003910}
3911
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003912static PyObject *
3913dict_keys_inorder(PyObject *dict, int offset)
3914{
3915 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003916 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003917
3918 tuple = PyTuple_New(size);
3919 if (tuple == NULL)
3920 return NULL;
3921 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003922 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003923 /* The keys of the dictionary are tuples. (see compiler_add_o)
3924 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003925 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003926 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003927 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003928 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003929 PyTuple_SET_ITEM(tuple, i - offset, k);
3930 }
3931 return tuple;
3932}
3933
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003934static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003936{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003937 PySTEntryObject *ste = c->u->u_ste;
3938 int flags = 0, n;
3939 if (ste->ste_type != ModuleBlock)
3940 flags |= CO_NEWLOCALS;
3941 if (ste->ste_type == FunctionBlock) {
3942 if (!ste->ste_unoptimized)
3943 flags |= CO_OPTIMIZED;
3944 if (ste->ste_nested)
3945 flags |= CO_NESTED;
3946 if (ste->ste_generator)
3947 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003948 if (ste->ste_varargs)
3949 flags |= CO_VARARGS;
3950 if (ste->ste_varkeywords)
3951 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003952 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003953
3954 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003955 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003956
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957 n = PyDict_Size(c->u->u_freevars);
3958 if (n < 0)
3959 return -1;
3960 if (n == 0) {
3961 n = PyDict_Size(c->u->u_cellvars);
3962 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003963 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964 if (n == 0) {
3965 flags |= CO_NOFREE;
3966 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003967 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003968
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003969 return flags;
3970}
3971
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972static PyCodeObject *
3973makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003974{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003975 PyObject *tmp;
3976 PyCodeObject *co = NULL;
3977 PyObject *consts = NULL;
3978 PyObject *names = NULL;
3979 PyObject *varnames = NULL;
3980 PyObject *filename = NULL;
3981 PyObject *name = NULL;
3982 PyObject *freevars = NULL;
3983 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003984 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003985 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003986
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003987 tmp = dict_keys_inorder(c->u->u_consts, 0);
3988 if (!tmp)
3989 goto error;
3990 consts = PySequence_List(tmp); /* optimize_code requires a list */
3991 Py_DECREF(tmp);
3992
3993 names = dict_keys_inorder(c->u->u_names, 0);
3994 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3995 if (!consts || !names || !varnames)
3996 goto error;
3997
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003998 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3999 if (!cellvars)
4000 goto error;
4001 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4002 if (!freevars)
4003 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004004 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005 if (!filename)
4006 goto error;
4007
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004008 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009 flags = compute_code_flags(c);
4010 if (flags < 0)
4011 goto error;
4012
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004013 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004014 if (!bytecode)
4015 goto error;
4016
4017 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4018 if (!tmp)
4019 goto error;
4020 Py_DECREF(consts);
4021 consts = tmp;
4022
Guido van Rossum4f72a782006-10-27 23:31:49 +00004023 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4024 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025 bytecode, consts, names, varnames,
4026 freevars, cellvars,
4027 filename, c->u->u_name,
4028 c->u->u_firstlineno,
4029 a->a_lnotab);
4030 error:
4031 Py_XDECREF(consts);
4032 Py_XDECREF(names);
4033 Py_XDECREF(varnames);
4034 Py_XDECREF(filename);
4035 Py_XDECREF(name);
4036 Py_XDECREF(freevars);
4037 Py_XDECREF(cellvars);
4038 Py_XDECREF(bytecode);
4039 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004040}
4041
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004042
4043/* For debugging purposes only */
4044#if 0
4045static void
4046dump_instr(const struct instr *i)
4047{
4048 const char *jrel = i->i_jrel ? "jrel " : "";
4049 const char *jabs = i->i_jabs ? "jabs " : "";
4050 char arg[128];
4051
4052 *arg = '\0';
4053 if (i->i_hasarg)
4054 sprintf(arg, "arg: %d ", i->i_oparg);
4055
4056 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4057 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4058}
4059
4060static void
4061dump_basicblock(const basicblock *b)
4062{
4063 const char *seen = b->b_seen ? "seen " : "";
4064 const char *b_return = b->b_return ? "return " : "";
4065 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4066 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4067 if (b->b_instr) {
4068 int i;
4069 for (i = 0; i < b->b_iused; i++) {
4070 fprintf(stderr, " [%02d] ", i);
4071 dump_instr(b->b_instr + i);
4072 }
4073 }
4074}
4075#endif
4076
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077static PyCodeObject *
4078assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004079{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080 basicblock *b, *entryblock;
4081 struct assembler a;
4082 int i, j, nblocks;
4083 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085 /* Make sure every block that falls off the end returns None.
4086 XXX NEXT_BLOCK() isn't quite right, because if the last
4087 block ends with a jump or return b_next shouldn't set.
4088 */
4089 if (!c->u->u_curblock->b_return) {
4090 NEXT_BLOCK(c);
4091 if (addNone)
4092 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4093 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004094 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004095
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096 nblocks = 0;
4097 entryblock = NULL;
4098 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4099 nblocks++;
4100 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004101 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004102
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004103 /* Set firstlineno if it wasn't explicitly set. */
4104 if (!c->u->u_firstlineno) {
4105 if (entryblock && entryblock->b_instr)
4106 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4107 else
4108 c->u->u_firstlineno = 1;
4109 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4111 goto error;
4112 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004113
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004115 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004116
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117 /* Emit code in reverse postorder from dfs. */
4118 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004119 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120 for (j = 0; j < b->b_iused; j++)
4121 if (!assemble_emit(&a, &b->b_instr[j]))
4122 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004123 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004124
Christian Heimes72b710a2008-05-26 13:28:38 +00004125 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004127 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004129
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130 co = makecode(c, &a);
4131 error:
4132 assemble_free(&a);
4133 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004134}