blob: f048743701e106d48b01a983285287f6d8e7721a [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
554/* Allocate a new block and return a pointer to it.
555 Returns NULL on error.
556*/
557
558static basicblock *
559compiler_new_block(struct compiler *c)
560{
561 basicblock *b;
562 struct compiler_unit *u;
563
564 u = c->u;
565 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000566 if (b == NULL) {
567 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000568 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000569 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000570 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000571 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572 b->b_list = u->u_blocks;
573 u->u_blocks = b;
574 return b;
575}
576
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000577static basicblock *
578compiler_use_new_block(struct compiler *c)
579{
580 basicblock *block = compiler_new_block(c);
581 if (block == NULL)
582 return NULL;
583 c->u->u_curblock = block;
584 return block;
585}
586
587static basicblock *
588compiler_next_block(struct compiler *c)
589{
590 basicblock *block = compiler_new_block(c);
591 if (block == NULL)
592 return NULL;
593 c->u->u_curblock->b_next = block;
594 c->u->u_curblock = block;
595 return block;
596}
597
598static basicblock *
599compiler_use_next_block(struct compiler *c, basicblock *block)
600{
601 assert(block != NULL);
602 c->u->u_curblock->b_next = block;
603 c->u->u_curblock = block;
604 return block;
605}
606
607/* Returns the offset of the next instruction in the current block's
608 b_instr array. Resizes the b_instr as necessary.
609 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000610*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
612static int
613compiler_next_instr(struct compiler *c, basicblock *b)
614{
615 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000616 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000617 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619 if (b->b_instr == NULL) {
620 PyErr_NoMemory();
621 return -1;
622 }
623 b->b_ialloc = DEFAULT_BLOCK_SIZE;
624 memset((char *)b->b_instr, 0,
625 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000626 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000627 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000628 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629 size_t oldsize, newsize;
630 oldsize = b->b_ialloc * sizeof(struct instr);
631 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000632
633 if (oldsize > (PY_SIZE_MAX >> 1)) {
634 PyErr_NoMemory();
635 return -1;
636 }
637
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638 if (newsize == 0) {
639 PyErr_NoMemory();
640 return -1;
641 }
642 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645 if (tmp == NULL) {
646 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648 }
649 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
651 }
652 return b->b_iused++;
653}
654
Christian Heimes2202f872008-02-06 14:31:34 +0000655/* Set the i_lineno member of the instruction at offset off if the
656 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 already been set. If it has been set, the call has no effect.
658
Christian Heimes2202f872008-02-06 14:31:34 +0000659 The line number is reset in the following cases:
660 - when entering a new scope
661 - on each statement
662 - on each expression that start a new line
663 - before the "except" clause
664 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000665*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667static void
668compiler_set_lineno(struct compiler *c, int off)
669{
670 basicblock *b;
671 if (c->u->u_lineno_set)
672 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000673 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000674 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000675 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
678static int
679opcode_stack_effect(int opcode, int oparg)
680{
681 switch (opcode) {
682 case POP_TOP:
683 return -1;
684 case ROT_TWO:
685 case ROT_THREE:
686 return 0;
687 case DUP_TOP:
688 return 1;
689 case ROT_FOUR:
690 return 0;
691
692 case UNARY_POSITIVE:
693 case UNARY_NEGATIVE:
694 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000695 case UNARY_INVERT:
696 return 0;
697
Nick Coghlan650f0d02007-04-15 12:05:43 +0000698 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000699 case LIST_APPEND:
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000700 return -1;
701 case MAP_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000702 return -2;
703
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704 case BINARY_POWER:
705 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000706 case BINARY_MODULO:
707 case BINARY_ADD:
708 case BINARY_SUBTRACT:
709 case BINARY_SUBSCR:
710 case BINARY_FLOOR_DIVIDE:
711 case BINARY_TRUE_DIVIDE:
712 return -1;
713 case INPLACE_FLOOR_DIVIDE:
714 case INPLACE_TRUE_DIVIDE:
715 return -1;
716
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000717 case INPLACE_ADD:
718 case INPLACE_SUBTRACT:
719 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000720 case INPLACE_MODULO:
721 return -1;
722 case STORE_SUBSCR:
723 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000724 case STORE_MAP:
725 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000726 case DELETE_SUBSCR:
727 return -2;
728
729 case BINARY_LSHIFT:
730 case BINARY_RSHIFT:
731 case BINARY_AND:
732 case BINARY_XOR:
733 case BINARY_OR:
734 return -1;
735 case INPLACE_POWER:
736 return -1;
737 case GET_ITER:
738 return 0;
739
740 case PRINT_EXPR:
741 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000742 case LOAD_BUILD_CLASS:
743 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744 case INPLACE_LSHIFT:
745 case INPLACE_RSHIFT:
746 case INPLACE_AND:
747 case INPLACE_XOR:
748 case INPLACE_OR:
749 return -1;
750 case BREAK_LOOP:
751 return 0;
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000752 case SETUP_WITH:
753 return 7;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000754 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000755 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000756 case STORE_LOCALS:
757 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758 case RETURN_VALUE:
759 return -1;
760 case IMPORT_STAR:
761 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762 case YIELD_VALUE:
763 return 0;
764
765 case POP_BLOCK:
766 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000767 case POP_EXCEPT:
768 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769 case END_FINALLY:
770 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000771
772 case STORE_NAME:
773 return -1;
774 case DELETE_NAME:
775 return 0;
776 case UNPACK_SEQUENCE:
777 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000778 case UNPACK_EX:
779 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780 case FOR_ITER:
781 return 1;
782
783 case STORE_ATTR:
784 return -2;
785 case DELETE_ATTR:
786 return -1;
787 case STORE_GLOBAL:
788 return -1;
789 case DELETE_GLOBAL:
790 return 0;
791 case DUP_TOPX:
792 return oparg;
793 case LOAD_CONST:
794 return 1;
795 case LOAD_NAME:
796 return 1;
797 case BUILD_TUPLE:
798 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000799 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000800 return 1-oparg;
801 case BUILD_MAP:
802 return 1;
803 case LOAD_ATTR:
804 return 0;
805 case COMPARE_OP:
806 return -1;
807 case IMPORT_NAME:
808 return 0;
809 case IMPORT_FROM:
810 return 1;
811
812 case JUMP_FORWARD:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000813 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
814 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000815 case JUMP_ABSOLUTE:
816 return 0;
817
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000818 case POP_JUMP_IF_FALSE:
819 case POP_JUMP_IF_TRUE:
820 return -1;
821
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822 case LOAD_GLOBAL:
823 return 1;
824
825 case CONTINUE_LOOP:
826 return 0;
827 case SETUP_LOOP:
828 return 0;
829 case SETUP_EXCEPT:
830 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000831 return 6; /* can push 3 values for the new exception
832 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833
834 case LOAD_FAST:
835 return 1;
836 case STORE_FAST:
837 return -1;
838 case DELETE_FAST:
839 return 0;
840
841 case RAISE_VARARGS:
842 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000843#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844 case CALL_FUNCTION:
845 return -NARGS(oparg);
846 case CALL_FUNCTION_VAR:
847 case CALL_FUNCTION_KW:
848 return -NARGS(oparg)-1;
849 case CALL_FUNCTION_VAR_KW:
850 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000851 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000852 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000853 case MAKE_CLOSURE:
854 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000855#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856 case BUILD_SLICE:
857 if (oparg == 3)
858 return -2;
859 else
860 return -1;
861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862 case LOAD_CLOSURE:
863 return 1;
864 case LOAD_DEREF:
865 return 1;
866 case STORE_DEREF:
867 return -1;
868 default:
869 fprintf(stderr, "opcode = %d\n", opcode);
870 Py_FatalError("opcode_stack_effect()");
871
872 }
873 return 0; /* not reachable */
874}
875
876/* Add an opcode with no argument.
877 Returns 0 on failure, 1 on success.
878*/
879
880static int
881compiler_addop(struct compiler *c, int opcode)
882{
883 basicblock *b;
884 struct instr *i;
885 int off;
886 off = compiler_next_instr(c, c->u->u_curblock);
887 if (off < 0)
888 return 0;
889 b = c->u->u_curblock;
890 i = &b->b_instr[off];
891 i->i_opcode = opcode;
892 i->i_hasarg = 0;
893 if (opcode == RETURN_VALUE)
894 b->b_return = 1;
895 compiler_set_lineno(c, off);
896 return 1;
897}
898
899static int
900compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
901{
902 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000903 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000904 unsigned char *p, *q;
905 Py_complex z;
906 double d;
907 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000908
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000909 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000910 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
911 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000912 d = PyFloat_AS_DOUBLE(o);
913 p = (unsigned char*) &d;
914 /* all we need is to make the tuple different in either the 0.0
915 * or -0.0 case from all others, just to avoid the "coercion".
916 */
917 if (*p==0 && p[sizeof(double)-1]==0)
918 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
919 else
920 t = PyTuple_Pack(2, o, o->ob_type);
921 }
922 else if (PyComplex_Check(o)) {
923 /* complex case is even messier: we need to make complex(x,
924 0.) different from complex(x, -0.) and complex(0., y)
925 different from complex(-0., y), for any x and y. In
926 particular, all four complex zeros should be
927 distinguished.*/
928 z = PyComplex_AsCComplex(o);
929 p = (unsigned char*) &(z.real);
930 q = (unsigned char*) &(z.imag);
931 /* all that matters here is that on IEEE platforms
932 real_part_zero will be true if z.real == 0., and false if
933 z.real == -0. In fact, real_part_zero will also be true
934 for some other rarely occurring nonzero floats, but this
935 doesn't matter. Similar comments apply to
936 imag_part_zero. */
937 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
938 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
939 if (real_part_zero && imag_part_zero) {
940 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
941 }
942 else if (real_part_zero && !imag_part_zero) {
943 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
944 }
945 else if (!real_part_zero && imag_part_zero) {
946 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
947 }
948 else {
949 t = PyTuple_Pack(2, o, o->ob_type);
950 }
951 }
952 else {
953 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000954 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000955 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000956 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957
958 v = PyDict_GetItem(dict, t);
959 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000960 if (PyErr_Occurred())
961 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000962 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000963 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964 if (!v) {
965 Py_DECREF(t);
966 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000967 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 if (PyDict_SetItem(dict, t, v) < 0) {
969 Py_DECREF(t);
970 Py_DECREF(v);
971 return -1;
972 }
973 Py_DECREF(v);
974 }
975 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000976 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000978 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979}
980
981static int
982compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
983 PyObject *o)
984{
985 int arg = compiler_add_o(c, dict, o);
986 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000987 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 return compiler_addop_i(c, opcode, arg);
989}
990
991static int
992compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000993 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994{
995 int arg;
996 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
997 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999 arg = compiler_add_o(c, dict, mangled);
1000 Py_DECREF(mangled);
1001 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 return compiler_addop_i(c, opcode, arg);
1004}
1005
1006/* Add an opcode with an integer argument.
1007 Returns 0 on failure, 1 on success.
1008*/
1009
1010static int
1011compiler_addop_i(struct compiler *c, int opcode, int oparg)
1012{
1013 struct instr *i;
1014 int off;
1015 off = compiler_next_instr(c, c->u->u_curblock);
1016 if (off < 0)
1017 return 0;
1018 i = &c->u->u_curblock->b_instr[off];
1019 i->i_opcode = opcode;
1020 i->i_oparg = oparg;
1021 i->i_hasarg = 1;
1022 compiler_set_lineno(c, off);
1023 return 1;
1024}
1025
1026static int
1027compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1028{
1029 struct instr *i;
1030 int off;
1031
1032 assert(b != NULL);
1033 off = compiler_next_instr(c, c->u->u_curblock);
1034 if (off < 0)
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 i = &c->u->u_curblock->b_instr[off];
1037 i->i_opcode = opcode;
1038 i->i_target = b;
1039 i->i_hasarg = 1;
1040 if (absolute)
1041 i->i_jabs = 1;
1042 else
1043 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001044 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045 return 1;
1046}
1047
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001048/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1049 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050 it as the current block. NEXT_BLOCK() also creates an implicit jump
1051 from the current block to the new block.
1052*/
1053
Thomas Wouters89f507f2006-12-13 04:49:30 +00001054/* The returns inside these macros make it impossible to decref objects
1055 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056*/
1057
1058
1059#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001060 if (compiler_use_new_block((C)) == NULL) \
1061 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062}
1063
1064#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001065 if (compiler_next_block((C)) == NULL) \
1066 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067}
1068
1069#define ADDOP(C, OP) { \
1070 if (!compiler_addop((C), (OP))) \
1071 return 0; \
1072}
1073
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001074#define ADDOP_IN_SCOPE(C, OP) { \
1075 if (!compiler_addop((C), (OP))) { \
1076 compiler_exit_scope(c); \
1077 return 0; \
1078 } \
1079}
1080
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081#define ADDOP_O(C, OP, O, TYPE) { \
1082 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1083 return 0; \
1084}
1085
1086#define ADDOP_NAME(C, OP, O, TYPE) { \
1087 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1088 return 0; \
1089}
1090
1091#define ADDOP_I(C, OP, O) { \
1092 if (!compiler_addop_i((C), (OP), (O))) \
1093 return 0; \
1094}
1095
1096#define ADDOP_JABS(C, OP, O) { \
1097 if (!compiler_addop_j((C), (OP), (O), 1)) \
1098 return 0; \
1099}
1100
1101#define ADDOP_JREL(C, OP, O) { \
1102 if (!compiler_addop_j((C), (OP), (O), 0)) \
1103 return 0; \
1104}
1105
1106/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1107 the ASDL name to synthesize the name of the C type and the visit function.
1108*/
1109
1110#define VISIT(C, TYPE, V) {\
1111 if (!compiler_visit_ ## TYPE((C), (V))) \
1112 return 0; \
1113}
1114
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001115#define VISIT_IN_SCOPE(C, TYPE, V) {\
1116 if (!compiler_visit_ ## TYPE((C), (V))) { \
1117 compiler_exit_scope(c); \
1118 return 0; \
1119 } \
1120}
1121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122#define VISIT_SLICE(C, V, CTX) {\
1123 if (!compiler_visit_slice((C), (V), (CTX))) \
1124 return 0; \
1125}
1126
1127#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001128 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132 if (!compiler_visit_ ## TYPE((C), elt)) \
1133 return 0; \
1134 } \
1135}
1136
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001137#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001138 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001141 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001142 if (!compiler_visit_ ## TYPE((C), elt)) { \
1143 compiler_exit_scope(c); \
1144 return 0; \
1145 } \
1146 } \
1147}
1148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149static int
1150compiler_isdocstring(stmt_ty s)
1151{
1152 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return s->v.Expr.value->kind == Str_kind;
1155}
1156
1157/* Compile a sequence of statements, checking for a docstring. */
1158
1159static int
1160compiler_body(struct compiler *c, asdl_seq *stmts)
1161{
1162 int i = 0;
1163 stmt_ty st;
1164
1165 if (!asdl_seq_LEN(stmts))
1166 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001167 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001168 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1169 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 i = 1;
1171 VISIT(c, expr, st->v.Expr.value);
1172 if (!compiler_nameop(c, __doc__, Store))
1173 return 0;
1174 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001175 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001176 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 return 1;
1178}
1179
1180static PyCodeObject *
1181compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001182{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001183 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 static PyObject *module;
1186 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001187 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188 if (!module)
1189 return NULL;
1190 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001191 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1192 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001193 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 switch (mod->kind) {
1195 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001196 if (!compiler_body(c, mod->v.Module.body)) {
1197 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 break;
1201 case Interactive_kind:
1202 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001203 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001204 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 break;
1206 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001207 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001208 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 break;
1210 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001211 PyErr_SetString(PyExc_SystemError,
1212 "suite should not be possible");
1213 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001214 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001215 PyErr_Format(PyExc_SystemError,
1216 "module kind %d should not be possible",
1217 mod->kind);
1218 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220 co = assemble(c, addNone);
1221 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001222 return co;
1223}
1224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225/* The test for LOCAL must come before the test for FREE in order to
1226 handle classes where name is both local and free. The local var is
1227 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001228*/
1229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230static int
1231get_ref_type(struct compiler *c, PyObject *name)
1232{
1233 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001234 if (scope == 0) {
1235 char buf[350];
1236 PyOS_snprintf(buf, sizeof(buf),
1237 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001238 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001239 PyBytes_AS_STRING(name),
1240 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001241 PyObject_REPR(c->u->u_ste->ste_id),
1242 c->c_filename,
1243 PyObject_REPR(c->u->u_ste->ste_symbols),
1244 PyObject_REPR(c->u->u_varnames),
1245 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 Py_FatalError(buf);
1248 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001249
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251}
1252
1253static int
1254compiler_lookup_arg(PyObject *dict, PyObject *name)
1255{
1256 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001261 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001263 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001264 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267static int
1268compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1269{
1270 int i, free = PyCode_GetNumFree(co);
1271 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1273 ADDOP_I(c, MAKE_FUNCTION, args);
1274 return 1;
1275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 for (i = 0; i < free; ++i) {
1277 /* Bypass com_addop_varname because it will generate
1278 LOAD_DEREF but LOAD_CLOSURE is needed.
1279 */
1280 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1281 int arg, reftype;
1282
1283 /* Special case: If a class contains a method with a
1284 free variable that has the same name as a method,
1285 the name will be considered free *and* local in the
1286 class. It should be handled by the closure, as
1287 well as by the normal name loookup logic.
1288 */
1289 reftype = get_ref_type(c, name);
1290 if (reftype == CELL)
1291 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1292 else /* (reftype == FREE) */
1293 arg = compiler_lookup_arg(c->u->u_freevars, name);
1294 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001295 fprintf(stderr,
1296 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297 "freevars of %s: %s\n",
1298 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001299 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001301 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302 PyObject_REPR(co->co_freevars));
1303 Py_FatalError("compiler_make_closure()");
1304 }
1305 ADDOP_I(c, LOAD_CLOSURE, arg);
1306 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001309 ADDOP_I(c, MAKE_CLOSURE, args);
1310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
1314compiler_decorators(struct compiler *c, asdl_seq* decos)
1315{
1316 int i;
1317
1318 if (!decos)
1319 return 1;
1320
1321 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 }
1324 return 1;
1325}
1326
1327static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001328compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1329 asdl_seq *kw_defaults)
1330{
1331 int i, default_count = 0;
1332 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001333 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001334 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1335 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001336 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001337 if (!compiler_visit_expr(c, default_)) {
1338 return -1;
1339 }
1340 default_count++;
1341 }
1342 }
1343 return default_count;
1344}
1345
1346static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001347compiler_visit_argannotation(struct compiler *c, identifier id,
1348 expr_ty annotation, PyObject *names)
1349{
1350 if (annotation) {
1351 VISIT(c, expr, annotation);
1352 if (PyList_Append(names, id))
1353 return -1;
1354 }
1355 return 0;
1356}
1357
1358static int
1359compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1360 PyObject *names)
1361{
1362 int i, error;
1363 for (i = 0; i < asdl_seq_LEN(args); i++) {
1364 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001365 error = compiler_visit_argannotation(
1366 c,
1367 arg->arg,
1368 arg->annotation,
1369 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001370 if (error)
1371 return error;
1372 }
1373 return 0;
1374}
1375
1376static int
1377compiler_visit_annotations(struct compiler *c, arguments_ty args,
1378 expr_ty returns)
1379{
Guido van Rossum0240b922007-02-26 21:23:50 +00001380 /* Push arg annotations and a list of the argument names. Return the #
1381 of items pushed. The expressions are evaluated out-of-order wrt the
1382 source code.
1383
1384 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1385 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001386 static identifier return_str;
1387 PyObject *names;
1388 int len;
1389 names = PyList_New(0);
1390 if (!names)
1391 return -1;
1392
1393 if (compiler_visit_argannotations(c, args->args, names))
1394 goto error;
1395 if (args->varargannotation &&
1396 compiler_visit_argannotation(c, args->vararg,
1397 args->varargannotation, names))
1398 goto error;
1399 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1400 goto error;
1401 if (args->kwargannotation &&
1402 compiler_visit_argannotation(c, args->kwarg,
1403 args->kwargannotation, names))
1404 goto error;
1405
1406 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001407 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001408 if (!return_str)
1409 goto error;
1410 }
1411 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1412 goto error;
1413 }
1414
1415 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001416 if (len > 65534) {
1417 /* len must fit in 16 bits, and len is incremented below */
1418 PyErr_SetString(PyExc_SyntaxError,
1419 "too many annotations");
1420 goto error;
1421 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001422 if (len) {
1423 /* convert names to a tuple and place on stack */
1424 PyObject *elt;
1425 int i;
1426 PyObject *s = PyTuple_New(len);
1427 if (!s)
1428 goto error;
1429 for (i = 0; i < len; i++) {
1430 elt = PyList_GET_ITEM(names, i);
1431 Py_INCREF(elt);
1432 PyTuple_SET_ITEM(s, i, elt);
1433 }
1434 ADDOP_O(c, LOAD_CONST, s, consts);
1435 Py_DECREF(s);
1436 len++; /* include the just-pushed tuple */
1437 }
1438 Py_DECREF(names);
1439 return len;
1440
1441error:
1442 Py_DECREF(names);
1443 return -1;
1444}
1445
1446static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447compiler_function(struct compiler *c, stmt_ty s)
1448{
1449 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001450 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001452 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001453 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001454 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001455 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001456 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457
1458 assert(s->kind == FunctionDef_kind);
1459
1460 if (!compiler_decorators(c, decos))
1461 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001462 if (args->kwonlyargs) {
1463 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1464 args->kw_defaults);
1465 if (res < 0)
1466 return 0;
1467 kw_default_count = res;
1468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 if (args->defaults)
1470 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001471 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001472 if (num_annotations < 0)
1473 return 0;
1474 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1477 s->lineno))
1478 return 0;
1479
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001480 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001482 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001483 first_const = st->v.Expr.value->v.Str.s;
1484 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001485 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001486 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001487 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001490 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001492 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001494 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1495 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496 }
1497 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001498 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499 if (co == NULL)
1500 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501
Guido van Rossum4f72a782006-10-27 23:31:49 +00001502 arglength = asdl_seq_LEN(args->defaults);
1503 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001504 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001505 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001506 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507
Neal Norwitzc1505362006-12-28 06:47:50 +00001508 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1510 ADDOP_I(c, CALL_FUNCTION, 1);
1511 }
1512
1513 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1514}
1515
1516static int
1517compiler_class(struct compiler *c, stmt_ty s)
1518{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001520 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001521 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001522 asdl_seq* decos = s->v.ClassDef.decorator_list;
1523
1524 if (!compiler_decorators(c, decos))
1525 return 0;
1526
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001527 /* ultimately generate code for:
1528 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1529 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001530 <func> is a function/closure created from the class body;
1531 it has a single argument (__locals__) where the dict
1532 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001533 <name> is the class name
1534 <bases> is the positional arguments and *varargs argument
1535 <keywords> is the keyword arguments and **kwds argument
1536 This borrows from compiler_call.
1537 */
1538
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001539 /* 1. compile the class body into a code object */
1540 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1541 return 0;
1542 /* this block represents what we do in the new scope */
1543 {
1544 /* use the class name for name mangling */
1545 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001546 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001547 c->u->u_private = s->v.ClassDef.name;
1548 /* force it to have one mandatory argument */
1549 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001550 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001551 ADDOP_I(c, LOAD_FAST, 0);
1552 /* ... and store it into f_locals */
1553 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001554 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001555 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001556 if (!str || !compiler_nameop(c, str, Load)) {
1557 Py_XDECREF(str);
1558 compiler_exit_scope(c);
1559 return 0;
1560 }
1561 Py_DECREF(str);
1562 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001563 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001564 if (!str || !compiler_nameop(c, str, Store)) {
1565 Py_XDECREF(str);
1566 compiler_exit_scope(c);
1567 return 0;
1568 }
1569 Py_DECREF(str);
1570 /* compile the body proper */
1571 if (!compiler_body(c, s->v.ClassDef.body)) {
1572 compiler_exit_scope(c);
1573 return 0;
1574 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001575 /* return the (empty) __class__ cell */
1576 str = PyUnicode_InternFromString("__class__");
1577 if (str == NULL) {
1578 compiler_exit_scope(c);
1579 return 0;
1580 }
1581 i = compiler_lookup_arg(c->u->u_cellvars, str);
1582 Py_DECREF(str);
1583 if (i == -1) {
1584 /* This happens when nobody references the cell */
1585 PyErr_Clear();
1586 /* Return None */
1587 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1588 }
1589 else {
1590 /* Return the cell where to store __class__ */
1591 ADDOP_I(c, LOAD_CLOSURE, i);
1592 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001593 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1594 /* create the code object */
1595 co = assemble(c, 1);
1596 }
1597 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001598 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599 if (co == NULL)
1600 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001602 /* 2. load the 'build_class' function */
1603 ADDOP(c, LOAD_BUILD_CLASS);
1604
1605 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001606 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001607 Py_DECREF(co);
1608
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001609 /* 4. load class name */
1610 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1611
1612 /* 5. generate the rest of the code for the call */
1613 if (!compiler_call_helper(c, 2,
1614 s->v.ClassDef.bases,
1615 s->v.ClassDef.keywords,
1616 s->v.ClassDef.starargs,
1617 s->v.ClassDef.kwargs))
1618 return 0;
1619
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001620 /* 6. apply decorators */
1621 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1622 ADDOP_I(c, CALL_FUNCTION, 1);
1623 }
1624
1625 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1627 return 0;
1628 return 1;
1629}
1630
1631static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001632compiler_ifexp(struct compiler *c, expr_ty e)
1633{
1634 basicblock *end, *next;
1635
1636 assert(e->kind == IfExp_kind);
1637 end = compiler_new_block(c);
1638 if (end == NULL)
1639 return 0;
1640 next = compiler_new_block(c);
1641 if (next == NULL)
1642 return 0;
1643 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001644 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001645 VISIT(c, expr, e->v.IfExp.body);
1646 ADDOP_JREL(c, JUMP_FORWARD, end);
1647 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001648 VISIT(c, expr, e->v.IfExp.orelse);
1649 compiler_use_next_block(c, end);
1650 return 1;
1651}
1652
1653static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654compiler_lambda(struct compiler *c, expr_ty e)
1655{
1656 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001657 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001658 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001659 arguments_ty args = e->v.Lambda.args;
1660 assert(e->kind == Lambda_kind);
1661
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001662 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001663 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001664 if (!name)
1665 return 0;
1666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667
Guido van Rossum4f72a782006-10-27 23:31:49 +00001668 if (args->kwonlyargs) {
1669 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1670 args->kw_defaults);
1671 if (res < 0) return 0;
1672 kw_default_count = res;
1673 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 if (args->defaults)
1675 VISIT_SEQ(c, expr, args->defaults);
1676 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1677 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001680 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001681 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001682 if (c->u->u_ste->ste_generator) {
1683 ADDOP_IN_SCOPE(c, POP_TOP);
1684 }
1685 else {
1686 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1687 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001689 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690 if (co == NULL)
1691 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
Guido van Rossum4f72a782006-10-27 23:31:49 +00001693 arglength = asdl_seq_LEN(args->defaults);
1694 arglength |= kw_default_count << 8;
1695 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001696 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697
1698 return 1;
1699}
1700
1701static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702compiler_if(struct compiler *c, stmt_ty s)
1703{
1704 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001705 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 assert(s->kind == If_kind);
1707 end = compiler_new_block(c);
1708 if (end == NULL)
1709 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001710
1711 constant = expr_constant(s->v.If.test);
1712 /* constant = 0: "if 0"
1713 * constant = 1: "if 1", "if 2", ...
1714 * constant = -1: rest */
1715 if (constant == 0) {
1716 if (s->v.If.orelse)
1717 VISIT_SEQ(c, stmt, s->v.If.orelse);
1718 } else if (constant == 1) {
1719 VISIT_SEQ(c, stmt, s->v.If.body);
1720 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001721 if (s->v.If.orelse) {
1722 next = compiler_new_block(c);
1723 if (next == NULL)
1724 return 0;
1725 }
1726 else
1727 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001728 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001729 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001730 VISIT_SEQ(c, stmt, s->v.If.body);
1731 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001732 if (s->v.If.orelse) {
1733 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001734 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001735 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001736 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737 compiler_use_next_block(c, end);
1738 return 1;
1739}
1740
1741static int
1742compiler_for(struct compiler *c, stmt_ty s)
1743{
1744 basicblock *start, *cleanup, *end;
1745
1746 start = compiler_new_block(c);
1747 cleanup = compiler_new_block(c);
1748 end = compiler_new_block(c);
1749 if (start == NULL || end == NULL || cleanup == NULL)
1750 return 0;
1751 ADDOP_JREL(c, SETUP_LOOP, end);
1752 if (!compiler_push_fblock(c, LOOP, start))
1753 return 0;
1754 VISIT(c, expr, s->v.For.iter);
1755 ADDOP(c, GET_ITER);
1756 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001757 /* for expressions must be traced on each iteration,
1758 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001759 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760 ADDOP_JREL(c, FOR_ITER, cleanup);
1761 VISIT(c, expr, s->v.For.target);
1762 VISIT_SEQ(c, stmt, s->v.For.body);
1763 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1764 compiler_use_next_block(c, cleanup);
1765 ADDOP(c, POP_BLOCK);
1766 compiler_pop_fblock(c, LOOP, start);
1767 VISIT_SEQ(c, stmt, s->v.For.orelse);
1768 compiler_use_next_block(c, end);
1769 return 1;
1770}
1771
1772static int
1773compiler_while(struct compiler *c, stmt_ty s)
1774{
1775 basicblock *loop, *orelse, *end, *anchor = NULL;
1776 int constant = expr_constant(s->v.While.test);
1777
Christian Heimes969fe572008-01-25 11:23:10 +00001778 if (constant == 0) {
1779 if (s->v.While.orelse)
1780 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001782 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783 loop = compiler_new_block(c);
1784 end = compiler_new_block(c);
1785 if (constant == -1) {
1786 anchor = compiler_new_block(c);
1787 if (anchor == NULL)
1788 return 0;
1789 }
1790 if (loop == NULL || end == NULL)
1791 return 0;
1792 if (s->v.While.orelse) {
1793 orelse = compiler_new_block(c);
1794 if (orelse == NULL)
1795 return 0;
1796 }
1797 else
1798 orelse = NULL;
1799
1800 ADDOP_JREL(c, SETUP_LOOP, end);
1801 compiler_use_next_block(c, loop);
1802 if (!compiler_push_fblock(c, LOOP, loop))
1803 return 0;
1804 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001805 /* while expressions must be traced on each iteration,
1806 so we need to set an extra line number. */
1807 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001809 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810 }
1811 VISIT_SEQ(c, stmt, s->v.While.body);
1812 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1813
1814 /* XXX should the two POP instructions be in a separate block
1815 if there is no else clause ?
1816 */
1817
1818 if (constant == -1) {
1819 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820 ADDOP(c, POP_BLOCK);
1821 }
1822 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001823 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824 VISIT_SEQ(c, stmt, s->v.While.orelse);
1825 compiler_use_next_block(c, end);
1826
1827 return 1;
1828}
1829
1830static int
1831compiler_continue(struct compiler *c)
1832{
1833 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001834 static const char IN_FINALLY_ERROR_MSG[] =
1835 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 int i;
1837
1838 if (!c->u->u_nfblocks)
1839 return compiler_error(c, LOOP_ERROR_MSG);
1840 i = c->u->u_nfblocks - 1;
1841 switch (c->u->u_fblock[i].fb_type) {
1842 case LOOP:
1843 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1844 break;
1845 case EXCEPT:
1846 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001847 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1848 /* Prevent continue anywhere under a finally
1849 even if hidden in a sub-try or except. */
1850 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1851 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1852 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 if (i == -1)
1854 return compiler_error(c, LOOP_ERROR_MSG);
1855 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1856 break;
1857 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001858 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 }
1860
1861 return 1;
1862}
1863
1864/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1865
1866 SETUP_FINALLY L
1867 <code for body>
1868 POP_BLOCK
1869 LOAD_CONST <None>
1870 L: <code for finalbody>
1871 END_FINALLY
1872
1873 The special instructions use the block stack. Each block
1874 stack entry contains the instruction that created it (here
1875 SETUP_FINALLY), the level of the value stack at the time the
1876 block stack entry was created, and a label (here L).
1877
1878 SETUP_FINALLY:
1879 Pushes the current value stack level and the label
1880 onto the block stack.
1881 POP_BLOCK:
1882 Pops en entry from the block stack, and pops the value
1883 stack until its level is the same as indicated on the
1884 block stack. (The label is ignored.)
1885 END_FINALLY:
1886 Pops a variable number of entries from the *value* stack
1887 and re-raises the exception they specify. The number of
1888 entries popped depends on the (pseudo) exception type.
1889
1890 The block stack is unwound when an exception is raised:
1891 when a SETUP_FINALLY entry is found, the exception is pushed
1892 onto the value stack (and the exception condition is cleared),
1893 and the interpreter jumps to the label gotten from the block
1894 stack.
1895*/
1896
1897static int
1898compiler_try_finally(struct compiler *c, stmt_ty s)
1899{
1900 basicblock *body, *end;
1901 body = compiler_new_block(c);
1902 end = compiler_new_block(c);
1903 if (body == NULL || end == NULL)
1904 return 0;
1905
1906 ADDOP_JREL(c, SETUP_FINALLY, end);
1907 compiler_use_next_block(c, body);
1908 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1909 return 0;
1910 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1911 ADDOP(c, POP_BLOCK);
1912 compiler_pop_fblock(c, FINALLY_TRY, body);
1913
1914 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1915 compiler_use_next_block(c, end);
1916 if (!compiler_push_fblock(c, FINALLY_END, end))
1917 return 0;
1918 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1919 ADDOP(c, END_FINALLY);
1920 compiler_pop_fblock(c, FINALLY_END, end);
1921
1922 return 1;
1923}
1924
1925/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001926 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 (The contents of the value stack is shown in [], with the top
1928 at the right; 'tb' is trace-back info, 'val' the exception's
1929 associated value, and 'exc' the exception.)
1930
1931 Value stack Label Instruction Argument
1932 [] SETUP_EXCEPT L1
1933 [] <code for S>
1934 [] POP_BLOCK
1935 [] JUMP_FORWARD L0
1936
1937 [tb, val, exc] L1: DUP )
1938 [tb, val, exc, exc] <evaluate E1> )
1939 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001940 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 [tb, val, exc] POP
1942 [tb, val] <assign to V1> (or POP if no V1)
1943 [tb] POP
1944 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001945 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001947 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948 .............................etc.......................
1949
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001950 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951
1952 [] L0: <next statement>
1953
1954 Of course, parts are not generated if Vi or Ei is not present.
1955*/
1956static int
1957compiler_try_except(struct compiler *c, stmt_ty s)
1958{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001959 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 int i, n;
1961
1962 body = compiler_new_block(c);
1963 except = compiler_new_block(c);
1964 orelse = compiler_new_block(c);
1965 end = compiler_new_block(c);
1966 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1967 return 0;
1968 ADDOP_JREL(c, SETUP_EXCEPT, except);
1969 compiler_use_next_block(c, body);
1970 if (!compiler_push_fblock(c, EXCEPT, body))
1971 return 0;
1972 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1973 ADDOP(c, POP_BLOCK);
1974 compiler_pop_fblock(c, EXCEPT, body);
1975 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1976 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1977 compiler_use_next_block(c, except);
1978 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001979 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001981 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001983 c->u->u_lineno_set = 0;
1984 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985 except = compiler_new_block(c);
1986 if (except == NULL)
1987 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001988 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001990 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001992 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 }
1994 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001995 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001996 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001997
1998 cleanup_end = compiler_new_block(c);
1999 cleanup_body = compiler_new_block(c);
2000 if(!(cleanup_end || cleanup_body))
2001 return 0;
2002
Neal Norwitzad74aa82008-03-31 05:14:30 +00002003 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002004 ADDOP(c, POP_TOP);
2005
2006 /*
2007 try:
2008 # body
2009 except type as name:
2010 try:
2011 # body
2012 finally:
2013 name = None
2014 del name
2015 */
2016
2017 /* second try: */
2018 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2019 compiler_use_next_block(c, cleanup_body);
2020 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2021 return 0;
2022
2023 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002024 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002025 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002026 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002027 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2028
2029 /* finally: */
2030 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2031 compiler_use_next_block(c, cleanup_end);
2032 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2033 return 0;
2034
2035 /* name = None */
2036 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002037 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002038
Guido van Rossum16be03e2007-01-10 18:51:35 +00002039 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002040 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002041
2042 ADDOP(c, END_FINALLY);
2043 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044 }
2045 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002046 basicblock *cleanup_body;
2047
2048 cleanup_body = compiler_new_block(c);
2049 if(!cleanup_body)
2050 return 0;
2051
2052 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002053 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002054 compiler_use_next_block(c, cleanup_body);
2055 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2056 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002057 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002058 ADDOP(c, POP_EXCEPT);
2059 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 ADDOP_JREL(c, JUMP_FORWARD, end);
2062 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 }
2064 ADDOP(c, END_FINALLY);
2065 compiler_use_next_block(c, orelse);
2066 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2067 compiler_use_next_block(c, end);
2068 return 1;
2069}
2070
2071static int
2072compiler_import_as(struct compiler *c, identifier name, identifier asname)
2073{
2074 /* The IMPORT_NAME opcode was already generated. This function
2075 merely needs to bind the result to a name.
2076
2077 If there is a dot in name, we need to split it and emit a
2078 LOAD_ATTR for each name.
2079 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002080 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2081 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 if (dot) {
2083 /* Consume the base module name to get the first attribute */
2084 src = dot + 1;
2085 while (dot) {
2086 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002087 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002088 dot = Py_UNICODE_strchr(src, '.');
2089 attr = PyUnicode_FromUnicode(src,
2090 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002091 if (!attr)
2092 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002094 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 src = dot + 1;
2096 }
2097 }
2098 return compiler_nameop(c, asname, Store);
2099}
2100
2101static int
2102compiler_import(struct compiler *c, stmt_ty s)
2103{
2104 /* The Import node stores a module name like a.b.c as a single
2105 string. This is convenient for all cases except
2106 import a.b.c as d
2107 where we need to parse that string to extract the individual
2108 module names.
2109 XXX Perhaps change the representation to make this case simpler?
2110 */
2111 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002112
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002114 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002116 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117
Christian Heimes217cfd12007-12-02 14:31:20 +00002118 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002119 if (level == NULL)
2120 return 0;
2121
2122 ADDOP_O(c, LOAD_CONST, level, consts);
2123 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2125 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2126
2127 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002128 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 if (!r)
2130 return r;
2131 }
2132 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002134 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2135 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002137 tmp = PyUnicode_FromUnicode(base,
2138 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139 r = compiler_nameop(c, tmp, Store);
2140 if (dot) {
2141 Py_DECREF(tmp);
2142 }
2143 if (!r)
2144 return r;
2145 }
2146 }
2147 return 1;
2148}
2149
2150static int
2151compiler_from_import(struct compiler *c, stmt_ty s)
2152{
2153 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154
2155 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002156 PyObject *level;
2157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 if (!names)
2159 return 0;
2160
Christian Heimes217cfd12007-12-02 14:31:20 +00002161 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002162 if (!level) {
2163 Py_DECREF(names);
2164 return 0;
2165 }
2166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 /* build up the names */
2168 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002169 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 Py_INCREF(alias->name);
2171 PyTuple_SET_ITEM(names, i, alias->name);
2172 }
2173
2174 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002175 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2176 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002177 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 Py_DECREF(names);
2179 return compiler_error(c,
2180 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002181 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182
2183 }
2184 }
2185
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002186 ADDOP_O(c, LOAD_CONST, level, consts);
2187 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002189 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2191 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002192 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 identifier store_name;
2194
Martin v. Löwis5b222132007-06-10 09:51:05 +00002195 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 assert(n == 1);
2197 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199 }
2200
2201 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2202 store_name = alias->name;
2203 if (alias->asname)
2204 store_name = alias->asname;
2205
2206 if (!compiler_nameop(c, store_name, Store)) {
2207 Py_DECREF(names);
2208 return 0;
2209 }
2210 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002211 /* remove imported module */
2212 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213 return 1;
2214}
2215
2216static int
2217compiler_assert(struct compiler *c, stmt_ty s)
2218{
2219 static PyObject *assertion_error = NULL;
2220 basicblock *end;
2221
2222 if (Py_OptimizeFlag)
2223 return 1;
2224 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002225 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226 if (assertion_error == NULL)
2227 return 0;
2228 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002229 if (s->v.Assert.test->kind == Tuple_kind &&
2230 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2231 const char* msg =
2232 "assertion is always true, perhaps remove parentheses?";
2233 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2234 c->u->u_lineno, NULL, NULL) == -1)
2235 return 0;
2236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237 VISIT(c, expr, s->v.Assert.test);
2238 end = compiler_new_block(c);
2239 if (end == NULL)
2240 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002241 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2243 if (s->v.Assert.msg) {
2244 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002245 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246 }
Collin Winter828f04a2007-08-31 00:04:24 +00002247 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002248 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249 return 1;
2250}
2251
2252static int
2253compiler_visit_stmt(struct compiler *c, stmt_ty s)
2254{
2255 int i, n;
2256
Thomas Wouters89f507f2006-12-13 04:49:30 +00002257 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002259 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002264 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002266 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 if (c->u->u_ste->ste_type != FunctionBlock)
2268 return compiler_error(c, "'return' outside function");
2269 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 VISIT(c, expr, s->v.Return.value);
2271 }
2272 else
2273 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2274 ADDOP(c, RETURN_VALUE);
2275 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002276 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277 VISIT_SEQ(c, expr, s->v.Delete.targets)
2278 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002279 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 n = asdl_seq_LEN(s->v.Assign.targets);
2281 VISIT(c, expr, s->v.Assign.value);
2282 for (i = 0; i < n; i++) {
2283 if (i < n - 1)
2284 ADDOP(c, DUP_TOP);
2285 VISIT(c, expr,
2286 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2287 }
2288 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002289 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002295 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002297 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002299 if (s->v.Raise.exc) {
2300 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002302 if (s->v.Raise.cause) {
2303 VISIT(c, expr, s->v.Raise.cause);
2304 n++;
2305 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 }
2307 ADDOP_I(c, RAISE_VARARGS, n);
2308 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002309 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002311 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002313 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002315 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002317 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002320 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002322 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002324 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 ADDOP(c, PRINT_EXPR);
2326 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002327 else if (s->v.Expr.value->kind != Str_kind &&
2328 s->v.Expr.value->kind != Num_kind) {
2329 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 ADDOP(c, POP_TOP);
2331 }
2332 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002333 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002335 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002336 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 return compiler_error(c, "'break' outside loop");
2338 ADDOP(c, BREAK_LOOP);
2339 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002340 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002342 case With_kind:
2343 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344 }
2345 return 1;
2346}
2347
2348static int
2349unaryop(unaryop_ty op)
2350{
2351 switch (op) {
2352 case Invert:
2353 return UNARY_INVERT;
2354 case Not:
2355 return UNARY_NOT;
2356 case UAdd:
2357 return UNARY_POSITIVE;
2358 case USub:
2359 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002360 default:
2361 PyErr_Format(PyExc_SystemError,
2362 "unary op %d should not be possible", op);
2363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365}
2366
2367static int
2368binop(struct compiler *c, operator_ty op)
2369{
2370 switch (op) {
2371 case Add:
2372 return BINARY_ADD;
2373 case Sub:
2374 return BINARY_SUBTRACT;
2375 case Mult:
2376 return BINARY_MULTIPLY;
2377 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002378 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379 case Mod:
2380 return BINARY_MODULO;
2381 case Pow:
2382 return BINARY_POWER;
2383 case LShift:
2384 return BINARY_LSHIFT;
2385 case RShift:
2386 return BINARY_RSHIFT;
2387 case BitOr:
2388 return BINARY_OR;
2389 case BitXor:
2390 return BINARY_XOR;
2391 case BitAnd:
2392 return BINARY_AND;
2393 case FloorDiv:
2394 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002395 default:
2396 PyErr_Format(PyExc_SystemError,
2397 "binary op %d should not be possible", op);
2398 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400}
2401
2402static int
2403cmpop(cmpop_ty op)
2404{
2405 switch (op) {
2406 case Eq:
2407 return PyCmp_EQ;
2408 case NotEq:
2409 return PyCmp_NE;
2410 case Lt:
2411 return PyCmp_LT;
2412 case LtE:
2413 return PyCmp_LE;
2414 case Gt:
2415 return PyCmp_GT;
2416 case GtE:
2417 return PyCmp_GE;
2418 case Is:
2419 return PyCmp_IS;
2420 case IsNot:
2421 return PyCmp_IS_NOT;
2422 case In:
2423 return PyCmp_IN;
2424 case NotIn:
2425 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002426 default:
2427 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002429}
2430
2431static int
2432inplace_binop(struct compiler *c, operator_ty op)
2433{
2434 switch (op) {
2435 case Add:
2436 return INPLACE_ADD;
2437 case Sub:
2438 return INPLACE_SUBTRACT;
2439 case Mult:
2440 return INPLACE_MULTIPLY;
2441 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002442 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443 case Mod:
2444 return INPLACE_MODULO;
2445 case Pow:
2446 return INPLACE_POWER;
2447 case LShift:
2448 return INPLACE_LSHIFT;
2449 case RShift:
2450 return INPLACE_RSHIFT;
2451 case BitOr:
2452 return INPLACE_OR;
2453 case BitXor:
2454 return INPLACE_XOR;
2455 case BitAnd:
2456 return INPLACE_AND;
2457 case FloorDiv:
2458 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002459 default:
2460 PyErr_Format(PyExc_SystemError,
2461 "inplace binary op %d should not be possible", op);
2462 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464}
2465
2466static int
2467compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2468{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002469 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2471
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002472 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002473 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 /* XXX AugStore isn't used anywhere! */
2475
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002476 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002477 if (!mangled)
2478 return 0;
2479
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480 op = 0;
2481 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002482 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 switch (scope) {
2484 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002485 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 optype = OP_DEREF;
2487 break;
2488 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002489 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490 optype = OP_DEREF;
2491 break;
2492 case LOCAL:
2493 if (c->u->u_ste->ste_type == FunctionBlock)
2494 optype = OP_FAST;
2495 break;
2496 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002497 if (c->u->u_ste->ste_type == FunctionBlock &&
2498 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 optype = OP_GLOBAL;
2500 break;
2501 case GLOBAL_EXPLICIT:
2502 optype = OP_GLOBAL;
2503 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002504 default:
2505 /* scope can be 0 */
2506 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 }
2508
2509 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002510 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511
2512 switch (optype) {
2513 case OP_DEREF:
2514 switch (ctx) {
2515 case Load: op = LOAD_DEREF; break;
2516 case Store: op = STORE_DEREF; break;
2517 case AugLoad:
2518 case AugStore:
2519 break;
2520 case Del:
2521 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002522 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002524 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002525 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002528 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002529 PyErr_SetString(PyExc_SystemError,
2530 "param invalid for deref variable");
2531 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 }
2533 break;
2534 case OP_FAST:
2535 switch (ctx) {
2536 case Load: op = LOAD_FAST; break;
2537 case Store: op = STORE_FAST; break;
2538 case Del: op = DELETE_FAST; break;
2539 case AugLoad:
2540 case AugStore:
2541 break;
2542 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002543 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002544 PyErr_SetString(PyExc_SystemError,
2545 "param invalid for local variable");
2546 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002548 ADDOP_O(c, op, mangled, varnames);
2549 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 return 1;
2551 case OP_GLOBAL:
2552 switch (ctx) {
2553 case Load: op = LOAD_GLOBAL; break;
2554 case Store: op = STORE_GLOBAL; break;
2555 case Del: op = DELETE_GLOBAL; break;
2556 case AugLoad:
2557 case AugStore:
2558 break;
2559 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002560 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002561 PyErr_SetString(PyExc_SystemError,
2562 "param invalid for global variable");
2563 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 }
2565 break;
2566 case OP_NAME:
2567 switch (ctx) {
2568 case Load: op = LOAD_NAME; break;
2569 case Store: op = STORE_NAME; break;
2570 case Del: op = DELETE_NAME; break;
2571 case AugLoad:
2572 case AugStore:
2573 break;
2574 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002575 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002576 PyErr_SetString(PyExc_SystemError,
2577 "param invalid for name variable");
2578 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579 }
2580 break;
2581 }
2582
2583 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002584 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002585 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002586 if (arg < 0)
2587 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002588 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589}
2590
2591static int
2592compiler_boolop(struct compiler *c, expr_ty e)
2593{
2594 basicblock *end;
2595 int jumpi, i, n;
2596 asdl_seq *s;
2597
2598 assert(e->kind == BoolOp_kind);
2599 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002600 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002602 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002604 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002605 return 0;
2606 s = e->v.BoolOp.values;
2607 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002608 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002610 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002611 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002613 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 compiler_use_next_block(c, end);
2615 return 1;
2616}
2617
2618static int
2619compiler_list(struct compiler *c, expr_ty e)
2620{
2621 int n = asdl_seq_LEN(e->v.List.elts);
2622 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002623 int i, seen_star = 0;
2624 for (i = 0; i < n; i++) {
2625 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2626 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002627 if ((i >= (1 << 8)) ||
2628 (n-i-1 >= (INT_MAX >> 8)))
2629 return compiler_error(c,
2630 "too many expressions in "
2631 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002632 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2633 seen_star = 1;
2634 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2635 } else if (elt->kind == Starred_kind) {
2636 return compiler_error(c,
2637 "two starred expressions in assignment");
2638 }
2639 }
2640 if (!seen_star) {
2641 ADDOP_I(c, UNPACK_SEQUENCE, n);
2642 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643 }
2644 VISIT_SEQ(c, expr, e->v.List.elts);
2645 if (e->v.List.ctx == Load) {
2646 ADDOP_I(c, BUILD_LIST, n);
2647 }
2648 return 1;
2649}
2650
2651static int
2652compiler_tuple(struct compiler *c, expr_ty e)
2653{
2654 int n = asdl_seq_LEN(e->v.Tuple.elts);
2655 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002656 int i, seen_star = 0;
2657 for (i = 0; i < n; i++) {
2658 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2659 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002660 if ((i >= (1 << 8)) ||
2661 (n-i-1 >= (INT_MAX >> 8)))
2662 return compiler_error(c,
2663 "too many expressions in "
2664 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002665 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2666 seen_star = 1;
2667 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2668 } else if (elt->kind == Starred_kind) {
2669 return compiler_error(c,
2670 "two starred expressions in assignment");
2671 }
2672 }
2673 if (!seen_star) {
2674 ADDOP_I(c, UNPACK_SEQUENCE, n);
2675 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 }
2677 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2678 if (e->v.Tuple.ctx == Load) {
2679 ADDOP_I(c, BUILD_TUPLE, n);
2680 }
2681 return 1;
2682}
2683
2684static int
2685compiler_compare(struct compiler *c, expr_ty e)
2686{
2687 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002688 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689
2690 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2691 VISIT(c, expr, e->v.Compare.left);
2692 n = asdl_seq_LEN(e->v.Compare.ops);
2693 assert(n > 0);
2694 if (n > 1) {
2695 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002696 if (cleanup == NULL)
2697 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002698 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002699 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 }
2701 for (i = 1; i < n; i++) {
2702 ADDOP(c, DUP_TOP);
2703 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002705 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002706 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002707 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 if (i < (n - 1))
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, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002713 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002715 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 if (n > 1) {
2717 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002718 if (end == NULL)
2719 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 ADDOP_JREL(c, JUMP_FORWARD, end);
2721 compiler_use_next_block(c, cleanup);
2722 ADDOP(c, ROT_TWO);
2723 ADDOP(c, POP_TOP);
2724 compiler_use_next_block(c, end);
2725 }
2726 return 1;
2727}
2728
2729static int
2730compiler_call(struct compiler *c, expr_ty e)
2731{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002733 return compiler_call_helper(c, 0,
2734 e->v.Call.args,
2735 e->v.Call.keywords,
2736 e->v.Call.starargs,
2737 e->v.Call.kwargs);
2738}
2739
2740/* shared code between compiler_call and compiler_class */
2741static int
2742compiler_call_helper(struct compiler *c,
2743 int n, /* Args already pushed */
2744 asdl_seq *args,
2745 asdl_seq *keywords,
2746 expr_ty starargs,
2747 expr_ty kwargs)
2748{
2749 int code = 0;
2750
2751 n += asdl_seq_LEN(args);
2752 VISIT_SEQ(c, expr, args);
2753 if (keywords) {
2754 VISIT_SEQ(c, keyword, keywords);
2755 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002757 if (starargs) {
2758 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759 code |= 1;
2760 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002761 if (kwargs) {
2762 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763 code |= 2;
2764 }
2765 switch (code) {
2766 case 0:
2767 ADDOP_I(c, CALL_FUNCTION, n);
2768 break;
2769 case 1:
2770 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2771 break;
2772 case 2:
2773 ADDOP_I(c, CALL_FUNCTION_KW, n);
2774 break;
2775 case 3:
2776 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2777 break;
2778 }
2779 return 1;
2780}
2781
Nick Coghlan650f0d02007-04-15 12:05:43 +00002782
2783/* List and set comprehensions and generator expressions work by creating a
2784 nested function to perform the actual iteration. This means that the
2785 iteration variables don't leak into the current scope.
2786 The defined function is called immediately following its definition, with the
2787 result of that call being the result of the expression.
2788 The LC/SC version returns the populated container, while the GE version is
2789 flagged in symtable.c as a generator, so it returns the generator object
2790 when the function is called.
2791 This code *knows* that the loop cannot contain break, continue, or return,
2792 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2793
2794 Possible cleanups:
2795 - iterate over the generator sequence instead of using recursion
2796*/
2797
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002799compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002800 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002801 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802{
2803 /* generate code for the iterator, then each of the ifs,
2804 and then write to the element */
2805
Nick Coghlan650f0d02007-04-15 12:05:43 +00002806 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002808 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809
2810 start = compiler_new_block(c);
2811 skip = compiler_new_block(c);
2812 if_cleanup = compiler_new_block(c);
2813 anchor = compiler_new_block(c);
2814
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002816 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818
Nick Coghlan650f0d02007-04-15 12:05:43 +00002819 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821 if (gen_index == 0) {
2822 /* Receive outermost iter as an implicit argument */
2823 c->u->u_argcount = 1;
2824 ADDOP_I(c, LOAD_FAST, 0);
2825 }
2826 else {
2827 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002828 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829 ADDOP(c, GET_ITER);
2830 }
2831 compiler_use_next_block(c, start);
2832 ADDOP_JREL(c, FOR_ITER, anchor);
2833 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002834 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002836 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002837 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002839 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002841 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002846 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002847 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002848 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002849 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002850
Nick Coghlan650f0d02007-04-15 12:05:43 +00002851 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002852 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002853 /* comprehension specific code */
2854 switch (type) {
2855 case COMP_GENEXP:
2856 VISIT(c, expr, elt);
2857 ADDOP(c, YIELD_VALUE);
2858 ADDOP(c, POP_TOP);
2859 break;
2860 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002861 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002862 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002863 break;
2864 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002865 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002866 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002867 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002868 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002869 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002870 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002871 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002872 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002873 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002874 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875 default:
2876 return 0;
2877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
2879 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002880 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002881 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2883 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884
2885 return 1;
2886}
2887
2888static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002889compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002890 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002891{
2892 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002893 expr_ty outermost_iter;
2894
2895 outermost_iter = ((comprehension_ty)
2896 asdl_seq_GET(generators, 0))->iter;
2897
2898 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2899 goto error;
2900
2901 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002902 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002903 switch (type) {
2904 case COMP_LISTCOMP:
2905 op = BUILD_LIST;
2906 break;
2907 case COMP_SETCOMP:
2908 op = BUILD_SET;
2909 break;
2910 case COMP_DICTCOMP:
2911 op = BUILD_MAP;
2912 break;
2913 default:
2914 PyErr_Format(PyExc_SystemError,
2915 "unknown comprehension type %d", type);
2916 goto error_in_scope;
2917 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002918
Guido van Rossum992d4a32007-07-11 13:09:30 +00002919 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002920 }
2921
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002922 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002923 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002924 goto error_in_scope;
2925
2926 if (type != COMP_GENEXP) {
2927 ADDOP(c, RETURN_VALUE);
2928 }
2929
2930 co = assemble(c, 1);
2931 compiler_exit_scope(c);
2932 if (co == NULL)
2933 goto error;
2934
2935 if (!compiler_make_closure(c, co, 0))
2936 goto error;
2937 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002938
2939 VISIT(c, expr, outermost_iter);
2940 ADDOP(c, GET_ITER);
2941 ADDOP_I(c, CALL_FUNCTION, 1);
2942 return 1;
2943error_in_scope:
2944 compiler_exit_scope(c);
2945error:
2946 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002947 return 0;
2948}
2949
2950static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951compiler_genexp(struct compiler *c, expr_ty e)
2952{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002953 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002954 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002955 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002956 if (!name)
2957 return 0;
2958 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002959 assert(e->kind == GeneratorExp_kind);
2960 return compiler_comprehension(c, e, COMP_GENEXP, name,
2961 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002962 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963}
2964
2965static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002966compiler_listcomp(struct compiler *c, expr_ty e)
2967{
2968 static identifier name;
2969 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002970 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002971 if (!name)
2972 return 0;
2973 }
2974 assert(e->kind == ListComp_kind);
2975 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2976 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002977 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002978}
2979
2980static int
2981compiler_setcomp(struct compiler *c, expr_ty e)
2982{
2983 static identifier name;
2984 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002985 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002986 if (!name)
2987 return 0;
2988 }
2989 assert(e->kind == SetComp_kind);
2990 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2991 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002992 e->v.SetComp.elt, NULL);
2993}
2994
2995
2996static int
2997compiler_dictcomp(struct compiler *c, expr_ty e)
2998{
2999 static identifier name;
3000 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003001 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003002 if (!name)
3003 return 0;
3004 }
3005 assert(e->kind == DictComp_kind);
3006 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3007 e->v.DictComp.generators,
3008 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003009}
3010
3011
3012static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013compiler_visit_keyword(struct compiler *c, keyword_ty k)
3014{
3015 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3016 VISIT(c, expr, k->value);
3017 return 1;
3018}
3019
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003020/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 whether they are true or false.
3022
3023 Return values: 1 for true, 0 for false, -1 for non-constant.
3024 */
3025
3026static int
3027expr_constant(expr_ty e)
3028{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003029 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003031 case Ellipsis_kind:
3032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 case Num_kind:
3034 return PyObject_IsTrue(e->v.Num.n);
3035 case Str_kind:
3036 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003037 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003038 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003039 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003040 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003041 if (strcmp(id, "True") == 0) return 1;
3042 if (strcmp(id, "False") == 0) return 0;
3043 if (strcmp(id, "None") == 0) return 0;
3044 if (strcmp(id, "__debug__") == 0)
3045 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003046 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 default:
3048 return -1;
3049 }
3050}
3051
Guido van Rossumc2e20742006-02-27 22:32:47 +00003052/*
3053 Implements the with statement from PEP 343.
3054
3055 The semantics outlined in that PEP are as follows:
3056
3057 with EXPR as VAR:
3058 BLOCK
3059
3060 It is implemented roughly as:
3061
Thomas Wouters477c8d52006-05-27 19:21:47 +00003062 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003063 exit = context.__exit__ # not calling it
3064 value = context.__enter__()
3065 try:
3066 VAR = value # if VAR present in the syntax
3067 BLOCK
3068 finally:
3069 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003073 exit(*exc)
3074 */
3075static int
3076compiler_with(struct compiler *c, stmt_ty s)
3077{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003078 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079
3080 assert(s->kind == With_kind);
3081
Guido van Rossumc2e20742006-02-27 22:32:47 +00003082 block = compiler_new_block(c);
3083 finally = compiler_new_block(c);
3084 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003085 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003086
Thomas Wouters477c8d52006-05-27 19:21:47 +00003087 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003088 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003089 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003090
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003091 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003092 compiler_use_next_block(c, block);
3093 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003094 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003095 }
3096
3097 if (s->v.With.optional_vars) {
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003098 VISIT(c, expr, s->v.With.optional_vars);
3099 }
3100 else {
3101 /* Discard result from context.__enter__() */
3102 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003103 }
3104
3105 /* BLOCK code */
3106 VISIT_SEQ(c, stmt, s->v.With.body);
3107
3108 /* End of try block; start the finally block */
3109 ADDOP(c, POP_BLOCK);
3110 compiler_pop_fblock(c, FINALLY_TRY, block);
3111
3112 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3113 compiler_use_next_block(c, finally);
3114 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003115 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003116
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003117 /* Finally block starts; context.__exit__ is on the stack under
3118 the exception or return information. Just issue our magic
3119 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003120 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003121
3122 /* Finally block ends. */
3123 ADDOP(c, END_FINALLY);
3124 compiler_pop_fblock(c, FINALLY_END, finally);
3125 return 1;
3126}
3127
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128static int
3129compiler_visit_expr(struct compiler *c, expr_ty e)
3130{
3131 int i, n;
3132
Thomas Wouters89f507f2006-12-13 04:49:30 +00003133 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003134 set a new line number for the next instruction.
3135 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136 if (e->lineno > c->u->u_lineno) {
3137 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003138 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139 }
3140 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003141 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003143 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144 VISIT(c, expr, e->v.BinOp.left);
3145 VISIT(c, expr, e->v.BinOp.right);
3146 ADDOP(c, binop(c, e->v.BinOp.op));
3147 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149 VISIT(c, expr, e->v.UnaryOp.operand);
3150 ADDOP(c, unaryop(e->v.UnaryOp.op));
3151 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003152 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003153 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003154 case IfExp_kind:
3155 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003158 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003160 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003161 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003162 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003163 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003164 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165 }
3166 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003167 case Set_kind:
3168 n = asdl_seq_LEN(e->v.Set.elts);
3169 VISIT_SEQ(c, expr, e->v.Set.elts);
3170 ADDOP_I(c, BUILD_SET, n);
3171 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003172 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003174 case ListComp_kind:
3175 return compiler_listcomp(c, e);
3176 case SetComp_kind:
3177 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003178 case DictComp_kind:
3179 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 case Yield_kind:
3181 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003182 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183 if (e->v.Yield.value) {
3184 VISIT(c, expr, e->v.Yield.value);
3185 }
3186 else {
3187 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3188 }
3189 ADDOP(c, YIELD_VALUE);
3190 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003191 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3197 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3200 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003201 case Bytes_kind:
3202 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003203 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003204 case Ellipsis_kind:
3205 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3206 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003208 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209 if (e->v.Attribute.ctx != AugStore)
3210 VISIT(c, expr, e->v.Attribute.value);
3211 switch (e->v.Attribute.ctx) {
3212 case AugLoad:
3213 ADDOP(c, DUP_TOP);
3214 /* Fall through to load */
3215 case Load:
3216 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3217 break;
3218 case AugStore:
3219 ADDOP(c, ROT_TWO);
3220 /* Fall through to save */
3221 case Store:
3222 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3223 break;
3224 case Del:
3225 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3226 break;
3227 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003228 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003229 PyErr_SetString(PyExc_SystemError,
3230 "param invalid in attribute expression");
3231 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 }
3233 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003234 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235 switch (e->v.Subscript.ctx) {
3236 case AugLoad:
3237 VISIT(c, expr, e->v.Subscript.value);
3238 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3239 break;
3240 case Load:
3241 VISIT(c, expr, e->v.Subscript.value);
3242 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3243 break;
3244 case AugStore:
3245 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3246 break;
3247 case Store:
3248 VISIT(c, expr, e->v.Subscript.value);
3249 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3250 break;
3251 case Del:
3252 VISIT(c, expr, e->v.Subscript.value);
3253 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3254 break;
3255 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003256 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003257 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003258 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003259 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 }
3261 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003262 case Starred_kind:
3263 switch (e->v.Starred.ctx) {
3264 case Store:
3265 /* In all legitimate cases, the Starred node was already replaced
3266 * by compiler_list/compiler_tuple. XXX: is that okay? */
3267 return compiler_error(c,
3268 "starred assignment target must be in a list or tuple");
3269 default:
3270 return compiler_error(c,
3271 "can use starred expression only as assignment target");
3272 }
3273 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003274 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3276 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003277 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003279 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 return compiler_tuple(c, e);
3281 }
3282 return 1;
3283}
3284
3285static int
3286compiler_augassign(struct compiler *c, stmt_ty s)
3287{
3288 expr_ty e = s->v.AugAssign.target;
3289 expr_ty auge;
3290
3291 assert(s->kind == AugAssign_kind);
3292
3293 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003294 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003296 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003297 if (auge == NULL)
3298 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299 VISIT(c, expr, auge);
3300 VISIT(c, expr, s->v.AugAssign.value);
3301 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3302 auge->v.Attribute.ctx = AugStore;
3303 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304 break;
3305 case Subscript_kind:
3306 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003307 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003308 if (auge == NULL)
3309 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310 VISIT(c, expr, auge);
3311 VISIT(c, expr, s->v.AugAssign.value);
3312 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003313 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003315 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003317 if (!compiler_nameop(c, e->v.Name.id, Load))
3318 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319 VISIT(c, expr, s->v.AugAssign.value);
3320 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3321 return compiler_nameop(c, e->v.Name.id, Store);
3322 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003323 PyErr_Format(PyExc_SystemError,
3324 "invalid node type (%d) for augmented assignment",
3325 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003326 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327 }
3328 return 1;
3329}
3330
3331static int
3332compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3333{
3334 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003335 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3336 PyErr_SetString(PyExc_SystemError,
3337 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340 f = &c->u->u_fblock[c->u->u_nfblocks++];
3341 f->fb_type = t;
3342 f->fb_block = b;
3343 return 1;
3344}
3345
3346static void
3347compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3348{
3349 struct compiler_unit *u = c->u;
3350 assert(u->u_nfblocks > 0);
3351 u->u_nfblocks--;
3352 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3353 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3354}
3355
Thomas Wouters89f507f2006-12-13 04:49:30 +00003356static int
3357compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003358 int i;
3359 struct compiler_unit *u = c->u;
3360 for (i = 0; i < u->u_nfblocks; ++i) {
3361 if (u->u_fblock[i].fb_type == LOOP)
3362 return 1;
3363 }
3364 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003365}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366/* Raises a SyntaxError and returns 0.
3367 If something goes wrong, a different exception may be raised.
3368*/
3369
3370static int
3371compiler_error(struct compiler *c, const char *errstr)
3372{
3373 PyObject *loc;
3374 PyObject *u = NULL, *v = NULL;
3375
3376 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3377 if (!loc) {
3378 Py_INCREF(Py_None);
3379 loc = Py_None;
3380 }
3381 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3382 Py_None, loc);
3383 if (!u)
3384 goto exit;
3385 v = Py_BuildValue("(zO)", errstr, u);
3386 if (!v)
3387 goto exit;
3388 PyErr_SetObject(PyExc_SyntaxError, v);
3389 exit:
3390 Py_DECREF(loc);
3391 Py_XDECREF(u);
3392 Py_XDECREF(v);
3393 return 0;
3394}
3395
3396static int
3397compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003398 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003400 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003402 /* XXX this code is duplicated */
3403 switch (ctx) {
3404 case AugLoad: /* fall through to Load */
3405 case Load: op = BINARY_SUBSCR; break;
3406 case AugStore:/* fall through to Store */
3407 case Store: op = STORE_SUBSCR; break;
3408 case Del: op = DELETE_SUBSCR; break;
3409 case Param:
3410 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003411 "invalid %s kind %d in subscript\n",
3412 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003413 return 0;
3414 }
3415 if (ctx == AugLoad) {
3416 ADDOP_I(c, DUP_TOPX, 2);
3417 }
3418 else if (ctx == AugStore) {
3419 ADDOP(c, ROT_THREE);
3420 }
3421 ADDOP(c, op);
3422 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423}
3424
3425static int
3426compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3427{
3428 int n = 2;
3429 assert(s->kind == Slice_kind);
3430
3431 /* only handles the cases where BUILD_SLICE is emitted */
3432 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003433 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434 }
3435 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003436 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003437 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003438
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003440 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441 }
3442 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003443 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444 }
3445
3446 if (s->v.Slice.step) {
3447 n++;
3448 VISIT(c, expr, s->v.Slice.step);
3449 }
3450 ADDOP_I(c, BUILD_SLICE, n);
3451 return 1;
3452}
3453
3454static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3456 expr_context_ty ctx)
3457{
3458 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459 case Slice_kind:
3460 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461 case Index_kind:
3462 VISIT(c, expr, s->v.Index.value);
3463 break;
3464 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003465 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003466 PyErr_SetString(PyExc_SystemError,
3467 "extended slice invalid in nested slice");
3468 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469 }
3470 return 1;
3471}
3472
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473static int
3474compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3475{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003476 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003478 case Index_kind:
3479 kindname = "index";
3480 if (ctx != AugStore) {
3481 VISIT(c, expr, s->v.Index.value);
3482 }
3483 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003485 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003486 if (ctx != AugStore) {
3487 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488 return 0;
3489 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003490 break;
3491 case ExtSlice_kind:
3492 kindname = "extended slice";
3493 if (ctx != AugStore) {
3494 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3495 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003496 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003497 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003498 if (!compiler_visit_nested_slice(c, sub, ctx))
3499 return 0;
3500 }
3501 ADDOP_I(c, BUILD_TUPLE, n);
3502 }
3503 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003504 default:
3505 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003506 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003507 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003508 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003509 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510}
3511
Thomas Wouters89f507f2006-12-13 04:49:30 +00003512/* End of the compiler section, beginning of the assembler section */
3513
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514/* do depth-first search of basic block graph, starting with block.
3515 post records the block indices in post-order.
3516
3517 XXX must handle implicit jumps from one block to next
3518*/
3519
Thomas Wouters89f507f2006-12-13 04:49:30 +00003520struct assembler {
3521 PyObject *a_bytecode; /* string containing bytecode */
3522 int a_offset; /* offset into bytecode */
3523 int a_nblocks; /* number of reachable blocks */
3524 basicblock **a_postorder; /* list of blocks in dfs postorder */
3525 PyObject *a_lnotab; /* string containing lnotab */
3526 int a_lnotab_off; /* offset into lnotab */
3527 int a_lineno; /* last lineno of emitted instruction */
3528 int a_lineno_off; /* bytecode offset of last lineno */
3529};
3530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531static void
3532dfs(struct compiler *c, basicblock *b, struct assembler *a)
3533{
3534 int i;
3535 struct instr *instr = NULL;
3536
3537 if (b->b_seen)
3538 return;
3539 b->b_seen = 1;
3540 if (b->b_next != NULL)
3541 dfs(c, b->b_next, a);
3542 for (i = 0; i < b->b_iused; i++) {
3543 instr = &b->b_instr[i];
3544 if (instr->i_jrel || instr->i_jabs)
3545 dfs(c, instr->i_target, a);
3546 }
3547 a->a_postorder[a->a_nblocks++] = b;
3548}
3549
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003550static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3552{
3553 int i;
3554 struct instr *instr;
3555 if (b->b_seen || b->b_startdepth >= depth)
3556 return maxdepth;
3557 b->b_seen = 1;
3558 b->b_startdepth = depth;
3559 for (i = 0; i < b->b_iused; i++) {
3560 instr = &b->b_instr[i];
3561 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3562 if (depth > maxdepth)
3563 maxdepth = depth;
3564 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3565 if (instr->i_jrel || instr->i_jabs) {
3566 maxdepth = stackdepth_walk(c, instr->i_target,
3567 depth, maxdepth);
3568 if (instr->i_opcode == JUMP_ABSOLUTE ||
3569 instr->i_opcode == JUMP_FORWARD) {
3570 goto out; /* remaining code is dead */
3571 }
3572 }
3573 }
3574 if (b->b_next)
3575 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3576out:
3577 b->b_seen = 0;
3578 return maxdepth;
3579}
3580
3581/* Find the flow path that needs the largest stack. We assume that
3582 * cycles in the flow graph have no net effect on the stack depth.
3583 */
3584static int
3585stackdepth(struct compiler *c)
3586{
3587 basicblock *b, *entryblock;
3588 entryblock = NULL;
3589 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3590 b->b_seen = 0;
3591 b->b_startdepth = INT_MIN;
3592 entryblock = b;
3593 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003594 if (!entryblock)
3595 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 return stackdepth_walk(c, entryblock, 0, 0);
3597}
3598
3599static int
3600assemble_init(struct assembler *a, int nblocks, int firstlineno)
3601{
3602 memset(a, 0, sizeof(struct assembler));
3603 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003604 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 if (!a->a_bytecode)
3606 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003607 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608 if (!a->a_lnotab)
3609 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003610 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3611 PyErr_NoMemory();
3612 return 0;
3613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003615 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003616 if (!a->a_postorder) {
3617 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003619 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 return 1;
3621}
3622
3623static void
3624assemble_free(struct assembler *a)
3625{
3626 Py_XDECREF(a->a_bytecode);
3627 Py_XDECREF(a->a_lnotab);
3628 if (a->a_postorder)
3629 PyObject_Free(a->a_postorder);
3630}
3631
3632/* Return the size of a basic block in bytes. */
3633
3634static int
3635instrsize(struct instr *instr)
3636{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003637 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003638 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003639 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003640 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3641 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642}
3643
3644static int
3645blocksize(basicblock *b)
3646{
3647 int i;
3648 int size = 0;
3649
3650 for (i = 0; i < b->b_iused; i++)
3651 size += instrsize(&b->b_instr[i]);
3652 return size;
3653}
3654
3655/* All about a_lnotab.
3656
3657c_lnotab is an array of unsigned bytes disguised as a Python string.
3658It is used to map bytecode offsets to source code line #s (when needed
3659for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003660
Tim Peters2a7f3842001-06-09 09:26:21 +00003661The array is conceptually a list of
3662 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003663pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003664
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003665 byte code offset source code line number
3666 0 1
3667 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003668 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003669 350 307
3670 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003671
3672The first trick is that these numbers aren't stored, only the increments
3673from one row to the next (this doesn't really work, but it's a start):
3674
3675 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3676
3677The second trick is that an unsigned byte can't hold negative values, or
3678values larger than 255, so (a) there's a deep assumption that byte code
3679offsets and their corresponding line #s both increase monotonically, and (b)
3680if at least one column jumps by more than 255 from one row to the next, more
3681than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003682from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003683part. A user of c_lnotab desiring to find the source line number
3684corresponding to a bytecode address A should do something like this
3685
3686 lineno = addr = 0
3687 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003688 addr += addr_incr
3689 if addr > A:
3690 return lineno
3691 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003692
3693In order for this to work, when the addr field increments by more than 255,
3694the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003695increment is < 256. So, in the example above, assemble_lnotab (it used
3696to be called com_set_lineno) should not (as was actually done until 2.2)
3697expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003698 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003699*/
3700
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003701static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003703{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704 int d_bytecode, d_lineno;
3705 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003706 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003707
3708 d_bytecode = a->a_offset - a->a_lineno_off;
3709 d_lineno = i->i_lineno - a->a_lineno;
3710
3711 assert(d_bytecode >= 0);
3712 assert(d_lineno >= 0);
3713
Christian Heimes2202f872008-02-06 14:31:34 +00003714 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003715 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003716
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003718 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003720 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003722 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003724 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003726 else {
3727 PyErr_NoMemory();
3728 return 0;
3729 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003730 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003732 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003733 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003734 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003735 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736 *lnotab++ = 255;
3737 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003738 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 d_bytecode -= ncodes * 255;
3740 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003741 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742 assert(d_bytecode <= 255);
3743 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003744 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003746 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003748 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003749 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003750 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003752 else {
3753 PyErr_NoMemory();
3754 return 0;
3755 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003756 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003758 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003759 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003760 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003762 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003764 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003766 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003767 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768 d_lineno -= ncodes * 255;
3769 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003770 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003771
Christian Heimes72b710a2008-05-26 13:28:38 +00003772 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003774 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003775 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003776 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003777 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003778 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 a->a_lnotab_off += 2;
3781 if (d_bytecode) {
3782 *lnotab++ = d_bytecode;
3783 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003784 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003785 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 *lnotab++ = 0;
3787 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003788 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789 a->a_lineno = i->i_lineno;
3790 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003791 return 1;
3792}
3793
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794/* assemble_emit()
3795 Extend the bytecode with a new instruction.
3796 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003797*/
3798
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003799static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003801{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003802 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003803 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 char *code;
3805
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003806 size = instrsize(i);
3807 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003809 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003810 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003811 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003812 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003814 if (len > PY_SSIZE_T_MAX / 2)
3815 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003816 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003817 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003818 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003819 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003821 if (size == 6) {
3822 assert(i->i_hasarg);
3823 *code++ = (char)EXTENDED_ARG;
3824 *code++ = ext & 0xff;
3825 *code++ = ext >> 8;
3826 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003827 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003828 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003829 if (i->i_hasarg) {
3830 assert(size == 3 || size == 6);
3831 *code++ = arg & 0xff;
3832 *code++ = arg >> 8;
3833 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003834 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003835}
3836
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003837static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003838assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003839{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003841 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003842 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003843
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844 /* Compute the size of each block and fixup jump args.
3845 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003846start:
3847 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003849 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850 bsize = blocksize(b);
3851 b->b_offset = totsize;
3852 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003853 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003854 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3856 bsize = b->b_offset;
3857 for (i = 0; i < b->b_iused; i++) {
3858 struct instr *instr = &b->b_instr[i];
3859 /* Relative jumps are computed relative to
3860 the instruction pointer after fetching
3861 the jump instruction.
3862 */
3863 bsize += instrsize(instr);
3864 if (instr->i_jabs)
3865 instr->i_oparg = instr->i_target->b_offset;
3866 else if (instr->i_jrel) {
3867 int delta = instr->i_target->b_offset - bsize;
3868 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003869 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003870 else
3871 continue;
3872 if (instr->i_oparg > 0xffff)
3873 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003874 }
3875 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003876
3877 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003878 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003879 with a better solution.
3880
3881 In the meantime, should the goto be dropped in favor
3882 of a loop?
3883
3884 The issue is that in the first loop blocksize() is called
3885 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003886 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003887 i_oparg is calculated in the second loop above.
3888
3889 So we loop until we stop seeing new EXTENDED_ARGs.
3890 The only EXTENDED_ARGs that could be popping up are
3891 ones in jump instructions. So this should converge
3892 fairly quickly.
3893 */
3894 if (last_extended_arg_count != extended_arg_count) {
3895 last_extended_arg_count = extended_arg_count;
3896 goto start;
3897 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003898}
3899
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003900static PyObject *
3901dict_keys_inorder(PyObject *dict, int offset)
3902{
3903 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003904 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003905
3906 tuple = PyTuple_New(size);
3907 if (tuple == NULL)
3908 return NULL;
3909 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003910 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003911 /* The keys of the dictionary are tuples. (see compiler_add_o)
3912 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003913 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003914 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003915 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003916 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003917 PyTuple_SET_ITEM(tuple, i - offset, k);
3918 }
3919 return tuple;
3920}
3921
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003922static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003924{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003925 PySTEntryObject *ste = c->u->u_ste;
3926 int flags = 0, n;
3927 if (ste->ste_type != ModuleBlock)
3928 flags |= CO_NEWLOCALS;
3929 if (ste->ste_type == FunctionBlock) {
3930 if (!ste->ste_unoptimized)
3931 flags |= CO_OPTIMIZED;
3932 if (ste->ste_nested)
3933 flags |= CO_NESTED;
3934 if (ste->ste_generator)
3935 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003936 if (ste->ste_varargs)
3937 flags |= CO_VARARGS;
3938 if (ste->ste_varkeywords)
3939 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003940 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003941
3942 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003943 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003944
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945 n = PyDict_Size(c->u->u_freevars);
3946 if (n < 0)
3947 return -1;
3948 if (n == 0) {
3949 n = PyDict_Size(c->u->u_cellvars);
3950 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003951 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003952 if (n == 0) {
3953 flags |= CO_NOFREE;
3954 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003955 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003956
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003957 return flags;
3958}
3959
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003960static PyCodeObject *
3961makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003962{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003963 PyObject *tmp;
3964 PyCodeObject *co = NULL;
3965 PyObject *consts = NULL;
3966 PyObject *names = NULL;
3967 PyObject *varnames = NULL;
3968 PyObject *filename = NULL;
3969 PyObject *name = NULL;
3970 PyObject *freevars = NULL;
3971 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003972 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003973 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003974
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003975 tmp = dict_keys_inorder(c->u->u_consts, 0);
3976 if (!tmp)
3977 goto error;
3978 consts = PySequence_List(tmp); /* optimize_code requires a list */
3979 Py_DECREF(tmp);
3980
3981 names = dict_keys_inorder(c->u->u_names, 0);
3982 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3983 if (!consts || !names || !varnames)
3984 goto error;
3985
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003986 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3987 if (!cellvars)
3988 goto error;
3989 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3990 if (!freevars)
3991 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003992 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003993 if (!filename)
3994 goto error;
3995
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003996 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003997 flags = compute_code_flags(c);
3998 if (flags < 0)
3999 goto error;
4000
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004001 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004002 if (!bytecode)
4003 goto error;
4004
4005 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4006 if (!tmp)
4007 goto error;
4008 Py_DECREF(consts);
4009 consts = tmp;
4010
Guido van Rossum4f72a782006-10-27 23:31:49 +00004011 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4012 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004013 bytecode, consts, names, varnames,
4014 freevars, cellvars,
4015 filename, c->u->u_name,
4016 c->u->u_firstlineno,
4017 a->a_lnotab);
4018 error:
4019 Py_XDECREF(consts);
4020 Py_XDECREF(names);
4021 Py_XDECREF(varnames);
4022 Py_XDECREF(filename);
4023 Py_XDECREF(name);
4024 Py_XDECREF(freevars);
4025 Py_XDECREF(cellvars);
4026 Py_XDECREF(bytecode);
4027 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004028}
4029
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004030
4031/* For debugging purposes only */
4032#if 0
4033static void
4034dump_instr(const struct instr *i)
4035{
4036 const char *jrel = i->i_jrel ? "jrel " : "";
4037 const char *jabs = i->i_jabs ? "jabs " : "";
4038 char arg[128];
4039
4040 *arg = '\0';
4041 if (i->i_hasarg)
4042 sprintf(arg, "arg: %d ", i->i_oparg);
4043
4044 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4045 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4046}
4047
4048static void
4049dump_basicblock(const basicblock *b)
4050{
4051 const char *seen = b->b_seen ? "seen " : "";
4052 const char *b_return = b->b_return ? "return " : "";
4053 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4054 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4055 if (b->b_instr) {
4056 int i;
4057 for (i = 0; i < b->b_iused; i++) {
4058 fprintf(stderr, " [%02d] ", i);
4059 dump_instr(b->b_instr + i);
4060 }
4061 }
4062}
4063#endif
4064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065static PyCodeObject *
4066assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004067{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068 basicblock *b, *entryblock;
4069 struct assembler a;
4070 int i, j, nblocks;
4071 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004072
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073 /* Make sure every block that falls off the end returns None.
4074 XXX NEXT_BLOCK() isn't quite right, because if the last
4075 block ends with a jump or return b_next shouldn't set.
4076 */
4077 if (!c->u->u_curblock->b_return) {
4078 NEXT_BLOCK(c);
4079 if (addNone)
4080 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4081 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004082 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004083
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004084 nblocks = 0;
4085 entryblock = NULL;
4086 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4087 nblocks++;
4088 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004089 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004090
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004091 /* Set firstlineno if it wasn't explicitly set. */
4092 if (!c->u->u_firstlineno) {
4093 if (entryblock && entryblock->b_instr)
4094 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4095 else
4096 c->u->u_firstlineno = 1;
4097 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4099 goto error;
4100 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004102 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004103 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004104
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105 /* Emit code in reverse postorder from dfs. */
4106 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004107 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004108 for (j = 0; j < b->b_iused; j++)
4109 if (!assemble_emit(&a, &b->b_instr[j]))
4110 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004111 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004112
Christian Heimes72b710a2008-05-26 13:28:38 +00004113 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004115 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004117
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004118 co = makecode(c, &a);
4119 error:
4120 assemble_free(&a);
4121 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004122}