blob: 11d7c3317d5728948f88405c501078af9c95d8d8 [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;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000752 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000753 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000754 case STORE_LOCALS:
755 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756 case RETURN_VALUE:
757 return -1;
758 case IMPORT_STAR:
759 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760 case YIELD_VALUE:
761 return 0;
762
763 case POP_BLOCK:
764 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000765 case POP_EXCEPT:
766 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767 case END_FINALLY:
768 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769
770 case STORE_NAME:
771 return -1;
772 case DELETE_NAME:
773 return 0;
774 case UNPACK_SEQUENCE:
775 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000776 case UNPACK_EX:
777 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778 case FOR_ITER:
779 return 1;
780
781 case STORE_ATTR:
782 return -2;
783 case DELETE_ATTR:
784 return -1;
785 case STORE_GLOBAL:
786 return -1;
787 case DELETE_GLOBAL:
788 return 0;
789 case DUP_TOPX:
790 return oparg;
791 case LOAD_CONST:
792 return 1;
793 case LOAD_NAME:
794 return 1;
795 case BUILD_TUPLE:
796 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000797 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000798 return 1-oparg;
799 case BUILD_MAP:
800 return 1;
801 case LOAD_ATTR:
802 return 0;
803 case COMPARE_OP:
804 return -1;
805 case IMPORT_NAME:
806 return 0;
807 case IMPORT_FROM:
808 return 1;
809
810 case JUMP_FORWARD:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000811 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
812 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813 case JUMP_ABSOLUTE:
814 return 0;
815
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000816 case POP_JUMP_IF_FALSE:
817 case POP_JUMP_IF_TRUE:
818 return -1;
819
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000820 case LOAD_GLOBAL:
821 return 1;
822
823 case CONTINUE_LOOP:
824 return 0;
825 case SETUP_LOOP:
826 return 0;
827 case SETUP_EXCEPT:
828 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000829 return 6; /* can push 3 values for the new exception
830 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831
832 case LOAD_FAST:
833 return 1;
834 case STORE_FAST:
835 return -1;
836 case DELETE_FAST:
837 return 0;
838
839 case RAISE_VARARGS:
840 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000841#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842 case CALL_FUNCTION:
843 return -NARGS(oparg);
844 case CALL_FUNCTION_VAR:
845 case CALL_FUNCTION_KW:
846 return -NARGS(oparg)-1;
847 case CALL_FUNCTION_VAR_KW:
848 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000849 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000850 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000851 case MAKE_CLOSURE:
852 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000853#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854 case BUILD_SLICE:
855 if (oparg == 3)
856 return -2;
857 else
858 return -1;
859
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860 case LOAD_CLOSURE:
861 return 1;
862 case LOAD_DEREF:
863 return 1;
864 case STORE_DEREF:
865 return -1;
866 default:
867 fprintf(stderr, "opcode = %d\n", opcode);
868 Py_FatalError("opcode_stack_effect()");
869
870 }
871 return 0; /* not reachable */
872}
873
874/* Add an opcode with no argument.
875 Returns 0 on failure, 1 on success.
876*/
877
878static int
879compiler_addop(struct compiler *c, int opcode)
880{
881 basicblock *b;
882 struct instr *i;
883 int off;
884 off = compiler_next_instr(c, c->u->u_curblock);
885 if (off < 0)
886 return 0;
887 b = c->u->u_curblock;
888 i = &b->b_instr[off];
889 i->i_opcode = opcode;
890 i->i_hasarg = 0;
891 if (opcode == RETURN_VALUE)
892 b->b_return = 1;
893 compiler_set_lineno(c, off);
894 return 1;
895}
896
897static int
898compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
899{
900 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000901 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000902 unsigned char *p, *q;
903 Py_complex z;
904 double d;
905 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000907 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000908 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
909 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000910 d = PyFloat_AS_DOUBLE(o);
911 p = (unsigned char*) &d;
912 /* all we need is to make the tuple different in either the 0.0
913 * or -0.0 case from all others, just to avoid the "coercion".
914 */
915 if (*p==0 && p[sizeof(double)-1]==0)
916 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
917 else
918 t = PyTuple_Pack(2, o, o->ob_type);
919 }
920 else if (PyComplex_Check(o)) {
921 /* complex case is even messier: we need to make complex(x,
922 0.) different from complex(x, -0.) and complex(0., y)
923 different from complex(-0., y), for any x and y. In
924 particular, all four complex zeros should be
925 distinguished.*/
926 z = PyComplex_AsCComplex(o);
927 p = (unsigned char*) &(z.real);
928 q = (unsigned char*) &(z.imag);
929 /* all that matters here is that on IEEE platforms
930 real_part_zero will be true if z.real == 0., and false if
931 z.real == -0. In fact, real_part_zero will also be true
932 for some other rarely occurring nonzero floats, but this
933 doesn't matter. Similar comments apply to
934 imag_part_zero. */
935 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
936 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
937 if (real_part_zero && imag_part_zero) {
938 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
939 }
940 else if (real_part_zero && !imag_part_zero) {
941 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
942 }
943 else if (!real_part_zero && imag_part_zero) {
944 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
945 }
946 else {
947 t = PyTuple_Pack(2, o, o->ob_type);
948 }
949 }
950 else {
951 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000952 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000953 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000954 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000955
956 v = PyDict_GetItem(dict, t);
957 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000958 if (PyErr_Occurred())
959 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000960 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000961 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000962 if (!v) {
963 Py_DECREF(t);
964 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000966 if (PyDict_SetItem(dict, t, v) < 0) {
967 Py_DECREF(t);
968 Py_DECREF(v);
969 return -1;
970 }
971 Py_DECREF(v);
972 }
973 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000974 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000975 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000976 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977}
978
979static int
980compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
981 PyObject *o)
982{
983 int arg = compiler_add_o(c, dict, o);
984 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000985 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986 return compiler_addop_i(c, opcode, arg);
987}
988
989static int
990compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000991 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992{
993 int arg;
994 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
995 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997 arg = compiler_add_o(c, dict, mangled);
998 Py_DECREF(mangled);
999 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001 return compiler_addop_i(c, opcode, arg);
1002}
1003
1004/* Add an opcode with an integer argument.
1005 Returns 0 on failure, 1 on success.
1006*/
1007
1008static int
1009compiler_addop_i(struct compiler *c, int opcode, int oparg)
1010{
1011 struct instr *i;
1012 int off;
1013 off = compiler_next_instr(c, c->u->u_curblock);
1014 if (off < 0)
1015 return 0;
1016 i = &c->u->u_curblock->b_instr[off];
1017 i->i_opcode = opcode;
1018 i->i_oparg = oparg;
1019 i->i_hasarg = 1;
1020 compiler_set_lineno(c, off);
1021 return 1;
1022}
1023
1024static int
1025compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1026{
1027 struct instr *i;
1028 int off;
1029
1030 assert(b != NULL);
1031 off = compiler_next_instr(c, c->u->u_curblock);
1032 if (off < 0)
1033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034 i = &c->u->u_curblock->b_instr[off];
1035 i->i_opcode = opcode;
1036 i->i_target = b;
1037 i->i_hasarg = 1;
1038 if (absolute)
1039 i->i_jabs = 1;
1040 else
1041 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001042 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001043 return 1;
1044}
1045
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001046/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1047 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048 it as the current block. NEXT_BLOCK() also creates an implicit jump
1049 from the current block to the new block.
1050*/
1051
Thomas Wouters89f507f2006-12-13 04:49:30 +00001052/* The returns inside these macros make it impossible to decref objects
1053 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054*/
1055
1056
1057#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001058 if (compiler_use_new_block((C)) == NULL) \
1059 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060}
1061
1062#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001063 if (compiler_next_block((C)) == NULL) \
1064 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065}
1066
1067#define ADDOP(C, OP) { \
1068 if (!compiler_addop((C), (OP))) \
1069 return 0; \
1070}
1071
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001072#define ADDOP_IN_SCOPE(C, OP) { \
1073 if (!compiler_addop((C), (OP))) { \
1074 compiler_exit_scope(c); \
1075 return 0; \
1076 } \
1077}
1078
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079#define ADDOP_O(C, OP, O, TYPE) { \
1080 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1081 return 0; \
1082}
1083
1084#define ADDOP_NAME(C, OP, O, TYPE) { \
1085 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1086 return 0; \
1087}
1088
1089#define ADDOP_I(C, OP, O) { \
1090 if (!compiler_addop_i((C), (OP), (O))) \
1091 return 0; \
1092}
1093
1094#define ADDOP_JABS(C, OP, O) { \
1095 if (!compiler_addop_j((C), (OP), (O), 1)) \
1096 return 0; \
1097}
1098
1099#define ADDOP_JREL(C, OP, O) { \
1100 if (!compiler_addop_j((C), (OP), (O), 0)) \
1101 return 0; \
1102}
1103
1104/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1105 the ASDL name to synthesize the name of the C type and the visit function.
1106*/
1107
1108#define VISIT(C, TYPE, V) {\
1109 if (!compiler_visit_ ## TYPE((C), (V))) \
1110 return 0; \
1111}
1112
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001113#define VISIT_IN_SCOPE(C, TYPE, V) {\
1114 if (!compiler_visit_ ## TYPE((C), (V))) { \
1115 compiler_exit_scope(c); \
1116 return 0; \
1117 } \
1118}
1119
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120#define VISIT_SLICE(C, V, CTX) {\
1121 if (!compiler_visit_slice((C), (V), (CTX))) \
1122 return 0; \
1123}
1124
1125#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001126 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001128 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001129 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 if (!compiler_visit_ ## TYPE((C), elt)) \
1131 return 0; \
1132 } \
1133}
1134
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001135#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001136 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001137 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001138 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001139 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001140 if (!compiler_visit_ ## TYPE((C), elt)) { \
1141 compiler_exit_scope(c); \
1142 return 0; \
1143 } \
1144 } \
1145}
1146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147static int
1148compiler_isdocstring(stmt_ty s)
1149{
1150 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 return s->v.Expr.value->kind == Str_kind;
1153}
1154
1155/* Compile a sequence of statements, checking for a docstring. */
1156
1157static int
1158compiler_body(struct compiler *c, asdl_seq *stmts)
1159{
1160 int i = 0;
1161 stmt_ty st;
1162
1163 if (!asdl_seq_LEN(stmts))
1164 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001165 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001166 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1167 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 i = 1;
1169 VISIT(c, expr, st->v.Expr.value);
1170 if (!compiler_nameop(c, __doc__, Store))
1171 return 0;
1172 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001173 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001174 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175 return 1;
1176}
1177
1178static PyCodeObject *
1179compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001180{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001181 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001182 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 static PyObject *module;
1184 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001185 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 if (!module)
1187 return NULL;
1188 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001189 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1190 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001191 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192 switch (mod->kind) {
1193 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001194 if (!compiler_body(c, mod->v.Module.body)) {
1195 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001197 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 break;
1199 case Interactive_kind:
1200 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001201 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001202 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 break;
1204 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001205 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001206 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207 break;
1208 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001209 PyErr_SetString(PyExc_SystemError,
1210 "suite should not be possible");
1211 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001212 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001213 PyErr_Format(PyExc_SystemError,
1214 "module kind %d should not be possible",
1215 mod->kind);
1216 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 co = assemble(c, addNone);
1219 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001220 return co;
1221}
1222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223/* The test for LOCAL must come before the test for FREE in order to
1224 handle classes where name is both local and free. The local var is
1225 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001226*/
1227
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228static int
1229get_ref_type(struct compiler *c, PyObject *name)
1230{
1231 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001232 if (scope == 0) {
1233 char buf[350];
1234 PyOS_snprintf(buf, sizeof(buf),
1235 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001236 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001237 PyBytes_AS_STRING(name),
1238 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001239 PyObject_REPR(c->u->u_ste->ste_id),
1240 c->c_filename,
1241 PyObject_REPR(c->u->u_ste->ste_symbols),
1242 PyObject_REPR(c->u->u_varnames),
1243 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 Py_FatalError(buf);
1246 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001247
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001248 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249}
1250
1251static int
1252compiler_lookup_arg(PyObject *dict, PyObject *name)
1253{
1254 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001255 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001257 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001259 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001261 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001262 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263}
1264
1265static int
1266compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1267{
1268 int i, free = PyCode_GetNumFree(co);
1269 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001270 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1271 ADDOP_I(c, MAKE_FUNCTION, args);
1272 return 1;
1273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274 for (i = 0; i < free; ++i) {
1275 /* Bypass com_addop_varname because it will generate
1276 LOAD_DEREF but LOAD_CLOSURE is needed.
1277 */
1278 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1279 int arg, reftype;
1280
1281 /* Special case: If a class contains a method with a
1282 free variable that has the same name as a method,
1283 the name will be considered free *and* local in the
1284 class. It should be handled by the closure, as
1285 well as by the normal name loookup logic.
1286 */
1287 reftype = get_ref_type(c, name);
1288 if (reftype == CELL)
1289 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1290 else /* (reftype == FREE) */
1291 arg = compiler_lookup_arg(c->u->u_freevars, name);
1292 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001293 fprintf(stderr,
1294 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295 "freevars of %s: %s\n",
1296 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001297 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001299 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300 PyObject_REPR(co->co_freevars));
1301 Py_FatalError("compiler_make_closure()");
1302 }
1303 ADDOP_I(c, LOAD_CLOSURE, arg);
1304 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001305 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, MAKE_CLOSURE, args);
1308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
1311static int
1312compiler_decorators(struct compiler *c, asdl_seq* decos)
1313{
1314 int i;
1315
1316 if (!decos)
1317 return 1;
1318
1319 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001320 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321 }
1322 return 1;
1323}
1324
1325static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001326compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1327 asdl_seq *kw_defaults)
1328{
1329 int i, default_count = 0;
1330 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001331 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001332 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1333 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001334 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001335 if (!compiler_visit_expr(c, default_)) {
1336 return -1;
1337 }
1338 default_count++;
1339 }
1340 }
1341 return default_count;
1342}
1343
1344static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001345compiler_visit_argannotation(struct compiler *c, identifier id,
1346 expr_ty annotation, PyObject *names)
1347{
1348 if (annotation) {
1349 VISIT(c, expr, annotation);
1350 if (PyList_Append(names, id))
1351 return -1;
1352 }
1353 return 0;
1354}
1355
1356static int
1357compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1358 PyObject *names)
1359{
1360 int i, error;
1361 for (i = 0; i < asdl_seq_LEN(args); i++) {
1362 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001363 error = compiler_visit_argannotation(
1364 c,
1365 arg->arg,
1366 arg->annotation,
1367 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001368 if (error)
1369 return error;
1370 }
1371 return 0;
1372}
1373
1374static int
1375compiler_visit_annotations(struct compiler *c, arguments_ty args,
1376 expr_ty returns)
1377{
Guido van Rossum0240b922007-02-26 21:23:50 +00001378 /* Push arg annotations and a list of the argument names. Return the #
1379 of items pushed. The expressions are evaluated out-of-order wrt the
1380 source code.
1381
1382 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1383 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001384 static identifier return_str;
1385 PyObject *names;
1386 int len;
1387 names = PyList_New(0);
1388 if (!names)
1389 return -1;
1390
1391 if (compiler_visit_argannotations(c, args->args, names))
1392 goto error;
1393 if (args->varargannotation &&
1394 compiler_visit_argannotation(c, args->vararg,
1395 args->varargannotation, names))
1396 goto error;
1397 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1398 goto error;
1399 if (args->kwargannotation &&
1400 compiler_visit_argannotation(c, args->kwarg,
1401 args->kwargannotation, names))
1402 goto error;
1403
1404 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001405 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001406 if (!return_str)
1407 goto error;
1408 }
1409 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1410 goto error;
1411 }
1412
1413 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001414 if (len > 65534) {
1415 /* len must fit in 16 bits, and len is incremented below */
1416 PyErr_SetString(PyExc_SyntaxError,
1417 "too many annotations");
1418 goto error;
1419 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001420 if (len) {
1421 /* convert names to a tuple and place on stack */
1422 PyObject *elt;
1423 int i;
1424 PyObject *s = PyTuple_New(len);
1425 if (!s)
1426 goto error;
1427 for (i = 0; i < len; i++) {
1428 elt = PyList_GET_ITEM(names, i);
1429 Py_INCREF(elt);
1430 PyTuple_SET_ITEM(s, i, elt);
1431 }
1432 ADDOP_O(c, LOAD_CONST, s, consts);
1433 Py_DECREF(s);
1434 len++; /* include the just-pushed tuple */
1435 }
1436 Py_DECREF(names);
1437 return len;
1438
1439error:
1440 Py_DECREF(names);
1441 return -1;
1442}
1443
1444static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445compiler_function(struct compiler *c, stmt_ty s)
1446{
1447 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001448 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001450 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001451 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001452 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001453 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001454 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455
1456 assert(s->kind == FunctionDef_kind);
1457
1458 if (!compiler_decorators(c, decos))
1459 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001460 if (args->kwonlyargs) {
1461 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1462 args->kw_defaults);
1463 if (res < 0)
1464 return 0;
1465 kw_default_count = res;
1466 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467 if (args->defaults)
1468 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001469 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001470 if (num_annotations < 0)
1471 return 0;
1472 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1475 s->lineno))
1476 return 0;
1477
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001478 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001479 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001480 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 first_const = st->v.Expr.value->v.Str.s;
1482 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001483 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001484 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001485 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001488 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001490 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001492 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1493 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494 }
1495 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001496 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497 if (co == NULL)
1498 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499
Guido van Rossum4f72a782006-10-27 23:31:49 +00001500 arglength = asdl_seq_LEN(args->defaults);
1501 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001502 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001503 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001504 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505
Neal Norwitzc1505362006-12-28 06:47:50 +00001506 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1508 ADDOP_I(c, CALL_FUNCTION, 1);
1509 }
1510
1511 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1512}
1513
1514static int
1515compiler_class(struct compiler *c, stmt_ty s)
1516{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001518 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001519 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001520 asdl_seq* decos = s->v.ClassDef.decorator_list;
1521
1522 if (!compiler_decorators(c, decos))
1523 return 0;
1524
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001525 /* ultimately generate code for:
1526 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1527 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001528 <func> is a function/closure created from the class body;
1529 it has a single argument (__locals__) where the dict
1530 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001531 <name> is the class name
1532 <bases> is the positional arguments and *varargs argument
1533 <keywords> is the keyword arguments and **kwds argument
1534 This borrows from compiler_call.
1535 */
1536
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001537 /* 1. compile the class body into a code object */
1538 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1539 return 0;
1540 /* this block represents what we do in the new scope */
1541 {
1542 /* use the class name for name mangling */
1543 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001544 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001545 c->u->u_private = s->v.ClassDef.name;
1546 /* force it to have one mandatory argument */
1547 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001548 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001549 ADDOP_I(c, LOAD_FAST, 0);
1550 /* ... and store it into f_locals */
1551 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001552 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001553 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001554 if (!str || !compiler_nameop(c, str, Load)) {
1555 Py_XDECREF(str);
1556 compiler_exit_scope(c);
1557 return 0;
1558 }
1559 Py_DECREF(str);
1560 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001561 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001562 if (!str || !compiler_nameop(c, str, Store)) {
1563 Py_XDECREF(str);
1564 compiler_exit_scope(c);
1565 return 0;
1566 }
1567 Py_DECREF(str);
1568 /* compile the body proper */
1569 if (!compiler_body(c, s->v.ClassDef.body)) {
1570 compiler_exit_scope(c);
1571 return 0;
1572 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001573 /* return the (empty) __class__ cell */
1574 str = PyUnicode_InternFromString("__class__");
1575 if (str == NULL) {
1576 compiler_exit_scope(c);
1577 return 0;
1578 }
1579 i = compiler_lookup_arg(c->u->u_cellvars, str);
1580 Py_DECREF(str);
1581 if (i == -1) {
1582 /* This happens when nobody references the cell */
1583 PyErr_Clear();
1584 /* Return None */
1585 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1586 }
1587 else {
1588 /* Return the cell where to store __class__ */
1589 ADDOP_I(c, LOAD_CLOSURE, i);
1590 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001591 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1592 /* create the code object */
1593 co = assemble(c, 1);
1594 }
1595 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001596 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001597 if (co == NULL)
1598 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001600 /* 2. load the 'build_class' function */
1601 ADDOP(c, LOAD_BUILD_CLASS);
1602
1603 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001604 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001605 Py_DECREF(co);
1606
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001607 /* 4. load class name */
1608 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1609
1610 /* 5. generate the rest of the code for the call */
1611 if (!compiler_call_helper(c, 2,
1612 s->v.ClassDef.bases,
1613 s->v.ClassDef.keywords,
1614 s->v.ClassDef.starargs,
1615 s->v.ClassDef.kwargs))
1616 return 0;
1617
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001618 /* 6. apply decorators */
1619 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1620 ADDOP_I(c, CALL_FUNCTION, 1);
1621 }
1622
1623 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1625 return 0;
1626 return 1;
1627}
1628
1629static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001630compiler_ifexp(struct compiler *c, expr_ty e)
1631{
1632 basicblock *end, *next;
1633
1634 assert(e->kind == IfExp_kind);
1635 end = compiler_new_block(c);
1636 if (end == NULL)
1637 return 0;
1638 next = compiler_new_block(c);
1639 if (next == NULL)
1640 return 0;
1641 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001642 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001643 VISIT(c, expr, e->v.IfExp.body);
1644 ADDOP_JREL(c, JUMP_FORWARD, end);
1645 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001646 VISIT(c, expr, e->v.IfExp.orelse);
1647 compiler_use_next_block(c, end);
1648 return 1;
1649}
1650
1651static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652compiler_lambda(struct compiler *c, expr_ty e)
1653{
1654 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001655 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001656 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657 arguments_ty args = e->v.Lambda.args;
1658 assert(e->kind == Lambda_kind);
1659
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001660 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001661 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001662 if (!name)
1663 return 0;
1664 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001665
Guido van Rossum4f72a782006-10-27 23:31:49 +00001666 if (args->kwonlyargs) {
1667 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1668 args->kw_defaults);
1669 if (res < 0) return 0;
1670 kw_default_count = res;
1671 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001672 if (args->defaults)
1673 VISIT_SEQ(c, expr, args->defaults);
1674 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1675 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001678 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001679 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001680 if (c->u->u_ste->ste_generator) {
1681 ADDOP_IN_SCOPE(c, POP_TOP);
1682 }
1683 else {
1684 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1685 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001687 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 if (co == NULL)
1689 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690
Guido van Rossum4f72a782006-10-27 23:31:49 +00001691 arglength = asdl_seq_LEN(args->defaults);
1692 arglength |= kw_default_count << 8;
1693 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001694 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001695
1696 return 1;
1697}
1698
1699static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700compiler_if(struct compiler *c, stmt_ty s)
1701{
1702 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001703 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 assert(s->kind == If_kind);
1705 end = compiler_new_block(c);
1706 if (end == NULL)
1707 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001708
1709 constant = expr_constant(s->v.If.test);
1710 /* constant = 0: "if 0"
1711 * constant = 1: "if 1", "if 2", ...
1712 * constant = -1: rest */
1713 if (constant == 0) {
1714 if (s->v.If.orelse)
1715 VISIT_SEQ(c, stmt, s->v.If.orelse);
1716 } else if (constant == 1) {
1717 VISIT_SEQ(c, stmt, s->v.If.body);
1718 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001719 if (s->v.If.orelse) {
1720 next = compiler_new_block(c);
1721 if (next == NULL)
1722 return 0;
1723 }
1724 else
1725 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001726 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001727 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001728 VISIT_SEQ(c, stmt, s->v.If.body);
1729 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001730 if (s->v.If.orelse) {
1731 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001732 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001733 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001734 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735 compiler_use_next_block(c, end);
1736 return 1;
1737}
1738
1739static int
1740compiler_for(struct compiler *c, stmt_ty s)
1741{
1742 basicblock *start, *cleanup, *end;
1743
1744 start = compiler_new_block(c);
1745 cleanup = compiler_new_block(c);
1746 end = compiler_new_block(c);
1747 if (start == NULL || end == NULL || cleanup == NULL)
1748 return 0;
1749 ADDOP_JREL(c, SETUP_LOOP, end);
1750 if (!compiler_push_fblock(c, LOOP, start))
1751 return 0;
1752 VISIT(c, expr, s->v.For.iter);
1753 ADDOP(c, GET_ITER);
1754 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001755 /* for expressions must be traced on each iteration,
1756 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001757 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758 ADDOP_JREL(c, FOR_ITER, cleanup);
1759 VISIT(c, expr, s->v.For.target);
1760 VISIT_SEQ(c, stmt, s->v.For.body);
1761 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1762 compiler_use_next_block(c, cleanup);
1763 ADDOP(c, POP_BLOCK);
1764 compiler_pop_fblock(c, LOOP, start);
1765 VISIT_SEQ(c, stmt, s->v.For.orelse);
1766 compiler_use_next_block(c, end);
1767 return 1;
1768}
1769
1770static int
1771compiler_while(struct compiler *c, stmt_ty s)
1772{
1773 basicblock *loop, *orelse, *end, *anchor = NULL;
1774 int constant = expr_constant(s->v.While.test);
1775
Christian Heimes969fe572008-01-25 11:23:10 +00001776 if (constant == 0) {
1777 if (s->v.While.orelse)
1778 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001780 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 loop = compiler_new_block(c);
1782 end = compiler_new_block(c);
1783 if (constant == -1) {
1784 anchor = compiler_new_block(c);
1785 if (anchor == NULL)
1786 return 0;
1787 }
1788 if (loop == NULL || end == NULL)
1789 return 0;
1790 if (s->v.While.orelse) {
1791 orelse = compiler_new_block(c);
1792 if (orelse == NULL)
1793 return 0;
1794 }
1795 else
1796 orelse = NULL;
1797
1798 ADDOP_JREL(c, SETUP_LOOP, end);
1799 compiler_use_next_block(c, loop);
1800 if (!compiler_push_fblock(c, LOOP, loop))
1801 return 0;
1802 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001803 /* while expressions must be traced on each iteration,
1804 so we need to set an extra line number. */
1805 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001807 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 }
1809 VISIT_SEQ(c, stmt, s->v.While.body);
1810 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1811
1812 /* XXX should the two POP instructions be in a separate block
1813 if there is no else clause ?
1814 */
1815
1816 if (constant == -1) {
1817 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818 ADDOP(c, POP_BLOCK);
1819 }
1820 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001821 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822 VISIT_SEQ(c, stmt, s->v.While.orelse);
1823 compiler_use_next_block(c, end);
1824
1825 return 1;
1826}
1827
1828static int
1829compiler_continue(struct compiler *c)
1830{
1831 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001832 static const char IN_FINALLY_ERROR_MSG[] =
1833 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 int i;
1835
1836 if (!c->u->u_nfblocks)
1837 return compiler_error(c, LOOP_ERROR_MSG);
1838 i = c->u->u_nfblocks - 1;
1839 switch (c->u->u_fblock[i].fb_type) {
1840 case LOOP:
1841 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1842 break;
1843 case EXCEPT:
1844 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001845 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1846 /* Prevent continue anywhere under a finally
1847 even if hidden in a sub-try or except. */
1848 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1849 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1850 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851 if (i == -1)
1852 return compiler_error(c, LOOP_ERROR_MSG);
1853 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1854 break;
1855 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001856 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857 }
1858
1859 return 1;
1860}
1861
1862/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1863
1864 SETUP_FINALLY L
1865 <code for body>
1866 POP_BLOCK
1867 LOAD_CONST <None>
1868 L: <code for finalbody>
1869 END_FINALLY
1870
1871 The special instructions use the block stack. Each block
1872 stack entry contains the instruction that created it (here
1873 SETUP_FINALLY), the level of the value stack at the time the
1874 block stack entry was created, and a label (here L).
1875
1876 SETUP_FINALLY:
1877 Pushes the current value stack level and the label
1878 onto the block stack.
1879 POP_BLOCK:
1880 Pops en entry from the block stack, and pops the value
1881 stack until its level is the same as indicated on the
1882 block stack. (The label is ignored.)
1883 END_FINALLY:
1884 Pops a variable number of entries from the *value* stack
1885 and re-raises the exception they specify. The number of
1886 entries popped depends on the (pseudo) exception type.
1887
1888 The block stack is unwound when an exception is raised:
1889 when a SETUP_FINALLY entry is found, the exception is pushed
1890 onto the value stack (and the exception condition is cleared),
1891 and the interpreter jumps to the label gotten from the block
1892 stack.
1893*/
1894
1895static int
1896compiler_try_finally(struct compiler *c, stmt_ty s)
1897{
1898 basicblock *body, *end;
1899 body = compiler_new_block(c);
1900 end = compiler_new_block(c);
1901 if (body == NULL || end == NULL)
1902 return 0;
1903
1904 ADDOP_JREL(c, SETUP_FINALLY, end);
1905 compiler_use_next_block(c, body);
1906 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1907 return 0;
1908 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1909 ADDOP(c, POP_BLOCK);
1910 compiler_pop_fblock(c, FINALLY_TRY, body);
1911
1912 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1913 compiler_use_next_block(c, end);
1914 if (!compiler_push_fblock(c, FINALLY_END, end))
1915 return 0;
1916 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1917 ADDOP(c, END_FINALLY);
1918 compiler_pop_fblock(c, FINALLY_END, end);
1919
1920 return 1;
1921}
1922
1923/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001924 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925 (The contents of the value stack is shown in [], with the top
1926 at the right; 'tb' is trace-back info, 'val' the exception's
1927 associated value, and 'exc' the exception.)
1928
1929 Value stack Label Instruction Argument
1930 [] SETUP_EXCEPT L1
1931 [] <code for S>
1932 [] POP_BLOCK
1933 [] JUMP_FORWARD L0
1934
1935 [tb, val, exc] L1: DUP )
1936 [tb, val, exc, exc] <evaluate E1> )
1937 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001938 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939 [tb, val, exc] POP
1940 [tb, val] <assign to V1> (or POP if no V1)
1941 [tb] POP
1942 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001943 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001945 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946 .............................etc.......................
1947
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001948 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949
1950 [] L0: <next statement>
1951
1952 Of course, parts are not generated if Vi or Ei is not present.
1953*/
1954static int
1955compiler_try_except(struct compiler *c, stmt_ty s)
1956{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001957 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 int i, n;
1959
1960 body = compiler_new_block(c);
1961 except = compiler_new_block(c);
1962 orelse = compiler_new_block(c);
1963 end = compiler_new_block(c);
1964 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1965 return 0;
1966 ADDOP_JREL(c, SETUP_EXCEPT, except);
1967 compiler_use_next_block(c, body);
1968 if (!compiler_push_fblock(c, EXCEPT, body))
1969 return 0;
1970 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1971 ADDOP(c, POP_BLOCK);
1972 compiler_pop_fblock(c, EXCEPT, body);
1973 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1974 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1975 compiler_use_next_block(c, except);
1976 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001977 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001979 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001981 c->u->u_lineno_set = 0;
1982 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001983 except = compiler_new_block(c);
1984 if (except == NULL)
1985 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001986 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001988 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001990 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 }
1992 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001993 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001994 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001995
1996 cleanup_end = compiler_new_block(c);
1997 cleanup_body = compiler_new_block(c);
1998 if(!(cleanup_end || cleanup_body))
1999 return 0;
2000
Neal Norwitzad74aa82008-03-31 05:14:30 +00002001 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002002 ADDOP(c, POP_TOP);
2003
2004 /*
2005 try:
2006 # body
2007 except type as name:
2008 try:
2009 # body
2010 finally:
2011 name = None
2012 del name
2013 */
2014
2015 /* second try: */
2016 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2017 compiler_use_next_block(c, cleanup_body);
2018 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2019 return 0;
2020
2021 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002022 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002023 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002024 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002025 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2026
2027 /* finally: */
2028 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2029 compiler_use_next_block(c, cleanup_end);
2030 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2031 return 0;
2032
2033 /* name = None */
2034 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002035 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002036
Guido van Rossum16be03e2007-01-10 18:51:35 +00002037 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002038 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002039
2040 ADDOP(c, END_FINALLY);
2041 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042 }
2043 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002044 basicblock *cleanup_body;
2045
2046 cleanup_body = compiler_new_block(c);
2047 if(!cleanup_body)
2048 return 0;
2049
2050 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002051 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002052 compiler_use_next_block(c, cleanup_body);
2053 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2054 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002055 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002056 ADDOP(c, POP_EXCEPT);
2057 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 ADDOP_JREL(c, JUMP_FORWARD, end);
2060 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 }
2062 ADDOP(c, END_FINALLY);
2063 compiler_use_next_block(c, orelse);
2064 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2065 compiler_use_next_block(c, end);
2066 return 1;
2067}
2068
2069static int
2070compiler_import_as(struct compiler *c, identifier name, identifier asname)
2071{
2072 /* The IMPORT_NAME opcode was already generated. This function
2073 merely needs to bind the result to a name.
2074
2075 If there is a dot in name, we need to split it and emit a
2076 LOAD_ATTR for each name.
2077 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002078 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2079 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 if (dot) {
2081 /* Consume the base module name to get the first attribute */
2082 src = dot + 1;
2083 while (dot) {
2084 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002085 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002086 dot = Py_UNICODE_strchr(src, '.');
2087 attr = PyUnicode_FromUnicode(src,
2088 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002089 if (!attr)
2090 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002092 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 src = dot + 1;
2094 }
2095 }
2096 return compiler_nameop(c, asname, Store);
2097}
2098
2099static int
2100compiler_import(struct compiler *c, stmt_ty s)
2101{
2102 /* The Import node stores a module name like a.b.c as a single
2103 string. This is convenient for all cases except
2104 import a.b.c as d
2105 where we need to parse that string to extract the individual
2106 module names.
2107 XXX Perhaps change the representation to make this case simpler?
2108 */
2109 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002110
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002112 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002114 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115
Christian Heimes217cfd12007-12-02 14:31:20 +00002116 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002117 if (level == NULL)
2118 return 0;
2119
2120 ADDOP_O(c, LOAD_CONST, level, consts);
2121 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2123 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2124
2125 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002126 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 if (!r)
2128 return r;
2129 }
2130 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002132 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2133 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002135 tmp = PyUnicode_FromUnicode(base,
2136 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137 r = compiler_nameop(c, tmp, Store);
2138 if (dot) {
2139 Py_DECREF(tmp);
2140 }
2141 if (!r)
2142 return r;
2143 }
2144 }
2145 return 1;
2146}
2147
2148static int
2149compiler_from_import(struct compiler *c, stmt_ty s)
2150{
2151 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152
2153 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002154 PyObject *level;
2155
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002156 if (!names)
2157 return 0;
2158
Christian Heimes217cfd12007-12-02 14:31:20 +00002159 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002160 if (!level) {
2161 Py_DECREF(names);
2162 return 0;
2163 }
2164
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165 /* build up the names */
2166 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002167 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168 Py_INCREF(alias->name);
2169 PyTuple_SET_ITEM(names, i, alias->name);
2170 }
2171
2172 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002173 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2174 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002175 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 Py_DECREF(names);
2177 return compiler_error(c,
2178 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002179 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180
2181 }
2182 }
2183
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002184 ADDOP_O(c, LOAD_CONST, level, consts);
2185 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002187 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2189 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002190 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191 identifier store_name;
2192
Martin v. Löwis5b222132007-06-10 09:51:05 +00002193 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194 assert(n == 1);
2195 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002196 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 }
2198
2199 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2200 store_name = alias->name;
2201 if (alias->asname)
2202 store_name = alias->asname;
2203
2204 if (!compiler_nameop(c, store_name, Store)) {
2205 Py_DECREF(names);
2206 return 0;
2207 }
2208 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002209 /* remove imported module */
2210 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211 return 1;
2212}
2213
2214static int
2215compiler_assert(struct compiler *c, stmt_ty s)
2216{
2217 static PyObject *assertion_error = NULL;
2218 basicblock *end;
2219
2220 if (Py_OptimizeFlag)
2221 return 1;
2222 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002223 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224 if (assertion_error == NULL)
2225 return 0;
2226 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002227 if (s->v.Assert.test->kind == Tuple_kind &&
2228 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2229 const char* msg =
2230 "assertion is always true, perhaps remove parentheses?";
2231 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2232 c->u->u_lineno, NULL, NULL) == -1)
2233 return 0;
2234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235 VISIT(c, expr, s->v.Assert.test);
2236 end = compiler_new_block(c);
2237 if (end == NULL)
2238 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002239 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2241 if (s->v.Assert.msg) {
2242 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002243 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 }
Collin Winter828f04a2007-08-31 00:04:24 +00002245 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002246 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247 return 1;
2248}
2249
2250static int
2251compiler_visit_stmt(struct compiler *c, stmt_ty s)
2252{
2253 int i, n;
2254
Thomas Wouters89f507f2006-12-13 04:49:30 +00002255 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002257 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002260 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002264 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 if (c->u->u_ste->ste_type != FunctionBlock)
2266 return compiler_error(c, "'return' outside function");
2267 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268 VISIT(c, expr, s->v.Return.value);
2269 }
2270 else
2271 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2272 ADDOP(c, RETURN_VALUE);
2273 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002274 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275 VISIT_SEQ(c, expr, s->v.Delete.targets)
2276 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002277 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 n = asdl_seq_LEN(s->v.Assign.targets);
2279 VISIT(c, expr, s->v.Assign.value);
2280 for (i = 0; i < n; i++) {
2281 if (i < n - 1)
2282 ADDOP(c, DUP_TOP);
2283 VISIT(c, expr,
2284 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2285 }
2286 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002287 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002289 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002295 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002297 if (s->v.Raise.exc) {
2298 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002300 if (s->v.Raise.cause) {
2301 VISIT(c, expr, s->v.Raise.cause);
2302 n++;
2303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304 }
2305 ADDOP_I(c, RAISE_VARARGS, n);
2306 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002307 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002309 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002311 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002313 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002315 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002317 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002318 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002320 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002322 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 ADDOP(c, PRINT_EXPR);
2324 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002325 else if (s->v.Expr.value->kind != Str_kind &&
2326 s->v.Expr.value->kind != Num_kind) {
2327 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 ADDOP(c, POP_TOP);
2329 }
2330 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002331 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002333 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002334 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 return compiler_error(c, "'break' outside loop");
2336 ADDOP(c, BREAK_LOOP);
2337 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002338 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002340 case With_kind:
2341 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342 }
2343 return 1;
2344}
2345
2346static int
2347unaryop(unaryop_ty op)
2348{
2349 switch (op) {
2350 case Invert:
2351 return UNARY_INVERT;
2352 case Not:
2353 return UNARY_NOT;
2354 case UAdd:
2355 return UNARY_POSITIVE;
2356 case USub:
2357 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002358 default:
2359 PyErr_Format(PyExc_SystemError,
2360 "unary op %d should not be possible", op);
2361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363}
2364
2365static int
2366binop(struct compiler *c, operator_ty op)
2367{
2368 switch (op) {
2369 case Add:
2370 return BINARY_ADD;
2371 case Sub:
2372 return BINARY_SUBTRACT;
2373 case Mult:
2374 return BINARY_MULTIPLY;
2375 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002376 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377 case Mod:
2378 return BINARY_MODULO;
2379 case Pow:
2380 return BINARY_POWER;
2381 case LShift:
2382 return BINARY_LSHIFT;
2383 case RShift:
2384 return BINARY_RSHIFT;
2385 case BitOr:
2386 return BINARY_OR;
2387 case BitXor:
2388 return BINARY_XOR;
2389 case BitAnd:
2390 return BINARY_AND;
2391 case FloorDiv:
2392 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002393 default:
2394 PyErr_Format(PyExc_SystemError,
2395 "binary op %d should not be possible", op);
2396 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002398}
2399
2400static int
2401cmpop(cmpop_ty op)
2402{
2403 switch (op) {
2404 case Eq:
2405 return PyCmp_EQ;
2406 case NotEq:
2407 return PyCmp_NE;
2408 case Lt:
2409 return PyCmp_LT;
2410 case LtE:
2411 return PyCmp_LE;
2412 case Gt:
2413 return PyCmp_GT;
2414 case GtE:
2415 return PyCmp_GE;
2416 case Is:
2417 return PyCmp_IS;
2418 case IsNot:
2419 return PyCmp_IS_NOT;
2420 case In:
2421 return PyCmp_IN;
2422 case NotIn:
2423 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002424 default:
2425 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002426 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427}
2428
2429static int
2430inplace_binop(struct compiler *c, operator_ty op)
2431{
2432 switch (op) {
2433 case Add:
2434 return INPLACE_ADD;
2435 case Sub:
2436 return INPLACE_SUBTRACT;
2437 case Mult:
2438 return INPLACE_MULTIPLY;
2439 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002440 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441 case Mod:
2442 return INPLACE_MODULO;
2443 case Pow:
2444 return INPLACE_POWER;
2445 case LShift:
2446 return INPLACE_LSHIFT;
2447 case RShift:
2448 return INPLACE_RSHIFT;
2449 case BitOr:
2450 return INPLACE_OR;
2451 case BitXor:
2452 return INPLACE_XOR;
2453 case BitAnd:
2454 return INPLACE_AND;
2455 case FloorDiv:
2456 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002457 default:
2458 PyErr_Format(PyExc_SystemError,
2459 "inplace binary op %d should not be possible", op);
2460 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462}
2463
2464static int
2465compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2466{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002467 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2469
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002470 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002471 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472 /* XXX AugStore isn't used anywhere! */
2473
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002474 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002475 if (!mangled)
2476 return 0;
2477
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 op = 0;
2479 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002480 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481 switch (scope) {
2482 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002483 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 optype = OP_DEREF;
2485 break;
2486 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002487 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 optype = OP_DEREF;
2489 break;
2490 case LOCAL:
2491 if (c->u->u_ste->ste_type == FunctionBlock)
2492 optype = OP_FAST;
2493 break;
2494 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002495 if (c->u->u_ste->ste_type == FunctionBlock &&
2496 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497 optype = OP_GLOBAL;
2498 break;
2499 case GLOBAL_EXPLICIT:
2500 optype = OP_GLOBAL;
2501 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002502 default:
2503 /* scope can be 0 */
2504 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505 }
2506
2507 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002508 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509
2510 switch (optype) {
2511 case OP_DEREF:
2512 switch (ctx) {
2513 case Load: op = LOAD_DEREF; break;
2514 case Store: op = STORE_DEREF; break;
2515 case AugLoad:
2516 case AugStore:
2517 break;
2518 case Del:
2519 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002520 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002522 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002523 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002526 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002527 PyErr_SetString(PyExc_SystemError,
2528 "param invalid for deref variable");
2529 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 }
2531 break;
2532 case OP_FAST:
2533 switch (ctx) {
2534 case Load: op = LOAD_FAST; break;
2535 case Store: op = STORE_FAST; break;
2536 case Del: op = DELETE_FAST; break;
2537 case AugLoad:
2538 case AugStore:
2539 break;
2540 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002541 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002542 PyErr_SetString(PyExc_SystemError,
2543 "param invalid for local variable");
2544 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002546 ADDOP_O(c, op, mangled, varnames);
2547 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 return 1;
2549 case OP_GLOBAL:
2550 switch (ctx) {
2551 case Load: op = LOAD_GLOBAL; break;
2552 case Store: op = STORE_GLOBAL; break;
2553 case Del: op = DELETE_GLOBAL; break;
2554 case AugLoad:
2555 case AugStore:
2556 break;
2557 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002558 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002559 PyErr_SetString(PyExc_SystemError,
2560 "param invalid for global variable");
2561 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 }
2563 break;
2564 case OP_NAME:
2565 switch (ctx) {
2566 case Load: op = LOAD_NAME; break;
2567 case Store: op = STORE_NAME; break;
2568 case Del: op = DELETE_NAME; break;
2569 case AugLoad:
2570 case AugStore:
2571 break;
2572 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002573 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002574 PyErr_SetString(PyExc_SystemError,
2575 "param invalid for name variable");
2576 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002577 }
2578 break;
2579 }
2580
2581 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002582 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002583 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002584 if (arg < 0)
2585 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002586 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587}
2588
2589static int
2590compiler_boolop(struct compiler *c, expr_ty e)
2591{
2592 basicblock *end;
2593 int jumpi, i, n;
2594 asdl_seq *s;
2595
2596 assert(e->kind == BoolOp_kind);
2597 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002598 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002600 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002602 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 return 0;
2604 s = e->v.BoolOp.values;
2605 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002606 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002608 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002609 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002611 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 compiler_use_next_block(c, end);
2613 return 1;
2614}
2615
2616static int
2617compiler_list(struct compiler *c, expr_ty e)
2618{
2619 int n = asdl_seq_LEN(e->v.List.elts);
2620 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002621 int i, seen_star = 0;
2622 for (i = 0; i < n; i++) {
2623 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2624 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002625 if ((i >= (1 << 8)) ||
2626 (n-i-1 >= (INT_MAX >> 8)))
2627 return compiler_error(c,
2628 "too many expressions in "
2629 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002630 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2631 seen_star = 1;
2632 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2633 } else if (elt->kind == Starred_kind) {
2634 return compiler_error(c,
2635 "two starred expressions in assignment");
2636 }
2637 }
2638 if (!seen_star) {
2639 ADDOP_I(c, UNPACK_SEQUENCE, n);
2640 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641 }
2642 VISIT_SEQ(c, expr, e->v.List.elts);
2643 if (e->v.List.ctx == Load) {
2644 ADDOP_I(c, BUILD_LIST, n);
2645 }
2646 return 1;
2647}
2648
2649static int
2650compiler_tuple(struct compiler *c, expr_ty e)
2651{
2652 int n = asdl_seq_LEN(e->v.Tuple.elts);
2653 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002654 int i, seen_star = 0;
2655 for (i = 0; i < n; i++) {
2656 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2657 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002658 if ((i >= (1 << 8)) ||
2659 (n-i-1 >= (INT_MAX >> 8)))
2660 return compiler_error(c,
2661 "too many expressions in "
2662 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002663 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2664 seen_star = 1;
2665 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2666 } else if (elt->kind == Starred_kind) {
2667 return compiler_error(c,
2668 "two starred expressions in assignment");
2669 }
2670 }
2671 if (!seen_star) {
2672 ADDOP_I(c, UNPACK_SEQUENCE, n);
2673 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 }
2675 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2676 if (e->v.Tuple.ctx == Load) {
2677 ADDOP_I(c, BUILD_TUPLE, n);
2678 }
2679 return 1;
2680}
2681
2682static int
2683compiler_compare(struct compiler *c, expr_ty e)
2684{
2685 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002686 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
2688 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2689 VISIT(c, expr, e->v.Compare.left);
2690 n = asdl_seq_LEN(e->v.Compare.ops);
2691 assert(n > 0);
2692 if (n > 1) {
2693 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002694 if (cleanup == NULL)
2695 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002696 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002697 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 }
2699 for (i = 1; i < n; i++) {
2700 ADDOP(c, DUP_TOP);
2701 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002703 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002704 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002705 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002708 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002709 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002711 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002713 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 if (n > 1) {
2715 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002716 if (end == NULL)
2717 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 ADDOP_JREL(c, JUMP_FORWARD, end);
2719 compiler_use_next_block(c, cleanup);
2720 ADDOP(c, ROT_TWO);
2721 ADDOP(c, POP_TOP);
2722 compiler_use_next_block(c, end);
2723 }
2724 return 1;
2725}
2726
2727static int
2728compiler_call(struct compiler *c, expr_ty e)
2729{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002731 return compiler_call_helper(c, 0,
2732 e->v.Call.args,
2733 e->v.Call.keywords,
2734 e->v.Call.starargs,
2735 e->v.Call.kwargs);
2736}
2737
2738/* shared code between compiler_call and compiler_class */
2739static int
2740compiler_call_helper(struct compiler *c,
2741 int n, /* Args already pushed */
2742 asdl_seq *args,
2743 asdl_seq *keywords,
2744 expr_ty starargs,
2745 expr_ty kwargs)
2746{
2747 int code = 0;
2748
2749 n += asdl_seq_LEN(args);
2750 VISIT_SEQ(c, expr, args);
2751 if (keywords) {
2752 VISIT_SEQ(c, keyword, keywords);
2753 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002755 if (starargs) {
2756 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 code |= 1;
2758 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002759 if (kwargs) {
2760 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761 code |= 2;
2762 }
2763 switch (code) {
2764 case 0:
2765 ADDOP_I(c, CALL_FUNCTION, n);
2766 break;
2767 case 1:
2768 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2769 break;
2770 case 2:
2771 ADDOP_I(c, CALL_FUNCTION_KW, n);
2772 break;
2773 case 3:
2774 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2775 break;
2776 }
2777 return 1;
2778}
2779
Nick Coghlan650f0d02007-04-15 12:05:43 +00002780
2781/* List and set comprehensions and generator expressions work by creating a
2782 nested function to perform the actual iteration. This means that the
2783 iteration variables don't leak into the current scope.
2784 The defined function is called immediately following its definition, with the
2785 result of that call being the result of the expression.
2786 The LC/SC version returns the populated container, while the GE version is
2787 flagged in symtable.c as a generator, so it returns the generator object
2788 when the function is called.
2789 This code *knows* that the loop cannot contain break, continue, or return,
2790 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2791
2792 Possible cleanups:
2793 - iterate over the generator sequence instead of using recursion
2794*/
2795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002797compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002798 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002799 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800{
2801 /* generate code for the iterator, then each of the ifs,
2802 and then write to the element */
2803
Nick Coghlan650f0d02007-04-15 12:05:43 +00002804 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002806 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
2808 start = compiler_new_block(c);
2809 skip = compiler_new_block(c);
2810 if_cleanup = compiler_new_block(c);
2811 anchor = compiler_new_block(c);
2812
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002813 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002814 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002816
Nick Coghlan650f0d02007-04-15 12:05:43 +00002817 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819 if (gen_index == 0) {
2820 /* Receive outermost iter as an implicit argument */
2821 c->u->u_argcount = 1;
2822 ADDOP_I(c, LOAD_FAST, 0);
2823 }
2824 else {
2825 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002826 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827 ADDOP(c, GET_ITER);
2828 }
2829 compiler_use_next_block(c, start);
2830 ADDOP_JREL(c, FOR_ITER, anchor);
2831 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002832 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002834 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002835 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002837 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002839 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002841 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002843 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002844 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002845 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002846 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002847 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848
Nick Coghlan650f0d02007-04-15 12:05:43 +00002849 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002850 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002851 /* comprehension specific code */
2852 switch (type) {
2853 case COMP_GENEXP:
2854 VISIT(c, expr, elt);
2855 ADDOP(c, YIELD_VALUE);
2856 ADDOP(c, POP_TOP);
2857 break;
2858 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002859 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002860 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002861 break;
2862 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002863 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002864 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002865 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002866 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002867 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002868 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002869 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002870 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002871 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002872 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002873 default:
2874 return 0;
2875 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876
2877 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002878 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002879 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2881 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882
2883 return 1;
2884}
2885
2886static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002887compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002888 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002889{
2890 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002891 expr_ty outermost_iter;
2892
2893 outermost_iter = ((comprehension_ty)
2894 asdl_seq_GET(generators, 0))->iter;
2895
2896 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2897 goto error;
2898
2899 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002900 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002901 switch (type) {
2902 case COMP_LISTCOMP:
2903 op = BUILD_LIST;
2904 break;
2905 case COMP_SETCOMP:
2906 op = BUILD_SET;
2907 break;
2908 case COMP_DICTCOMP:
2909 op = BUILD_MAP;
2910 break;
2911 default:
2912 PyErr_Format(PyExc_SystemError,
2913 "unknown comprehension type %d", type);
2914 goto error_in_scope;
2915 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002916
Guido van Rossum992d4a32007-07-11 13:09:30 +00002917 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002918 }
2919
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002920 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002921 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002922 goto error_in_scope;
2923
2924 if (type != COMP_GENEXP) {
2925 ADDOP(c, RETURN_VALUE);
2926 }
2927
2928 co = assemble(c, 1);
2929 compiler_exit_scope(c);
2930 if (co == NULL)
2931 goto error;
2932
2933 if (!compiler_make_closure(c, co, 0))
2934 goto error;
2935 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002936
2937 VISIT(c, expr, outermost_iter);
2938 ADDOP(c, GET_ITER);
2939 ADDOP_I(c, CALL_FUNCTION, 1);
2940 return 1;
2941error_in_scope:
2942 compiler_exit_scope(c);
2943error:
2944 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002945 return 0;
2946}
2947
2948static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949compiler_genexp(struct compiler *c, expr_ty e)
2950{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002951 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002952 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002953 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002954 if (!name)
2955 return 0;
2956 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002957 assert(e->kind == GeneratorExp_kind);
2958 return compiler_comprehension(c, e, COMP_GENEXP, name,
2959 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002960 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961}
2962
2963static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002964compiler_listcomp(struct compiler *c, expr_ty e)
2965{
2966 static identifier name;
2967 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002968 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002969 if (!name)
2970 return 0;
2971 }
2972 assert(e->kind == ListComp_kind);
2973 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2974 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002975 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002976}
2977
2978static int
2979compiler_setcomp(struct compiler *c, expr_ty e)
2980{
2981 static identifier name;
2982 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002983 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002984 if (!name)
2985 return 0;
2986 }
2987 assert(e->kind == SetComp_kind);
2988 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2989 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002990 e->v.SetComp.elt, NULL);
2991}
2992
2993
2994static int
2995compiler_dictcomp(struct compiler *c, expr_ty e)
2996{
2997 static identifier name;
2998 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00002999 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003000 if (!name)
3001 return 0;
3002 }
3003 assert(e->kind == DictComp_kind);
3004 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3005 e->v.DictComp.generators,
3006 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003007}
3008
3009
3010static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011compiler_visit_keyword(struct compiler *c, keyword_ty k)
3012{
3013 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3014 VISIT(c, expr, k->value);
3015 return 1;
3016}
3017
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003018/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 whether they are true or false.
3020
3021 Return values: 1 for true, 0 for false, -1 for non-constant.
3022 */
3023
3024static int
3025expr_constant(expr_ty e)
3026{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003027 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003029 case Ellipsis_kind:
3030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031 case Num_kind:
3032 return PyObject_IsTrue(e->v.Num.n);
3033 case Str_kind:
3034 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003035 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003036 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003037 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003038 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003039 if (strcmp(id, "True") == 0) return 1;
3040 if (strcmp(id, "False") == 0) return 0;
3041 if (strcmp(id, "None") == 0) return 0;
3042 if (strcmp(id, "__debug__") == 0)
3043 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003044 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 default:
3046 return -1;
3047 }
3048}
3049
Guido van Rossumc2e20742006-02-27 22:32:47 +00003050/*
3051 Implements the with statement from PEP 343.
3052
3053 The semantics outlined in that PEP are as follows:
3054
3055 with EXPR as VAR:
3056 BLOCK
3057
3058 It is implemented roughly as:
3059
Thomas Wouters477c8d52006-05-27 19:21:47 +00003060 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003061 exit = context.__exit__ # not calling it
3062 value = context.__enter__()
3063 try:
3064 VAR = value # if VAR present in the syntax
3065 BLOCK
3066 finally:
3067 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003068 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003069 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 exit(*exc)
3072 */
3073static int
3074compiler_with(struct compiler *c, stmt_ty s)
3075{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003076 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003077 basicblock *block, *finally;
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003078 identifier tmpvalue = NULL, tmpexit = NULL;
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 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003083 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003084 if (!enter_attr)
3085 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003086 }
3087 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003088 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003089 if (!exit_attr)
3090 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003091 }
3092
3093 block = compiler_new_block(c);
3094 finally = compiler_new_block(c);
3095 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003096 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003097
Guido van Rossumc2e20742006-02-27 22:32:47 +00003098 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003099 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003100 We need to do this rather than preserving it on the stack
3101 because SETUP_FINALLY remembers the stack level.
3102 We need to do the assignment *inside* the try/finally
3103 so that context.__exit__() is called when the assignment
3104 fails. But we need to call context.__enter__() *before*
3105 the try/finally so that if it fails we won't call
3106 context.__exit__().
3107 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003108 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003109 if (tmpvalue == NULL)
3110 return 0;
3111 PyArena_AddPyObject(c->c_arena, tmpvalue);
3112 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003113 tmpexit = compiler_new_tmpname(c);
3114 if (tmpexit == NULL)
3115 return 0;
3116 PyArena_AddPyObject(c->c_arena, tmpexit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003117
Thomas Wouters477c8d52006-05-27 19:21:47 +00003118 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003119 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003120
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003121 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003122 ADDOP(c, DUP_TOP);
3123 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003124 if (!compiler_nameop(c, tmpexit, Store))
3125 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003126
3127 /* Call context.__enter__() */
3128 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3129 ADDOP_I(c, CALL_FUNCTION, 0);
3130
3131 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003132 /* Store it in tmpvalue */
3133 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003134 return 0;
3135 }
3136 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003137 /* Discard result from context.__enter__() */
3138 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003139 }
3140
3141 /* Start the try block */
3142 ADDOP_JREL(c, SETUP_FINALLY, finally);
3143
3144 compiler_use_next_block(c, block);
3145 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003146 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003147 }
3148
3149 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 /* Bind saved result of context.__enter__() to VAR */
3151 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003152 !compiler_nameop(c, tmpvalue, Del))
3153 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003154 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003155 }
3156
3157 /* BLOCK code */
3158 VISIT_SEQ(c, stmt, s->v.With.body);
3159
3160 /* End of try block; start the finally block */
3161 ADDOP(c, POP_BLOCK);
3162 compiler_pop_fblock(c, FINALLY_TRY, block);
3163
3164 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3165 compiler_use_next_block(c, finally);
3166 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003168
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003169 /* Finally block starts; context.__exit__ is on the stack under
3170 the exception or return information. Just issue our magic
3171 opcode. */
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003172 if (!compiler_nameop(c, tmpexit, Load) ||
3173 !compiler_nameop(c, tmpexit, Del))
3174 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003175 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003176
3177 /* Finally block ends. */
3178 ADDOP(c, END_FINALLY);
3179 compiler_pop_fblock(c, FINALLY_END, finally);
3180 return 1;
3181}
3182
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183static int
3184compiler_visit_expr(struct compiler *c, expr_ty e)
3185{
3186 int i, n;
3187
Thomas Wouters89f507f2006-12-13 04:49:30 +00003188 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003189 set a new line number for the next instruction.
3190 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191 if (e->lineno > c->u->u_lineno) {
3192 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003193 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 }
3195 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 VISIT(c, expr, e->v.BinOp.left);
3200 VISIT(c, expr, e->v.BinOp.right);
3201 ADDOP(c, binop(c, e->v.BinOp.op));
3202 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 VISIT(c, expr, e->v.UnaryOp.operand);
3205 ADDOP(c, unaryop(e->v.UnaryOp.op));
3206 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003207 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003209 case IfExp_kind:
3210 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003213 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003215 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003216 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003217 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003218 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003219 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 }
3221 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003222 case Set_kind:
3223 n = asdl_seq_LEN(e->v.Set.elts);
3224 VISIT_SEQ(c, expr, e->v.Set.elts);
3225 ADDOP_I(c, BUILD_SET, n);
3226 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003227 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003229 case ListComp_kind:
3230 return compiler_listcomp(c, e);
3231 case SetComp_kind:
3232 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003233 case DictComp_kind:
3234 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235 case Yield_kind:
3236 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003237 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 if (e->v.Yield.value) {
3239 VISIT(c, expr, e->v.Yield.value);
3240 }
3241 else {
3242 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3243 }
3244 ADDOP(c, YIELD_VALUE);
3245 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003246 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003247 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003248 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003250 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3252 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003253 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3255 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003256 case Bytes_kind:
3257 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003258 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003259 case Ellipsis_kind:
3260 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3261 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 if (e->v.Attribute.ctx != AugStore)
3265 VISIT(c, expr, e->v.Attribute.value);
3266 switch (e->v.Attribute.ctx) {
3267 case AugLoad:
3268 ADDOP(c, DUP_TOP);
3269 /* Fall through to load */
3270 case Load:
3271 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3272 break;
3273 case AugStore:
3274 ADDOP(c, ROT_TWO);
3275 /* Fall through to save */
3276 case Store:
3277 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3278 break;
3279 case Del:
3280 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3281 break;
3282 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003283 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003284 PyErr_SetString(PyExc_SystemError,
3285 "param invalid in attribute expression");
3286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 }
3288 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003289 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290 switch (e->v.Subscript.ctx) {
3291 case AugLoad:
3292 VISIT(c, expr, e->v.Subscript.value);
3293 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3294 break;
3295 case Load:
3296 VISIT(c, expr, e->v.Subscript.value);
3297 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3298 break;
3299 case AugStore:
3300 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3301 break;
3302 case Store:
3303 VISIT(c, expr, e->v.Subscript.value);
3304 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3305 break;
3306 case Del:
3307 VISIT(c, expr, e->v.Subscript.value);
3308 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3309 break;
3310 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003311 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003312 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003313 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003314 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315 }
3316 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003317 case Starred_kind:
3318 switch (e->v.Starred.ctx) {
3319 case Store:
3320 /* In all legitimate cases, the Starred node was already replaced
3321 * by compiler_list/compiler_tuple. XXX: is that okay? */
3322 return compiler_error(c,
3323 "starred assignment target must be in a list or tuple");
3324 default:
3325 return compiler_error(c,
3326 "can use starred expression only as assignment target");
3327 }
3328 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003329 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3331 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003332 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003334 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335 return compiler_tuple(c, e);
3336 }
3337 return 1;
3338}
3339
3340static int
3341compiler_augassign(struct compiler *c, stmt_ty s)
3342{
3343 expr_ty e = s->v.AugAssign.target;
3344 expr_ty auge;
3345
3346 assert(s->kind == AugAssign_kind);
3347
3348 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003349 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003350 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003351 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003352 if (auge == NULL)
3353 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003354 VISIT(c, expr, auge);
3355 VISIT(c, expr, s->v.AugAssign.value);
3356 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3357 auge->v.Attribute.ctx = AugStore;
3358 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359 break;
3360 case Subscript_kind:
3361 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003362 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003363 if (auge == NULL)
3364 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365 VISIT(c, expr, auge);
3366 VISIT(c, expr, s->v.AugAssign.value);
3367 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003368 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003370 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003372 if (!compiler_nameop(c, e->v.Name.id, Load))
3373 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003374 VISIT(c, expr, s->v.AugAssign.value);
3375 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3376 return compiler_nameop(c, e->v.Name.id, Store);
3377 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003378 PyErr_Format(PyExc_SystemError,
3379 "invalid node type (%d) for augmented assignment",
3380 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003381 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382 }
3383 return 1;
3384}
3385
3386static int
3387compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3388{
3389 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003390 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3391 PyErr_SetString(PyExc_SystemError,
3392 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003395 f = &c->u->u_fblock[c->u->u_nfblocks++];
3396 f->fb_type = t;
3397 f->fb_block = b;
3398 return 1;
3399}
3400
3401static void
3402compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3403{
3404 struct compiler_unit *u = c->u;
3405 assert(u->u_nfblocks > 0);
3406 u->u_nfblocks--;
3407 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3408 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3409}
3410
Thomas Wouters89f507f2006-12-13 04:49:30 +00003411static int
3412compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003413 int i;
3414 struct compiler_unit *u = c->u;
3415 for (i = 0; i < u->u_nfblocks; ++i) {
3416 if (u->u_fblock[i].fb_type == LOOP)
3417 return 1;
3418 }
3419 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003420}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421/* Raises a SyntaxError and returns 0.
3422 If something goes wrong, a different exception may be raised.
3423*/
3424
3425static int
3426compiler_error(struct compiler *c, const char *errstr)
3427{
3428 PyObject *loc;
3429 PyObject *u = NULL, *v = NULL;
3430
3431 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3432 if (!loc) {
3433 Py_INCREF(Py_None);
3434 loc = Py_None;
3435 }
3436 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3437 Py_None, loc);
3438 if (!u)
3439 goto exit;
3440 v = Py_BuildValue("(zO)", errstr, u);
3441 if (!v)
3442 goto exit;
3443 PyErr_SetObject(PyExc_SyntaxError, v);
3444 exit:
3445 Py_DECREF(loc);
3446 Py_XDECREF(u);
3447 Py_XDECREF(v);
3448 return 0;
3449}
3450
3451static int
3452compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003453 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457 /* XXX this code is duplicated */
3458 switch (ctx) {
3459 case AugLoad: /* fall through to Load */
3460 case Load: op = BINARY_SUBSCR; break;
3461 case AugStore:/* fall through to Store */
3462 case Store: op = STORE_SUBSCR; break;
3463 case Del: op = DELETE_SUBSCR; break;
3464 case Param:
3465 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003466 "invalid %s kind %d in subscript\n",
3467 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468 return 0;
3469 }
3470 if (ctx == AugLoad) {
3471 ADDOP_I(c, DUP_TOPX, 2);
3472 }
3473 else if (ctx == AugStore) {
3474 ADDOP(c, ROT_THREE);
3475 }
3476 ADDOP(c, op);
3477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478}
3479
3480static int
3481compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3482{
3483 int n = 2;
3484 assert(s->kind == Slice_kind);
3485
3486 /* only handles the cases where BUILD_SLICE is emitted */
3487 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003488 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489 }
3490 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003491 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496 }
3497 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003498 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499 }
3500
3501 if (s->v.Slice.step) {
3502 n++;
3503 VISIT(c, expr, s->v.Slice.step);
3504 }
3505 ADDOP_I(c, BUILD_SLICE, n);
3506 return 1;
3507}
3508
3509static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3511 expr_context_ty ctx)
3512{
3513 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 case Slice_kind:
3515 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 case Index_kind:
3517 VISIT(c, expr, s->v.Index.value);
3518 break;
3519 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003520 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003521 PyErr_SetString(PyExc_SystemError,
3522 "extended slice invalid in nested slice");
3523 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 }
3525 return 1;
3526}
3527
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528static int
3529compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3530{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003531 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003533 case Index_kind:
3534 kindname = "index";
3535 if (ctx != AugStore) {
3536 VISIT(c, expr, s->v.Index.value);
3537 }
3538 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003540 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003541 if (ctx != AugStore) {
3542 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 return 0;
3544 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003545 break;
3546 case ExtSlice_kind:
3547 kindname = "extended slice";
3548 if (ctx != AugStore) {
3549 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3550 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003551 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003552 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003553 if (!compiler_visit_nested_slice(c, sub, ctx))
3554 return 0;
3555 }
3556 ADDOP_I(c, BUILD_TUPLE, n);
3557 }
3558 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003559 default:
3560 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003561 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003562 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003564 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565}
3566
Thomas Wouters89f507f2006-12-13 04:49:30 +00003567/* End of the compiler section, beginning of the assembler section */
3568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569/* do depth-first search of basic block graph, starting with block.
3570 post records the block indices in post-order.
3571
3572 XXX must handle implicit jumps from one block to next
3573*/
3574
Thomas Wouters89f507f2006-12-13 04:49:30 +00003575struct assembler {
3576 PyObject *a_bytecode; /* string containing bytecode */
3577 int a_offset; /* offset into bytecode */
3578 int a_nblocks; /* number of reachable blocks */
3579 basicblock **a_postorder; /* list of blocks in dfs postorder */
3580 PyObject *a_lnotab; /* string containing lnotab */
3581 int a_lnotab_off; /* offset into lnotab */
3582 int a_lineno; /* last lineno of emitted instruction */
3583 int a_lineno_off; /* bytecode offset of last lineno */
3584};
3585
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586static void
3587dfs(struct compiler *c, basicblock *b, struct assembler *a)
3588{
3589 int i;
3590 struct instr *instr = NULL;
3591
3592 if (b->b_seen)
3593 return;
3594 b->b_seen = 1;
3595 if (b->b_next != NULL)
3596 dfs(c, b->b_next, a);
3597 for (i = 0; i < b->b_iused; i++) {
3598 instr = &b->b_instr[i];
3599 if (instr->i_jrel || instr->i_jabs)
3600 dfs(c, instr->i_target, a);
3601 }
3602 a->a_postorder[a->a_nblocks++] = b;
3603}
3604
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003605static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3607{
3608 int i;
3609 struct instr *instr;
3610 if (b->b_seen || b->b_startdepth >= depth)
3611 return maxdepth;
3612 b->b_seen = 1;
3613 b->b_startdepth = depth;
3614 for (i = 0; i < b->b_iused; i++) {
3615 instr = &b->b_instr[i];
3616 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3617 if (depth > maxdepth)
3618 maxdepth = depth;
3619 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3620 if (instr->i_jrel || instr->i_jabs) {
3621 maxdepth = stackdepth_walk(c, instr->i_target,
3622 depth, maxdepth);
3623 if (instr->i_opcode == JUMP_ABSOLUTE ||
3624 instr->i_opcode == JUMP_FORWARD) {
3625 goto out; /* remaining code is dead */
3626 }
3627 }
3628 }
3629 if (b->b_next)
3630 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3631out:
3632 b->b_seen = 0;
3633 return maxdepth;
3634}
3635
3636/* Find the flow path that needs the largest stack. We assume that
3637 * cycles in the flow graph have no net effect on the stack depth.
3638 */
3639static int
3640stackdepth(struct compiler *c)
3641{
3642 basicblock *b, *entryblock;
3643 entryblock = NULL;
3644 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3645 b->b_seen = 0;
3646 b->b_startdepth = INT_MIN;
3647 entryblock = b;
3648 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003649 if (!entryblock)
3650 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 return stackdepth_walk(c, entryblock, 0, 0);
3652}
3653
3654static int
3655assemble_init(struct assembler *a, int nblocks, int firstlineno)
3656{
3657 memset(a, 0, sizeof(struct assembler));
3658 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003659 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 if (!a->a_bytecode)
3661 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003662 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663 if (!a->a_lnotab)
3664 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003665 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3666 PyErr_NoMemory();
3667 return 0;
3668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003670 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003671 if (!a->a_postorder) {
3672 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003674 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675 return 1;
3676}
3677
3678static void
3679assemble_free(struct assembler *a)
3680{
3681 Py_XDECREF(a->a_bytecode);
3682 Py_XDECREF(a->a_lnotab);
3683 if (a->a_postorder)
3684 PyObject_Free(a->a_postorder);
3685}
3686
3687/* Return the size of a basic block in bytes. */
3688
3689static int
3690instrsize(struct instr *instr)
3691{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003692 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003693 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003694 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003695 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3696 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003697}
3698
3699static int
3700blocksize(basicblock *b)
3701{
3702 int i;
3703 int size = 0;
3704
3705 for (i = 0; i < b->b_iused; i++)
3706 size += instrsize(&b->b_instr[i]);
3707 return size;
3708}
3709
3710/* All about a_lnotab.
3711
3712c_lnotab is an array of unsigned bytes disguised as a Python string.
3713It is used to map bytecode offsets to source code line #s (when needed
3714for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003715
Tim Peters2a7f3842001-06-09 09:26:21 +00003716The array is conceptually a list of
3717 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003718pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003719
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003720 byte code offset source code line number
3721 0 1
3722 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003723 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003724 350 307
3725 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003726
3727The first trick is that these numbers aren't stored, only the increments
3728from one row to the next (this doesn't really work, but it's a start):
3729
3730 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3731
3732The second trick is that an unsigned byte can't hold negative values, or
3733values larger than 255, so (a) there's a deep assumption that byte code
3734offsets and their corresponding line #s both increase monotonically, and (b)
3735if at least one column jumps by more than 255 from one row to the next, more
3736than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003737from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003738part. A user of c_lnotab desiring to find the source line number
3739corresponding to a bytecode address A should do something like this
3740
3741 lineno = addr = 0
3742 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003743 addr += addr_incr
3744 if addr > A:
3745 return lineno
3746 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003747
3748In order for this to work, when the addr field increments by more than 255,
3749the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003750increment is < 256. So, in the example above, assemble_lnotab (it used
3751to be called com_set_lineno) should not (as was actually done until 2.2)
3752expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003753 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003754*/
3755
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003756static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003758{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759 int d_bytecode, d_lineno;
3760 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003761 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762
3763 d_bytecode = a->a_offset - a->a_lineno_off;
3764 d_lineno = i->i_lineno - a->a_lineno;
3765
3766 assert(d_bytecode >= 0);
3767 assert(d_lineno >= 0);
3768
Christian Heimes2202f872008-02-06 14:31:34 +00003769 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003770 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003773 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003775 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003777 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003779 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003781 else {
3782 PyErr_NoMemory();
3783 return 0;
3784 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003785 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003787 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003788 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003789 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003790 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791 *lnotab++ = 255;
3792 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003793 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794 d_bytecode -= ncodes * 255;
3795 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003796 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797 assert(d_bytecode <= 255);
3798 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003799 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003801 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003803 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003805 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003807 else {
3808 PyErr_NoMemory();
3809 return 0;
3810 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003811 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003813 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003814 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003815 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003816 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003817 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003819 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003821 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003822 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003823 d_lineno -= ncodes * 255;
3824 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003825 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003826
Christian Heimes72b710a2008-05-26 13:28:38 +00003827 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003828 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003829 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003830 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003831 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003832 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003833 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003834
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 a->a_lnotab_off += 2;
3836 if (d_bytecode) {
3837 *lnotab++ = d_bytecode;
3838 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003839 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003840 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841 *lnotab++ = 0;
3842 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844 a->a_lineno = i->i_lineno;
3845 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003846 return 1;
3847}
3848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849/* assemble_emit()
3850 Extend the bytecode with a new instruction.
3851 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003852*/
3853
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003854static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003856{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003857 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003858 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 char *code;
3860
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003861 size = instrsize(i);
3862 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003864 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003865 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003866 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003867 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003869 if (len > PY_SSIZE_T_MAX / 2)
3870 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003871 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003872 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003873 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003874 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003876 if (size == 6) {
3877 assert(i->i_hasarg);
3878 *code++ = (char)EXTENDED_ARG;
3879 *code++ = ext & 0xff;
3880 *code++ = ext >> 8;
3881 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003882 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003884 if (i->i_hasarg) {
3885 assert(size == 3 || size == 6);
3886 *code++ = arg & 0xff;
3887 *code++ = arg >> 8;
3888 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003890}
3891
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003892static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003894{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003896 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003897 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 /* Compute the size of each block and fixup jump args.
3900 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003901start:
3902 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003904 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 bsize = blocksize(b);
3906 b->b_offset = totsize;
3907 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003908 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003909 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3911 bsize = b->b_offset;
3912 for (i = 0; i < b->b_iused; i++) {
3913 struct instr *instr = &b->b_instr[i];
3914 /* Relative jumps are computed relative to
3915 the instruction pointer after fetching
3916 the jump instruction.
3917 */
3918 bsize += instrsize(instr);
3919 if (instr->i_jabs)
3920 instr->i_oparg = instr->i_target->b_offset;
3921 else if (instr->i_jrel) {
3922 int delta = instr->i_target->b_offset - bsize;
3923 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003924 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003925 else
3926 continue;
3927 if (instr->i_oparg > 0xffff)
3928 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003929 }
3930 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003931
3932 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003933 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003934 with a better solution.
3935
3936 In the meantime, should the goto be dropped in favor
3937 of a loop?
3938
3939 The issue is that in the first loop blocksize() is called
3940 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003941 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003942 i_oparg is calculated in the second loop above.
3943
3944 So we loop until we stop seeing new EXTENDED_ARGs.
3945 The only EXTENDED_ARGs that could be popping up are
3946 ones in jump instructions. So this should converge
3947 fairly quickly.
3948 */
3949 if (last_extended_arg_count != extended_arg_count) {
3950 last_extended_arg_count = extended_arg_count;
3951 goto start;
3952 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003953}
3954
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003955static PyObject *
3956dict_keys_inorder(PyObject *dict, int offset)
3957{
3958 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003959 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003960
3961 tuple = PyTuple_New(size);
3962 if (tuple == NULL)
3963 return NULL;
3964 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003965 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003966 /* The keys of the dictionary are tuples. (see compiler_add_o)
3967 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003968 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003969 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003970 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003971 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003972 PyTuple_SET_ITEM(tuple, i - offset, k);
3973 }
3974 return tuple;
3975}
3976
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003977static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003978compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003979{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980 PySTEntryObject *ste = c->u->u_ste;
3981 int flags = 0, n;
3982 if (ste->ste_type != ModuleBlock)
3983 flags |= CO_NEWLOCALS;
3984 if (ste->ste_type == FunctionBlock) {
3985 if (!ste->ste_unoptimized)
3986 flags |= CO_OPTIMIZED;
3987 if (ste->ste_nested)
3988 flags |= CO_NESTED;
3989 if (ste->ste_generator)
3990 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003991 if (ste->ste_varargs)
3992 flags |= CO_VARARGS;
3993 if (ste->ste_varkeywords)
3994 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003995 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003996
3997 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003998 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003999
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004000 n = PyDict_Size(c->u->u_freevars);
4001 if (n < 0)
4002 return -1;
4003 if (n == 0) {
4004 n = PyDict_Size(c->u->u_cellvars);
4005 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004006 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004007 if (n == 0) {
4008 flags |= CO_NOFREE;
4009 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004010 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004011
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004012 return flags;
4013}
4014
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004015static PyCodeObject *
4016makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004017{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004018 PyObject *tmp;
4019 PyCodeObject *co = NULL;
4020 PyObject *consts = NULL;
4021 PyObject *names = NULL;
4022 PyObject *varnames = NULL;
4023 PyObject *filename = NULL;
4024 PyObject *name = NULL;
4025 PyObject *freevars = NULL;
4026 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004027 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030 tmp = dict_keys_inorder(c->u->u_consts, 0);
4031 if (!tmp)
4032 goto error;
4033 consts = PySequence_List(tmp); /* optimize_code requires a list */
4034 Py_DECREF(tmp);
4035
4036 names = dict_keys_inorder(c->u->u_names, 0);
4037 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4038 if (!consts || !names || !varnames)
4039 goto error;
4040
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004041 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4042 if (!cellvars)
4043 goto error;
4044 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4045 if (!freevars)
4046 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004047 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004048 if (!filename)
4049 goto error;
4050
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004051 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004052 flags = compute_code_flags(c);
4053 if (flags < 0)
4054 goto error;
4055
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004056 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057 if (!bytecode)
4058 goto error;
4059
4060 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4061 if (!tmp)
4062 goto error;
4063 Py_DECREF(consts);
4064 consts = tmp;
4065
Guido van Rossum4f72a782006-10-27 23:31:49 +00004066 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4067 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068 bytecode, consts, names, varnames,
4069 freevars, cellvars,
4070 filename, c->u->u_name,
4071 c->u->u_firstlineno,
4072 a->a_lnotab);
4073 error:
4074 Py_XDECREF(consts);
4075 Py_XDECREF(names);
4076 Py_XDECREF(varnames);
4077 Py_XDECREF(filename);
4078 Py_XDECREF(name);
4079 Py_XDECREF(freevars);
4080 Py_XDECREF(cellvars);
4081 Py_XDECREF(bytecode);
4082 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004083}
4084
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004085
4086/* For debugging purposes only */
4087#if 0
4088static void
4089dump_instr(const struct instr *i)
4090{
4091 const char *jrel = i->i_jrel ? "jrel " : "";
4092 const char *jabs = i->i_jabs ? "jabs " : "";
4093 char arg[128];
4094
4095 *arg = '\0';
4096 if (i->i_hasarg)
4097 sprintf(arg, "arg: %d ", i->i_oparg);
4098
4099 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4100 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4101}
4102
4103static void
4104dump_basicblock(const basicblock *b)
4105{
4106 const char *seen = b->b_seen ? "seen " : "";
4107 const char *b_return = b->b_return ? "return " : "";
4108 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4109 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4110 if (b->b_instr) {
4111 int i;
4112 for (i = 0; i < b->b_iused; i++) {
4113 fprintf(stderr, " [%02d] ", i);
4114 dump_instr(b->b_instr + i);
4115 }
4116 }
4117}
4118#endif
4119
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120static PyCodeObject *
4121assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004122{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123 basicblock *b, *entryblock;
4124 struct assembler a;
4125 int i, j, nblocks;
4126 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004127
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128 /* Make sure every block that falls off the end returns None.
4129 XXX NEXT_BLOCK() isn't quite right, because if the last
4130 block ends with a jump or return b_next shouldn't set.
4131 */
4132 if (!c->u->u_curblock->b_return) {
4133 NEXT_BLOCK(c);
4134 if (addNone)
4135 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4136 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004137 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004138
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139 nblocks = 0;
4140 entryblock = NULL;
4141 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4142 nblocks++;
4143 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004144 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004145
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004146 /* Set firstlineno if it wasn't explicitly set. */
4147 if (!c->u->u_firstlineno) {
4148 if (entryblock && entryblock->b_instr)
4149 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4150 else
4151 c->u->u_firstlineno = 1;
4152 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4154 goto error;
4155 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004158 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004159
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004160 /* Emit code in reverse postorder from dfs. */
4161 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004162 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004163 for (j = 0; j < b->b_iused; j++)
4164 if (!assemble_emit(&a, &b->b_instr[j]))
4165 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004166 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004167
Christian Heimes72b710a2008-05-26 13:28:38 +00004168 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004170 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004171 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173 co = makecode(c, &a);
4174 error:
4175 assemble_free(&a);
4176 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004177}