blob: ab5420867bda89c1f6da96dcab02148d7d30ada2 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Guido van Rossumd8faa362007-04-27 19:54:29 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Nick Coghlan650f0d02007-04-15 12:05:43 +000042#define COMP_GENEXP 0
43#define COMP_LISTCOMP 1
44#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000045#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000046
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
50 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000072 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000073 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
88enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
89
90struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000091 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092 basicblock *fb_block;
93};
94
95/* The following items change on entry and exit of code blocks.
96 They must be saved and restored when returning to a block.
97*/
98struct compiler_unit {
99 PySTEntryObject *u_ste;
100
101 PyObject *u_name;
102 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000103 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000104 the argument for opcodes that refer to those collections.
105 */
106 PyObject *u_consts; /* all constants */
107 PyObject *u_names; /* all names */
108 PyObject *u_varnames; /* local variables */
109 PyObject *u_cellvars; /* cell variables */
110 PyObject *u_freevars; /* free variables */
111
112 PyObject *u_private; /* for private name mangling */
113
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000114 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000115 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000116 /* Pointer to the most recently allocated block. By following b_list
117 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000120 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
122 int u_nfblocks;
123 struct fblockinfo u_fblock[CO_MAXBLOCKS];
124
125 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000126 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000127 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128 has been generated with current lineno */
129};
130
131/* This struct captures the global state of a compilation.
132
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133The u pointer points to the current compilation unit, while units
134for enclosing blocks are stored in c_stack. The u and c_stack are
135managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136*/
137
138struct compiler {
139 const char *c_filename;
140 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142 PyCompilerFlags *c_flags;
143
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 struct compiler_unit *u; /* compiler state for current block */
148 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151};
152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153static int compiler_enter_scope(struct compiler *, identifier, void *, int);
154static void compiler_free(struct compiler *);
155static basicblock *compiler_new_block(struct compiler *);
156static int compiler_next_instr(struct compiler *, basicblock *);
157static int compiler_addop(struct compiler *, int);
158static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
159static int compiler_addop_i(struct compiler *, int, int);
160static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161static basicblock *compiler_use_new_block(struct compiler *);
162static int compiler_error(struct compiler *, const char *);
163static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
164
165static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
166static int compiler_visit_stmt(struct compiler *, stmt_ty);
167static int compiler_visit_keyword(struct compiler *, keyword_ty);
168static int compiler_visit_expr(struct compiler *, expr_ty);
169static int compiler_augassign(struct compiler *, stmt_ty);
170static int compiler_visit_slice(struct compiler *, slice_ty,
171 expr_context_ty);
172
173static int compiler_push_fblock(struct compiler *, enum fblocktype,
174 basicblock *);
175static void compiler_pop_fblock(struct compiler *, enum fblocktype,
176 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000177/* Returns true if there is a loop on the fblock stack. */
178static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179
180static int inplace_binop(struct compiler *, operator_ty);
181static int expr_constant(expr_ty e);
182
Guido van Rossumc2e20742006-02-27 22:32:47 +0000183static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000184static int compiler_call_helper(struct compiler *c, int n,
185 asdl_seq *args,
186 asdl_seq *keywords,
187 expr_ty starargs,
188 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static PyCodeObject *assemble(struct compiler *, int addNone);
191static PyObject *__doc__;
192
Benjamin Petersonb173f782009-05-05 22:31:58 +0000193#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000197{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198 /* Name mangling: __private becomes _classname__private.
199 This is independent from how the name is used. */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000200 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
201 Py_UNICODE *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 size_t nlen, plen;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000203 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000204 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000207 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000208 p = PyUnicode_AS_UNICODE(privateobj);
209 nlen = Py_UNICODE_strlen(name);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 /* Don't mangle __id__ or names with dots.
211
212 The only time a name with a dot can occur is when
213 we are compiling an import statement that has a
214 package name.
215
216 TODO(jhylton): Decide whether we want to support
217 mangling of the module name, e.g. __M.X.
218 */
219 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Martin v. Löwis5b222132007-06-10 09:51:05 +0000220 || Py_UNICODE_strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224 /* Strip leading underscores from class name */
225 while (*p == '_')
226 p++;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000227 if (*p == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000231 plen = Py_UNICODE_strlen(p);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000232
233 assert(1 <= PY_SSIZE_T_MAX - nlen);
234 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
235
Martin v. Löwis5b222132007-06-10 09:51:05 +0000236 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000237 if (!ident)
238 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Martin v. Löwis5b222132007-06-10 09:51:05 +0000240 buffer = PyUnicode_AS_UNICODE(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000241 buffer[0] = '_';
Martin v. Löwis5b222132007-06-10 09:51:05 +0000242 Py_UNICODE_strncpy(buffer+1, p, plen);
243 Py_UNICODE_strcpy(buffer+1+plen, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000245}
246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000247static int
248compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000249{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000251
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252 c->c_stack = PyList_New(0);
253 if (!c->c_stack)
254 return 0;
255
256 return 1;
257}
258
259PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000260PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000261 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000262{
263 struct compiler c;
264 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000265 PyCompilerFlags local_flags;
266 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000268 if (!__doc__) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000269 __doc__ = PyUnicode_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000270 if (!__doc__)
271 return NULL;
272 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273
274 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000275 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000276 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000277 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278 c.c_future = PyFuture_FromAST(mod, filename);
279 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000280 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000281 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000282 local_flags.cf_flags = 0;
283 flags = &local_flags;
284 }
285 merged = c.c_future->ff_features | flags->cf_flags;
286 c.c_future->ff_features = merged;
287 flags->cf_flags = merged;
288 c.c_flags = flags;
289 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000290
291 c.c_st = PySymtable_Build(mod, filename, c.c_future);
292 if (c.c_st == NULL) {
293 if (!PyErr_Occurred())
294 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000295 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 }
297
298 /* XXX initialize to NULL for now, need to handle */
299 c.c_encoding = NULL;
300
301 co = compiler_mod(&c, mod);
302
Thomas Wouters1175c432006-02-27 22:49:54 +0000303 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000305 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000306 return co;
307}
308
309PyCodeObject *
310PyNode_Compile(struct _node *n, const char *filename)
311{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000312 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000313 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000314 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000315 if (!arena)
316 return NULL;
317 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000318 if (mod)
319 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000320 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000321 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000322}
323
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000324static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000326{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327 if (c->c_st)
328 PySymtable_Free(c->c_st);
329 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000330 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000332}
333
Guido van Rossum79f25d91997-04-29 20:08:16 +0000334static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000335list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000336{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000337 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338 PyObject *v, *k;
339 PyObject *dict = PyDict_New();
340 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000341
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 n = PyList_Size(list);
343 for (i = 0; i < n; i++) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000344 v = PyLong_FromLong(i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 if (!v) {
346 Py_DECREF(dict);
347 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000348 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000349 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000350 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
352 Py_XDECREF(k);
353 Py_DECREF(v);
354 Py_DECREF(dict);
355 return NULL;
356 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000357 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000359 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360 return dict;
361}
362
363/* Return new dict containing names from src that match scope(s).
364
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000365src is a symbol table dictionary. If the scope of a name matches
366either scope_type or flag is set, insert it into the new dict. The
367values are integers, starting at offset and increasing by one for
368each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369*/
370
371static PyObject *
372dictbytype(PyObject *src, int scope_type, int flag, int offset)
373{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000374 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375 PyObject *k, *v, *dest = PyDict_New();
376
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 assert(offset >= 0);
378 if (dest == NULL)
379 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380
381 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000382 /* XXX this should probably be a macro in symtable.h */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000383 long vi;
Christian Heimes217cfd12007-12-02 14:31:20 +0000384 assert(PyLong_Check(v));
385 vi = PyLong_AS_LONG(v);
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000386 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000388 if (scope == scope_type || vi & flag) {
Christian Heimes217cfd12007-12-02 14:31:20 +0000389 PyObject *tuple, *item = PyLong_FromLong(i);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000390 if (item == NULL) {
391 Py_DECREF(dest);
392 return NULL;
393 }
394 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000395 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000396 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
397 Py_DECREF(item);
398 Py_DECREF(dest);
399 Py_XDECREF(tuple);
400 return NULL;
401 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000403 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405 }
406 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000407}
408
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409static void
410compiler_unit_check(struct compiler_unit *u)
411{
412 basicblock *block;
413 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Christian Heimes77c02eb2008-02-09 02:18:51 +0000414 assert((void *)block != (void *)0xcbcbcbcb);
415 assert((void *)block != (void *)0xfbfbfbfb);
416 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417 if (block->b_instr != NULL) {
418 assert(block->b_ialloc > 0);
419 assert(block->b_iused > 0);
420 assert(block->b_ialloc >= block->b_iused);
421 }
422 else {
423 assert (block->b_iused == 0);
424 assert (block->b_ialloc == 0);
425 }
426 }
427}
428
429static void
430compiler_unit_free(struct compiler_unit *u)
431{
432 basicblock *b, *next;
433
434 compiler_unit_check(u);
435 b = u->u_blocks;
436 while (b != NULL) {
437 if (b->b_instr)
438 PyObject_Free((void *)b->b_instr);
439 next = b->b_list;
440 PyObject_Free((void *)b);
441 b = next;
442 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000443 Py_CLEAR(u->u_ste);
444 Py_CLEAR(u->u_name);
445 Py_CLEAR(u->u_consts);
446 Py_CLEAR(u->u_names);
447 Py_CLEAR(u->u_varnames);
448 Py_CLEAR(u->u_freevars);
449 Py_CLEAR(u->u_cellvars);
450 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451 PyObject_Free(u);
452}
453
454static int
455compiler_enter_scope(struct compiler *c, identifier name, void *key,
456 int lineno)
457{
458 struct compiler_unit *u;
459
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000460 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000461 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000462 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000463 PyErr_NoMemory();
464 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000465 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000466 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000468 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469 u->u_ste = PySymtable_Lookup(c->c_st, key);
470 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000471 compiler_unit_free(u);
472 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473 }
474 Py_INCREF(name);
475 u->u_name = name;
476 u->u_varnames = list2dict(u->u_ste->ste_varnames);
477 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000478 if (!u->u_varnames || !u->u_cellvars) {
479 compiler_unit_free(u);
480 return 0;
481 }
482
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000484 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485 if (!u->u_freevars) {
486 compiler_unit_free(u);
487 return 0;
488 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000489
490 u->u_blocks = NULL;
491 u->u_tmpname = 0;
492 u->u_nfblocks = 0;
493 u->u_firstlineno = lineno;
494 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000495 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496 u->u_consts = PyDict_New();
497 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499 return 0;
500 }
501 u->u_names = PyDict_New();
502 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000503 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504 return 0;
505 }
506
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000507 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000508
509 /* Push the old compiler_unit on the stack. */
510 if (c->u) {
Benjamin Petersonb173f782009-05-05 22:31:58 +0000511 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
512 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
513 Py_XDECREF(capsule);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000514 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515 return 0;
516 }
Benjamin Petersonb173f782009-05-05 22:31:58 +0000517 Py_DECREF(capsule);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000518 u->u_private = c->u->u_private;
519 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520 }
521 c->u = u;
522
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000523 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000524 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525 return 0;
526
527 return 1;
528}
529
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000530static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531compiler_exit_scope(struct compiler *c)
532{
533 int n;
Benjamin Petersonb173f782009-05-05 22:31:58 +0000534 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000536 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537 compiler_unit_free(c->u);
538 /* Restore c->u to the parent unit. */
539 n = PyList_GET_SIZE(c->c_stack) - 1;
540 if (n >= 0) {
Benjamin Petersonb173f782009-05-05 22:31:58 +0000541 capsule = PyList_GET_ITEM(c->c_stack, n);
542 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000543 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000544 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000546 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547 compiler_unit_check(c->u);
548 }
549 else
550 c->u = NULL;
551
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552}
553
Benjamin Peterson32123372009-06-28 22:36:18 +0000554/* Allocate a new "anonymous" local variable. Used by with statements. */
555
556static PyObject *
557compiler_new_tmpname(struct compiler *c)
558{
559 char tmpname[256];
560 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
561 return PyUnicode_FromString(tmpname);
562}
563
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564/* Allocate a new block and return a pointer to it.
565 Returns NULL on error.
566*/
567
568static basicblock *
569compiler_new_block(struct compiler *c)
570{
571 basicblock *b;
572 struct compiler_unit *u;
573
574 u = c->u;
575 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000576 if (b == NULL) {
577 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000581 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582 b->b_list = u->u_blocks;
583 u->u_blocks = b;
584 return b;
585}
586
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587static basicblock *
588compiler_use_new_block(struct compiler *c)
589{
590 basicblock *block = compiler_new_block(c);
591 if (block == NULL)
592 return NULL;
593 c->u->u_curblock = block;
594 return block;
595}
596
597static basicblock *
598compiler_next_block(struct compiler *c)
599{
600 basicblock *block = compiler_new_block(c);
601 if (block == NULL)
602 return NULL;
603 c->u->u_curblock->b_next = block;
604 c->u->u_curblock = block;
605 return block;
606}
607
608static basicblock *
609compiler_use_next_block(struct compiler *c, basicblock *block)
610{
611 assert(block != NULL);
612 c->u->u_curblock->b_next = block;
613 c->u->u_curblock = block;
614 return block;
615}
616
617/* Returns the offset of the next instruction in the current block's
618 b_instr array. Resizes the b_instr as necessary.
619 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000620*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621
622static int
623compiler_next_instr(struct compiler *c, basicblock *b)
624{
625 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000626 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 b->b_instr = (struct instr *)PyObject_Malloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000628 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629 if (b->b_instr == NULL) {
630 PyErr_NoMemory();
631 return -1;
632 }
633 b->b_ialloc = DEFAULT_BLOCK_SIZE;
634 memset((char *)b->b_instr, 0,
635 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000636 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639 size_t oldsize, newsize;
640 oldsize = b->b_ialloc * sizeof(struct instr);
641 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000642
643 if (oldsize > (PY_SIZE_MAX >> 1)) {
644 PyErr_NoMemory();
645 return -1;
646 }
647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648 if (newsize == 0) {
649 PyErr_NoMemory();
650 return -1;
651 }
652 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 tmp = (struct instr *)PyObject_Realloc(
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655 if (tmp == NULL) {
656 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658 }
659 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
661 }
662 return b->b_iused++;
663}
664
Christian Heimes2202f872008-02-06 14:31:34 +0000665/* Set the i_lineno member of the instruction at offset off if the
666 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000667 already been set. If it has been set, the call has no effect.
668
Christian Heimes2202f872008-02-06 14:31:34 +0000669 The line number is reset in the following cases:
670 - when entering a new scope
671 - on each statement
672 - on each expression that start a new line
673 - before the "except" clause
674 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677static void
678compiler_set_lineno(struct compiler *c, int off)
679{
680 basicblock *b;
681 if (c->u->u_lineno_set)
682 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000683 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000685 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686}
687
688static int
689opcode_stack_effect(int opcode, int oparg)
690{
691 switch (opcode) {
692 case POP_TOP:
693 return -1;
694 case ROT_TWO:
695 case ROT_THREE:
696 return 0;
697 case DUP_TOP:
698 return 1;
699 case ROT_FOUR:
700 return 0;
701
702 case UNARY_POSITIVE:
703 case UNARY_NEGATIVE:
704 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705 case UNARY_INVERT:
706 return 0;
707
Nick Coghlan650f0d02007-04-15 12:05:43 +0000708 case SET_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000709 case LIST_APPEND:
Antoine Pitrouf289ae62008-12-18 11:06:25 +0000710 return -1;
711 case MAP_ADD:
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000712 return -2;
713
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714 case BINARY_POWER:
715 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716 case BINARY_MODULO:
717 case BINARY_ADD:
718 case BINARY_SUBTRACT:
719 case BINARY_SUBSCR:
720 case BINARY_FLOOR_DIVIDE:
721 case BINARY_TRUE_DIVIDE:
722 return -1;
723 case INPLACE_FLOOR_DIVIDE:
724 case INPLACE_TRUE_DIVIDE:
725 return -1;
726
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000727 case INPLACE_ADD:
728 case INPLACE_SUBTRACT:
729 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 case INPLACE_MODULO:
731 return -1;
732 case STORE_SUBSCR:
733 return -3;
Christian Heimes99170a52007-12-19 02:07:34 +0000734 case STORE_MAP:
735 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736 case DELETE_SUBSCR:
737 return -2;
738
739 case BINARY_LSHIFT:
740 case BINARY_RSHIFT:
741 case BINARY_AND:
742 case BINARY_XOR:
743 case BINARY_OR:
744 return -1;
745 case INPLACE_POWER:
746 return -1;
747 case GET_ITER:
748 return 0;
749
750 case PRINT_EXPR:
751 return -1;
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000752 case LOAD_BUILD_CLASS:
753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000754 case INPLACE_LSHIFT:
755 case INPLACE_RSHIFT:
756 case INPLACE_AND:
757 case INPLACE_XOR:
758 case INPLACE_OR:
759 return -1;
760 case BREAK_LOOP:
761 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000762 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000763 return -1; /* XXX Sometimes more */
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000764 case STORE_LOCALS:
765 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766 case RETURN_VALUE:
767 return -1;
768 case IMPORT_STAR:
769 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770 case YIELD_VALUE:
771 return 0;
772
773 case POP_BLOCK:
774 return 0;
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000775 case POP_EXCEPT:
776 return 0; /* -3 except if bad bytecode */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777 case END_FINALLY:
778 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779
780 case STORE_NAME:
781 return -1;
782 case DELETE_NAME:
783 return 0;
784 case UNPACK_SEQUENCE:
785 return oparg-1;
Guido van Rossum0368b722007-05-11 16:50:42 +0000786 case UNPACK_EX:
787 return (oparg&0xFF) + (oparg>>8);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788 case FOR_ITER:
789 return 1;
790
791 case STORE_ATTR:
792 return -2;
793 case DELETE_ATTR:
794 return -1;
795 case STORE_GLOBAL:
796 return -1;
797 case DELETE_GLOBAL:
798 return 0;
799 case DUP_TOPX:
800 return oparg;
801 case LOAD_CONST:
802 return 1;
803 case LOAD_NAME:
804 return 1;
805 case BUILD_TUPLE:
806 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000807 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808 return 1-oparg;
809 case BUILD_MAP:
810 return 1;
811 case LOAD_ATTR:
812 return 0;
813 case COMPARE_OP:
814 return -1;
815 case IMPORT_NAME:
816 return 0;
817 case IMPORT_FROM:
818 return 1;
819
820 case JUMP_FORWARD:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000821 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
822 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000823 case JUMP_ABSOLUTE:
824 return 0;
825
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000826 case POP_JUMP_IF_FALSE:
827 case POP_JUMP_IF_TRUE:
828 return -1;
829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830 case LOAD_GLOBAL:
831 return 1;
832
833 case CONTINUE_LOOP:
834 return 0;
835 case SETUP_LOOP:
836 return 0;
837 case SETUP_EXCEPT:
838 case SETUP_FINALLY:
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000839 return 6; /* can push 3 values for the new exception
840 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
842 case LOAD_FAST:
843 return 1;
844 case STORE_FAST:
845 return -1;
846 case DELETE_FAST:
847 return 0;
848
849 case RAISE_VARARGS:
850 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000851#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852 case CALL_FUNCTION:
853 return -NARGS(oparg);
854 case CALL_FUNCTION_VAR:
855 case CALL_FUNCTION_KW:
856 return -NARGS(oparg)-1;
857 case CALL_FUNCTION_VAR_KW:
858 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000860 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000861 case MAKE_CLOSURE:
862 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000863#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864 case BUILD_SLICE:
865 if (oparg == 3)
866 return -2;
867 else
868 return -1;
869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000870 case LOAD_CLOSURE:
871 return 1;
872 case LOAD_DEREF:
873 return 1;
874 case STORE_DEREF:
875 return -1;
876 default:
877 fprintf(stderr, "opcode = %d\n", opcode);
878 Py_FatalError("opcode_stack_effect()");
879
880 }
881 return 0; /* not reachable */
882}
883
884/* Add an opcode with no argument.
885 Returns 0 on failure, 1 on success.
886*/
887
888static int
889compiler_addop(struct compiler *c, int opcode)
890{
891 basicblock *b;
892 struct instr *i;
893 int off;
894 off = compiler_next_instr(c, c->u->u_curblock);
895 if (off < 0)
896 return 0;
897 b = c->u->u_curblock;
898 i = &b->b_instr[off];
899 i->i_opcode = opcode;
900 i->i_hasarg = 0;
901 if (opcode == RETURN_VALUE)
902 b->b_return = 1;
903 compiler_set_lineno(c, off);
904 return 1;
905}
906
907static int
908compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
909{
910 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000911 Py_ssize_t arg;
Christian Heimes400adb02008-02-01 08:12:03 +0000912 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000914 /* necessary to make sure types aren't coerced (e.g., int and long) */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000915 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
916 if (PyFloat_Check(o)) {
Christian Heimes400adb02008-02-01 08:12:03 +0000917 d = PyFloat_AS_DOUBLE(o);
Christian Heimes400adb02008-02-01 08:12:03 +0000918 /* all we need is to make the tuple different in either the 0.0
919 * or -0.0 case from all others, just to avoid the "coercion".
920 */
Mark Dickinson192ce612009-11-28 16:39:12 +0000921 if (d == 0.0 && copysign(1.0, d) < 0.0)
Christian Heimes400adb02008-02-01 08:12:03 +0000922 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
923 else
924 t = PyTuple_Pack(2, o, o->ob_type);
925 }
Mark Dickinsonb42dab52009-10-27 17:31:26 +0000926#ifndef WITHOUT_COMPLEX
Christian Heimes400adb02008-02-01 08:12:03 +0000927 else if (PyComplex_Check(o)) {
Mark Dickinsonb42dab52009-10-27 17:31:26 +0000928 Py_complex z;
Mark Dickinson192ce612009-11-28 16:39:12 +0000929 int real_negzero, imag_negzero;
930 /* For the complex case we must make complex(x, 0.)
931 different from complex(x, -0.) and complex(0., y)
932 different from complex(-0., y), for any x and y.
933 All four complex zeros must be distinguished.*/
Christian Heimes400adb02008-02-01 08:12:03 +0000934 z = PyComplex_AsCComplex(o);
Mark Dickinson192ce612009-11-28 16:39:12 +0000935 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
936 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
937 if (real_negzero && imag_negzero) {
938 t = PyTuple_Pack(5, o, o->ob_type,
939 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000940 }
Mark Dickinson192ce612009-11-28 16:39:12 +0000941 else if (imag_negzero) {
942 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000943 }
Mark Dickinson192ce612009-11-28 16:39:12 +0000944 else if (real_negzero) {
945 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000946 }
947 else {
948 t = PyTuple_Pack(2, o, o->ob_type);
949 }
950 }
Mark Dickinsonb42dab52009-10-27 17:31:26 +0000951#endif /* WITHOUT_COMPLEX */
Christian Heimes400adb02008-02-01 08:12:03 +0000952 else {
953 t = PyTuple_Pack(2, o, o->ob_type);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000954 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000955 if (t == NULL)
Christian Heimes400adb02008-02-01 08:12:03 +0000956 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957
958 v = PyDict_GetItem(dict, t);
959 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000960 if (PyErr_Occurred())
961 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000962 arg = PyDict_Size(dict);
Christian Heimes217cfd12007-12-02 14:31:20 +0000963 v = PyLong_FromLong(arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964 if (!v) {
965 Py_DECREF(t);
966 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000967 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 if (PyDict_SetItem(dict, t, v) < 0) {
969 Py_DECREF(t);
970 Py_DECREF(v);
971 return -1;
972 }
973 Py_DECREF(v);
974 }
975 else
Christian Heimes217cfd12007-12-02 14:31:20 +0000976 arg = PyLong_AsLong(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000978 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979}
980
981static int
982compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
983 PyObject *o)
984{
985 int arg = compiler_add_o(c, dict, o);
986 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000987 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 return compiler_addop_i(c, opcode, arg);
989}
990
991static int
992compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000993 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994{
995 int arg;
996 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
997 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999 arg = compiler_add_o(c, dict, mangled);
1000 Py_DECREF(mangled);
1001 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 return compiler_addop_i(c, opcode, arg);
1004}
1005
1006/* Add an opcode with an integer argument.
1007 Returns 0 on failure, 1 on success.
1008*/
1009
1010static int
1011compiler_addop_i(struct compiler *c, int opcode, int oparg)
1012{
1013 struct instr *i;
1014 int off;
1015 off = compiler_next_instr(c, c->u->u_curblock);
1016 if (off < 0)
1017 return 0;
1018 i = &c->u->u_curblock->b_instr[off];
1019 i->i_opcode = opcode;
1020 i->i_oparg = oparg;
1021 i->i_hasarg = 1;
1022 compiler_set_lineno(c, off);
1023 return 1;
1024}
1025
1026static int
1027compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1028{
1029 struct instr *i;
1030 int off;
1031
1032 assert(b != NULL);
1033 off = compiler_next_instr(c, c->u->u_curblock);
1034 if (off < 0)
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 i = &c->u->u_curblock->b_instr[off];
1037 i->i_opcode = opcode;
1038 i->i_target = b;
1039 i->i_hasarg = 1;
1040 if (absolute)
1041 i->i_jabs = 1;
1042 else
1043 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001044 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045 return 1;
1046}
1047
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001048/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1049 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050 it as the current block. NEXT_BLOCK() also creates an implicit jump
1051 from the current block to the new block.
1052*/
1053
Thomas Wouters89f507f2006-12-13 04:49:30 +00001054/* The returns inside these macros make it impossible to decref objects
1055 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056*/
1057
1058
1059#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001060 if (compiler_use_new_block((C)) == NULL) \
1061 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062}
1063
1064#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001065 if (compiler_next_block((C)) == NULL) \
1066 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067}
1068
1069#define ADDOP(C, OP) { \
1070 if (!compiler_addop((C), (OP))) \
1071 return 0; \
1072}
1073
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001074#define ADDOP_IN_SCOPE(C, OP) { \
1075 if (!compiler_addop((C), (OP))) { \
1076 compiler_exit_scope(c); \
1077 return 0; \
1078 } \
1079}
1080
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081#define ADDOP_O(C, OP, O, TYPE) { \
1082 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1083 return 0; \
1084}
1085
1086#define ADDOP_NAME(C, OP, O, TYPE) { \
1087 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1088 return 0; \
1089}
1090
1091#define ADDOP_I(C, OP, O) { \
1092 if (!compiler_addop_i((C), (OP), (O))) \
1093 return 0; \
1094}
1095
1096#define ADDOP_JABS(C, OP, O) { \
1097 if (!compiler_addop_j((C), (OP), (O), 1)) \
1098 return 0; \
1099}
1100
1101#define ADDOP_JREL(C, OP, O) { \
1102 if (!compiler_addop_j((C), (OP), (O), 0)) \
1103 return 0; \
1104}
1105
1106/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1107 the ASDL name to synthesize the name of the C type and the visit function.
1108*/
1109
1110#define VISIT(C, TYPE, V) {\
1111 if (!compiler_visit_ ## TYPE((C), (V))) \
1112 return 0; \
1113}
1114
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001115#define VISIT_IN_SCOPE(C, TYPE, V) {\
1116 if (!compiler_visit_ ## TYPE((C), (V))) { \
1117 compiler_exit_scope(c); \
1118 return 0; \
1119 } \
1120}
1121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122#define VISIT_SLICE(C, V, CTX) {\
1123 if (!compiler_visit_slice((C), (V), (CTX))) \
1124 return 0; \
1125}
1126
1127#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001128 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132 if (!compiler_visit_ ## TYPE((C), elt)) \
1133 return 0; \
1134 } \
1135}
1136
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001137#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001138 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001141 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001142 if (!compiler_visit_ ## TYPE((C), elt)) { \
1143 compiler_exit_scope(c); \
1144 return 0; \
1145 } \
1146 } \
1147}
1148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149static int
1150compiler_isdocstring(stmt_ty s)
1151{
1152 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return s->v.Expr.value->kind == Str_kind;
1155}
1156
1157/* Compile a sequence of statements, checking for a docstring. */
1158
1159static int
1160compiler_body(struct compiler *c, asdl_seq *stmts)
1161{
1162 int i = 0;
1163 stmt_ty st;
1164
1165 if (!asdl_seq_LEN(stmts))
1166 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001167 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001168 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1169 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 i = 1;
1171 VISIT(c, expr, st->v.Expr.value);
1172 if (!compiler_nameop(c, __doc__, Store))
1173 return 0;
1174 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001175 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001176 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 return 1;
1178}
1179
1180static PyCodeObject *
1181compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001182{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001183 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 static PyObject *module;
1186 if (!module) {
Christian Heimesfe82e772008-01-28 02:38:20 +00001187 module = PyUnicode_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188 if (!module)
1189 return NULL;
1190 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001191 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1192 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001193 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 switch (mod->kind) {
1195 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001196 if (!compiler_body(c, mod->v.Module.body)) {
1197 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 break;
1201 case Interactive_kind:
1202 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001203 VISIT_SEQ_IN_SCOPE(c, stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001204 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 break;
1206 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001207 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001208 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 break;
1210 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001211 PyErr_SetString(PyExc_SystemError,
1212 "suite should not be possible");
1213 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001214 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001215 PyErr_Format(PyExc_SystemError,
1216 "module kind %d should not be possible",
1217 mod->kind);
1218 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220 co = assemble(c, addNone);
1221 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001222 return co;
1223}
1224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225/* The test for LOCAL must come before the test for FREE in order to
1226 handle classes where name is both local and free. The local var is
1227 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001228*/
1229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230static int
1231get_ref_type(struct compiler *c, PyObject *name)
1232{
1233 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001234 if (scope == 0) {
1235 char buf[350];
1236 PyOS_snprintf(buf, sizeof(buf),
1237 "unknown scope for %.100s in %.100s(%s) in %s\n"
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001238 "symbols: %s\nlocals: %s\nglobals: %s",
Christian Heimes72b710a2008-05-26 13:28:38 +00001239 PyBytes_AS_STRING(name),
1240 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001241 PyObject_REPR(c->u->u_ste->ste_id),
1242 c->c_filename,
1243 PyObject_REPR(c->u->u_ste->ste_symbols),
1244 PyObject_REPR(c->u->u_varnames),
1245 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 Py_FatalError(buf);
1248 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001249
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251}
1252
1253static int
1254compiler_lookup_arg(PyObject *dict, PyObject *name)
1255{
1256 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001261 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001263 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001264 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265}
1266
1267static int
1268compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1269{
1270 int i, free = PyCode_GetNumFree(co);
1271 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1273 ADDOP_I(c, MAKE_FUNCTION, args);
1274 return 1;
1275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 for (i = 0; i < free; ++i) {
1277 /* Bypass com_addop_varname because it will generate
1278 LOAD_DEREF but LOAD_CLOSURE is needed.
1279 */
1280 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1281 int arg, reftype;
1282
1283 /* Special case: If a class contains a method with a
1284 free variable that has the same name as a method,
1285 the name will be considered free *and* local in the
1286 class. It should be handled by the closure, as
1287 well as by the normal name loookup logic.
1288 */
1289 reftype = get_ref_type(c, name);
1290 if (reftype == CELL)
1291 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1292 else /* (reftype == FREE) */
1293 arg = compiler_lookup_arg(c->u->u_freevars, name);
1294 if (arg == -1) {
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001295 fprintf(stderr,
1296 "lookup %s in %s %d %d\n"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297 "freevars of %s: %s\n",
1298 PyObject_REPR(name),
Christian Heimes72b710a2008-05-26 13:28:38 +00001299 PyBytes_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300 reftype, arg,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001301 _PyUnicode_AsString(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302 PyObject_REPR(co->co_freevars));
1303 Py_FatalError("compiler_make_closure()");
1304 }
1305 ADDOP_I(c, LOAD_CLOSURE, arg);
1306 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001309 ADDOP_I(c, MAKE_CLOSURE, args);
1310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
1314compiler_decorators(struct compiler *c, asdl_seq* decos)
1315{
1316 int i;
1317
1318 if (!decos)
1319 return 1;
1320
1321 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 }
1324 return 1;
1325}
1326
1327static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001328compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1329 asdl_seq *kw_defaults)
1330{
1331 int i, default_count = 0;
1332 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001333 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001334 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1335 if (default_) {
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001336 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001337 if (!compiler_visit_expr(c, default_)) {
1338 return -1;
1339 }
1340 default_count++;
1341 }
1342 }
1343 return default_count;
1344}
1345
1346static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001347compiler_visit_argannotation(struct compiler *c, identifier id,
1348 expr_ty annotation, PyObject *names)
1349{
1350 if (annotation) {
1351 VISIT(c, expr, annotation);
1352 if (PyList_Append(names, id))
1353 return -1;
1354 }
1355 return 0;
1356}
1357
1358static int
1359compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1360 PyObject *names)
1361{
1362 int i, error;
1363 for (i = 0; i < asdl_seq_LEN(args); i++) {
1364 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001365 error = compiler_visit_argannotation(
1366 c,
1367 arg->arg,
1368 arg->annotation,
1369 names);
Neal Norwitzc1505362006-12-28 06:47:50 +00001370 if (error)
1371 return error;
1372 }
1373 return 0;
1374}
1375
1376static int
1377compiler_visit_annotations(struct compiler *c, arguments_ty args,
1378 expr_ty returns)
1379{
Guido van Rossum0240b922007-02-26 21:23:50 +00001380 /* Push arg annotations and a list of the argument names. Return the #
1381 of items pushed. The expressions are evaluated out-of-order wrt the
1382 source code.
1383
1384 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1385 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001386 static identifier return_str;
1387 PyObject *names;
1388 int len;
1389 names = PyList_New(0);
1390 if (!names)
1391 return -1;
1392
1393 if (compiler_visit_argannotations(c, args->args, names))
1394 goto error;
1395 if (args->varargannotation &&
1396 compiler_visit_argannotation(c, args->vararg,
1397 args->varargannotation, names))
1398 goto error;
1399 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1400 goto error;
1401 if (args->kwargannotation &&
1402 compiler_visit_argannotation(c, args->kwarg,
1403 args->kwargannotation, names))
1404 goto error;
1405
1406 if (!return_str) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001407 return_str = PyUnicode_InternFromString("return");
Neal Norwitzc1505362006-12-28 06:47:50 +00001408 if (!return_str)
1409 goto error;
1410 }
1411 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1412 goto error;
1413 }
1414
1415 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001416 if (len > 65534) {
1417 /* len must fit in 16 bits, and len is incremented below */
1418 PyErr_SetString(PyExc_SyntaxError,
1419 "too many annotations");
1420 goto error;
1421 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001422 if (len) {
1423 /* convert names to a tuple and place on stack */
1424 PyObject *elt;
1425 int i;
1426 PyObject *s = PyTuple_New(len);
1427 if (!s)
1428 goto error;
1429 for (i = 0; i < len; i++) {
1430 elt = PyList_GET_ITEM(names, i);
1431 Py_INCREF(elt);
1432 PyTuple_SET_ITEM(s, i, elt);
1433 }
1434 ADDOP_O(c, LOAD_CONST, s, consts);
1435 Py_DECREF(s);
1436 len++; /* include the just-pushed tuple */
1437 }
1438 Py_DECREF(names);
1439 return len;
1440
1441error:
1442 Py_DECREF(names);
1443 return -1;
1444}
1445
1446static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447compiler_function(struct compiler *c, stmt_ty s)
1448{
1449 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001450 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001452 expr_ty returns = s->v.FunctionDef.returns;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001453 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001454 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001455 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001456 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457
1458 assert(s->kind == FunctionDef_kind);
1459
1460 if (!compiler_decorators(c, decos))
1461 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001462 if (args->kwonlyargs) {
1463 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1464 args->kw_defaults);
1465 if (res < 0)
1466 return 0;
1467 kw_default_count = res;
1468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 if (args->defaults)
1470 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001471 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001472 if (num_annotations < 0)
1473 return 0;
1474 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1477 s->lineno))
1478 return 0;
1479
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001480 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 docstring = compiler_isdocstring(st);
Thomas Woutersce272b62007-09-19 21:19:28 +00001482 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001483 first_const = st->v.Expr.value->v.Str.s;
1484 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001485 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001486 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001487 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001490 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001492 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001494 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1495 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496 }
1497 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001498 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499 if (co == NULL)
1500 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501
Guido van Rossum4f72a782006-10-27 23:31:49 +00001502 arglength = asdl_seq_LEN(args->defaults);
1503 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001504 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001505 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001506 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507
Neal Norwitzc1505362006-12-28 06:47:50 +00001508 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1510 ADDOP_I(c, CALL_FUNCTION, 1);
1511 }
1512
1513 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1514}
1515
1516static int
1517compiler_class(struct compiler *c, stmt_ty s)
1518{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001520 PyObject *str;
Benjamin Petersondcaf3292009-03-03 00:54:05 +00001521 int i;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001522 asdl_seq* decos = s->v.ClassDef.decorator_list;
1523
1524 if (!compiler_decorators(c, decos))
1525 return 0;
1526
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001527 /* ultimately generate code for:
1528 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1529 where:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001530 <func> is a function/closure created from the class body;
1531 it has a single argument (__locals__) where the dict
1532 (or MutableSequence) representing the locals is passed
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001533 <name> is the class name
1534 <bases> is the positional arguments and *varargs argument
1535 <keywords> is the keyword arguments and **kwds argument
1536 This borrows from compiler_call.
1537 */
1538
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001539 /* 1. compile the class body into a code object */
1540 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1541 return 0;
1542 /* this block represents what we do in the new scope */
1543 {
1544 /* use the class name for name mangling */
1545 Py_INCREF(s->v.ClassDef.name);
Neal Norwitz36e63102008-04-01 08:08:09 +00001546 Py_XDECREF(c->u->u_private);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001547 c->u->u_private = s->v.ClassDef.name;
1548 /* force it to have one mandatory argument */
1549 c->u->u_argcount = 1;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001550 /* load the first argument (__locals__) ... */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001551 ADDOP_I(c, LOAD_FAST, 0);
1552 /* ... and store it into f_locals */
1553 ADDOP_IN_SCOPE(c, STORE_LOCALS);
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001554 /* load (global) __name__ ... */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001555 str = PyUnicode_InternFromString("__name__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001556 if (!str || !compiler_nameop(c, str, Load)) {
1557 Py_XDECREF(str);
1558 compiler_exit_scope(c);
1559 return 0;
1560 }
1561 Py_DECREF(str);
1562 /* ... and store it as __module__ */
Martin v. Löwis5b222132007-06-10 09:51:05 +00001563 str = PyUnicode_InternFromString("__module__");
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001564 if (!str || !compiler_nameop(c, str, Store)) {
1565 Py_XDECREF(str);
1566 compiler_exit_scope(c);
1567 return 0;
1568 }
1569 Py_DECREF(str);
1570 /* compile the body proper */
1571 if (!compiler_body(c, s->v.ClassDef.body)) {
1572 compiler_exit_scope(c);
1573 return 0;
1574 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001575 /* return the (empty) __class__ cell */
1576 str = PyUnicode_InternFromString("__class__");
1577 if (str == NULL) {
1578 compiler_exit_scope(c);
1579 return 0;
1580 }
1581 i = compiler_lookup_arg(c->u->u_cellvars, str);
1582 Py_DECREF(str);
1583 if (i == -1) {
1584 /* This happens when nobody references the cell */
1585 PyErr_Clear();
1586 /* Return None */
1587 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1588 }
1589 else {
1590 /* Return the cell where to store __class__ */
1591 ADDOP_I(c, LOAD_CLOSURE, i);
1592 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001593 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1594 /* create the code object */
1595 co = assemble(c, 1);
1596 }
1597 /* leave the new scope */
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001598 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599 if (co == NULL)
1600 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001602 /* 2. load the 'build_class' function */
1603 ADDOP(c, LOAD_BUILD_CLASS);
1604
1605 /* 3. load a function (or closure) made from the code object */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001606 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001607 Py_DECREF(co);
1608
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001609 /* 4. load class name */
1610 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1611
1612 /* 5. generate the rest of the code for the call */
1613 if (!compiler_call_helper(c, 2,
1614 s->v.ClassDef.bases,
1615 s->v.ClassDef.keywords,
1616 s->v.ClassDef.starargs,
1617 s->v.ClassDef.kwargs))
1618 return 0;
1619
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001620 /* 6. apply decorators */
1621 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1622 ADDOP_I(c, CALL_FUNCTION, 1);
1623 }
1624
1625 /* 7. store into <name> */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1627 return 0;
1628 return 1;
1629}
1630
1631static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001632compiler_ifexp(struct compiler *c, expr_ty e)
1633{
1634 basicblock *end, *next;
1635
1636 assert(e->kind == IfExp_kind);
1637 end = compiler_new_block(c);
1638 if (end == NULL)
1639 return 0;
1640 next = compiler_new_block(c);
1641 if (next == NULL)
1642 return 0;
1643 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001644 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001645 VISIT(c, expr, e->v.IfExp.body);
1646 ADDOP_JREL(c, JUMP_FORWARD, end);
1647 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001648 VISIT(c, expr, e->v.IfExp.orelse);
1649 compiler_use_next_block(c, end);
1650 return 1;
1651}
1652
1653static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654compiler_lambda(struct compiler *c, expr_ty e)
1655{
1656 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001657 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001658 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001659 arguments_ty args = e->v.Lambda.args;
1660 assert(e->kind == Lambda_kind);
1661
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001662 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001663 name = PyUnicode_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001664 if (!name)
1665 return 0;
1666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667
Guido van Rossum4f72a782006-10-27 23:31:49 +00001668 if (args->kwonlyargs) {
1669 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1670 args->kw_defaults);
1671 if (res < 0) return 0;
1672 kw_default_count = res;
1673 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 if (args->defaults)
1675 VISIT_SEQ(c, expr, args->defaults);
1676 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1677 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001680 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001681 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson371ccfb2008-12-27 19:03:36 +00001682 if (c->u->u_ste->ste_generator) {
1683 ADDOP_IN_SCOPE(c, POP_TOP);
1684 }
1685 else {
1686 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1687 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001689 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690 if (co == NULL)
1691 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692
Guido van Rossum4f72a782006-10-27 23:31:49 +00001693 arglength = asdl_seq_LEN(args->defaults);
1694 arglength |= kw_default_count << 8;
1695 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001696 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697
1698 return 1;
1699}
1700
1701static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702compiler_if(struct compiler *c, stmt_ty s)
1703{
1704 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001705 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 assert(s->kind == If_kind);
1707 end = compiler_new_block(c);
1708 if (end == NULL)
1709 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001710
1711 constant = expr_constant(s->v.If.test);
1712 /* constant = 0: "if 0"
1713 * constant = 1: "if 1", "if 2", ...
1714 * constant = -1: rest */
1715 if (constant == 0) {
1716 if (s->v.If.orelse)
1717 VISIT_SEQ(c, stmt, s->v.If.orelse);
1718 } else if (constant == 1) {
1719 VISIT_SEQ(c, stmt, s->v.If.body);
1720 } else {
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001721 if (s->v.If.orelse) {
1722 next = compiler_new_block(c);
1723 if (next == NULL)
1724 return 0;
1725 }
1726 else
1727 next = end;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001728 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001729 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001730 VISIT_SEQ(c, stmt, s->v.If.body);
1731 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001732 if (s->v.If.orelse) {
1733 compiler_use_next_block(c, next);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001734 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001735 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001736 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737 compiler_use_next_block(c, end);
1738 return 1;
1739}
1740
1741static int
1742compiler_for(struct compiler *c, stmt_ty s)
1743{
1744 basicblock *start, *cleanup, *end;
1745
1746 start = compiler_new_block(c);
1747 cleanup = compiler_new_block(c);
1748 end = compiler_new_block(c);
1749 if (start == NULL || end == NULL || cleanup == NULL)
1750 return 0;
1751 ADDOP_JREL(c, SETUP_LOOP, end);
1752 if (!compiler_push_fblock(c, LOOP, start))
1753 return 0;
1754 VISIT(c, expr, s->v.For.iter);
1755 ADDOP(c, GET_ITER);
1756 compiler_use_next_block(c, start);
Christian Heimes2202f872008-02-06 14:31:34 +00001757 /* for expressions must be traced on each iteration,
1758 so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001759 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760 ADDOP_JREL(c, FOR_ITER, cleanup);
1761 VISIT(c, expr, s->v.For.target);
1762 VISIT_SEQ(c, stmt, s->v.For.body);
1763 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1764 compiler_use_next_block(c, cleanup);
1765 ADDOP(c, POP_BLOCK);
1766 compiler_pop_fblock(c, LOOP, start);
1767 VISIT_SEQ(c, stmt, s->v.For.orelse);
1768 compiler_use_next_block(c, end);
1769 return 1;
1770}
1771
1772static int
1773compiler_while(struct compiler *c, stmt_ty s)
1774{
1775 basicblock *loop, *orelse, *end, *anchor = NULL;
1776 int constant = expr_constant(s->v.While.test);
1777
Christian Heimes969fe572008-01-25 11:23:10 +00001778 if (constant == 0) {
1779 if (s->v.While.orelse)
1780 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 return 1;
Christian Heimes969fe572008-01-25 11:23:10 +00001782 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783 loop = compiler_new_block(c);
1784 end = compiler_new_block(c);
1785 if (constant == -1) {
1786 anchor = compiler_new_block(c);
1787 if (anchor == NULL)
1788 return 0;
1789 }
1790 if (loop == NULL || end == NULL)
1791 return 0;
1792 if (s->v.While.orelse) {
1793 orelse = compiler_new_block(c);
1794 if (orelse == NULL)
1795 return 0;
1796 }
1797 else
1798 orelse = NULL;
1799
1800 ADDOP_JREL(c, SETUP_LOOP, end);
1801 compiler_use_next_block(c, loop);
1802 if (!compiler_push_fblock(c, LOOP, loop))
1803 return 0;
1804 if (constant == -1) {
Christian Heimes2202f872008-02-06 14:31:34 +00001805 /* while expressions must be traced on each iteration,
1806 so we need to set an extra line number. */
1807 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001809 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810 }
1811 VISIT_SEQ(c, stmt, s->v.While.body);
1812 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1813
1814 /* XXX should the two POP instructions be in a separate block
1815 if there is no else clause ?
1816 */
1817
1818 if (constant == -1) {
1819 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820 ADDOP(c, POP_BLOCK);
1821 }
1822 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001823 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824 VISIT_SEQ(c, stmt, s->v.While.orelse);
1825 compiler_use_next_block(c, end);
1826
1827 return 1;
1828}
1829
1830static int
1831compiler_continue(struct compiler *c)
1832{
1833 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001834 static const char IN_FINALLY_ERROR_MSG[] =
1835 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 int i;
1837
1838 if (!c->u->u_nfblocks)
1839 return compiler_error(c, LOOP_ERROR_MSG);
1840 i = c->u->u_nfblocks - 1;
1841 switch (c->u->u_fblock[i].fb_type) {
1842 case LOOP:
1843 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1844 break;
1845 case EXCEPT:
1846 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001847 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1848 /* Prevent continue anywhere under a finally
1849 even if hidden in a sub-try or except. */
1850 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1851 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1852 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 if (i == -1)
1854 return compiler_error(c, LOOP_ERROR_MSG);
1855 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1856 break;
1857 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001858 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 }
1860
1861 return 1;
1862}
1863
1864/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1865
1866 SETUP_FINALLY L
1867 <code for body>
1868 POP_BLOCK
1869 LOAD_CONST <None>
1870 L: <code for finalbody>
1871 END_FINALLY
1872
1873 The special instructions use the block stack. Each block
1874 stack entry contains the instruction that created it (here
1875 SETUP_FINALLY), the level of the value stack at the time the
1876 block stack entry was created, and a label (here L).
1877
1878 SETUP_FINALLY:
1879 Pushes the current value stack level and the label
1880 onto the block stack.
1881 POP_BLOCK:
1882 Pops en entry from the block stack, and pops the value
1883 stack until its level is the same as indicated on the
1884 block stack. (The label is ignored.)
1885 END_FINALLY:
1886 Pops a variable number of entries from the *value* stack
1887 and re-raises the exception they specify. The number of
1888 entries popped depends on the (pseudo) exception type.
1889
1890 The block stack is unwound when an exception is raised:
1891 when a SETUP_FINALLY entry is found, the exception is pushed
1892 onto the value stack (and the exception condition is cleared),
1893 and the interpreter jumps to the label gotten from the block
1894 stack.
1895*/
1896
1897static int
1898compiler_try_finally(struct compiler *c, stmt_ty s)
1899{
1900 basicblock *body, *end;
1901 body = compiler_new_block(c);
1902 end = compiler_new_block(c);
1903 if (body == NULL || end == NULL)
1904 return 0;
1905
1906 ADDOP_JREL(c, SETUP_FINALLY, end);
1907 compiler_use_next_block(c, body);
1908 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1909 return 0;
1910 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1911 ADDOP(c, POP_BLOCK);
1912 compiler_pop_fblock(c, FINALLY_TRY, body);
1913
1914 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1915 compiler_use_next_block(c, end);
1916 if (!compiler_push_fblock(c, FINALLY_END, end))
1917 return 0;
1918 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1919 ADDOP(c, END_FINALLY);
1920 compiler_pop_fblock(c, FINALLY_END, end);
1921
1922 return 1;
1923}
1924
1925/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001926 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 (The contents of the value stack is shown in [], with the top
1928 at the right; 'tb' is trace-back info, 'val' the exception's
1929 associated value, and 'exc' the exception.)
1930
1931 Value stack Label Instruction Argument
1932 [] SETUP_EXCEPT L1
1933 [] <code for S>
1934 [] POP_BLOCK
1935 [] JUMP_FORWARD L0
1936
1937 [tb, val, exc] L1: DUP )
1938 [tb, val, exc, exc] <evaluate E1> )
1939 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001940 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 [tb, val, exc] POP
1942 [tb, val] <assign to V1> (or POP if no V1)
1943 [tb] POP
1944 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001945 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001947 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948 .............................etc.......................
1949
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001950 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951
1952 [] L0: <next statement>
1953
1954 Of course, parts are not generated if Vi or Ei is not present.
1955*/
1956static int
1957compiler_try_except(struct compiler *c, stmt_ty s)
1958{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001959 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 int i, n;
1961
1962 body = compiler_new_block(c);
1963 except = compiler_new_block(c);
1964 orelse = compiler_new_block(c);
1965 end = compiler_new_block(c);
1966 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1967 return 0;
1968 ADDOP_JREL(c, SETUP_EXCEPT, except);
1969 compiler_use_next_block(c, body);
1970 if (!compiler_push_fblock(c, EXCEPT, body))
1971 return 0;
1972 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1973 ADDOP(c, POP_BLOCK);
1974 compiler_pop_fblock(c, EXCEPT, body);
1975 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1976 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1977 compiler_use_next_block(c, except);
1978 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001979 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 s->v.TryExcept.handlers, i);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001981 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 return compiler_error(c, "default 'except:' must be last");
Christian Heimes2202f872008-02-06 14:31:34 +00001983 c->u->u_lineno_set = 0;
1984 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985 except = compiler_new_block(c);
1986 if (except == NULL)
1987 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00001988 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 ADDOP(c, DUP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001990 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001992 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 }
1994 ADDOP(c, POP_TOP);
Neal Norwitzad74aa82008-03-31 05:14:30 +00001995 if (handler->v.ExceptHandler.name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001996 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001997
1998 cleanup_end = compiler_new_block(c);
1999 cleanup_body = compiler_new_block(c);
2000 if(!(cleanup_end || cleanup_body))
2001 return 0;
2002
Neal Norwitzad74aa82008-03-31 05:14:30 +00002003 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002004 ADDOP(c, POP_TOP);
2005
2006 /*
2007 try:
2008 # body
2009 except type as name:
2010 try:
2011 # body
2012 finally:
2013 name = None
2014 del name
2015 */
2016
2017 /* second try: */
2018 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2019 compiler_use_next_block(c, cleanup_body);
2020 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2021 return 0;
2022
2023 /* second # body */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002024 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Guido van Rossumb940e112007-01-10 16:19:56 +00002025 ADDOP(c, POP_BLOCK);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002026 ADDOP(c, POP_EXCEPT);
Guido van Rossumb940e112007-01-10 16:19:56 +00002027 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2028
2029 /* finally: */
2030 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2031 compiler_use_next_block(c, cleanup_end);
2032 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2033 return 0;
2034
2035 /* name = None */
2036 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Neal Norwitzad74aa82008-03-31 05:14:30 +00002037 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00002038
Guido van Rossum16be03e2007-01-10 18:51:35 +00002039 /* del name */
Neal Norwitzad74aa82008-03-31 05:14:30 +00002040 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00002041
2042 ADDOP(c, END_FINALLY);
2043 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044 }
2045 else {
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002046 basicblock *cleanup_body;
2047
2048 cleanup_body = compiler_new_block(c);
2049 if(!cleanup_body)
2050 return 0;
2051
2052 ADDOP(c, POP_TOP);
Guido van Rossumb940e112007-01-10 16:19:56 +00002053 ADDOP(c, POP_TOP);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002054 compiler_use_next_block(c, cleanup_body);
2055 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2056 return 0;
Neal Norwitzad74aa82008-03-31 05:14:30 +00002057 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00002058 ADDOP(c, POP_EXCEPT);
2059 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061 ADDOP_JREL(c, JUMP_FORWARD, end);
2062 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 }
2064 ADDOP(c, END_FINALLY);
2065 compiler_use_next_block(c, orelse);
2066 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2067 compiler_use_next_block(c, end);
2068 return 1;
2069}
2070
2071static int
2072compiler_import_as(struct compiler *c, identifier name, identifier asname)
2073{
2074 /* The IMPORT_NAME opcode was already generated. This function
2075 merely needs to bind the result to a name.
2076
2077 If there is a dot in name, we need to split it and emit a
2078 LOAD_ATTR for each name.
2079 */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002080 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2081 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 if (dot) {
2083 /* Consume the base module name to get the first attribute */
2084 src = dot + 1;
2085 while (dot) {
2086 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002087 PyObject *attr;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002088 dot = Py_UNICODE_strchr(src, '.');
2089 attr = PyUnicode_FromUnicode(src,
2090 dot ? dot - src : Py_UNICODE_strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002091 if (!attr)
2092 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002094 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 src = dot + 1;
2096 }
2097 }
2098 return compiler_nameop(c, asname, Store);
2099}
2100
2101static int
2102compiler_import(struct compiler *c, stmt_ty s)
2103{
2104 /* The Import node stores a module name like a.b.c as a single
2105 string. This is convenient for all cases except
2106 import a.b.c as d
2107 where we need to parse that string to extract the individual
2108 module names.
2109 XXX Perhaps change the representation to make this case simpler?
2110 */
2111 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002112
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002114 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002116 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117
Christian Heimes217cfd12007-12-02 14:31:20 +00002118 level = PyLong_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002119 if (level == NULL)
2120 return 0;
2121
2122 ADDOP_O(c, LOAD_CONST, level, consts);
2123 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2125 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2126
2127 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002128 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 if (!r)
2130 return r;
2131 }
2132 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 identifier tmp = alias->name;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002134 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2135 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 if (dot)
Martin v. Löwis5b222132007-06-10 09:51:05 +00002137 tmp = PyUnicode_FromUnicode(base,
2138 dot - base);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139 r = compiler_nameop(c, tmp, Store);
2140 if (dot) {
2141 Py_DECREF(tmp);
2142 }
2143 if (!r)
2144 return r;
2145 }
2146 }
2147 return 1;
2148}
2149
2150static int
2151compiler_from_import(struct compiler *c, stmt_ty s)
2152{
2153 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154
2155 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002156 PyObject *level;
2157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158 if (!names)
2159 return 0;
2160
Christian Heimes217cfd12007-12-02 14:31:20 +00002161 level = PyLong_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002162 if (!level) {
2163 Py_DECREF(names);
2164 return 0;
2165 }
2166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 /* build up the names */
2168 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002169 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 Py_INCREF(alias->name);
2171 PyTuple_SET_ITEM(names, i, alias->name);
2172 }
2173
2174 if (s->lineno > c->c_future->ff_lineno) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002175 if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module,
2176 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002177 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178 Py_DECREF(names);
2179 return compiler_error(c,
2180 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002181 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182
2183 }
2184 }
2185
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002186 ADDOP_O(c, LOAD_CONST, level, consts);
2187 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002189 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2191 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002192 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 identifier store_name;
2194
Martin v. Löwis5b222132007-06-10 09:51:05 +00002195 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196 assert(n == 1);
2197 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199 }
2200
2201 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2202 store_name = alias->name;
2203 if (alias->asname)
2204 store_name = alias->asname;
2205
2206 if (!compiler_nameop(c, store_name, Store)) {
2207 Py_DECREF(names);
2208 return 0;
2209 }
2210 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002211 /* remove imported module */
2212 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213 return 1;
2214}
2215
2216static int
2217compiler_assert(struct compiler *c, stmt_ty s)
2218{
2219 static PyObject *assertion_error = NULL;
2220 basicblock *end;
2221
2222 if (Py_OptimizeFlag)
2223 return 1;
2224 if (assertion_error == NULL) {
Christian Heimesfe82e772008-01-28 02:38:20 +00002225 assertion_error = PyUnicode_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226 if (assertion_error == NULL)
2227 return 0;
2228 }
Christian Heimes08976cb2008-03-16 00:32:36 +00002229 if (s->v.Assert.test->kind == Tuple_kind &&
2230 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2231 const char* msg =
2232 "assertion is always true, perhaps remove parentheses?";
2233 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2234 c->u->u_lineno, NULL, NULL) == -1)
2235 return 0;
2236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237 VISIT(c, expr, s->v.Assert.test);
2238 end = compiler_new_block(c);
2239 if (end == NULL)
2240 return 0;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002241 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2243 if (s->v.Assert.msg) {
2244 VISIT(c, expr, s->v.Assert.msg);
Collin Winter828f04a2007-08-31 00:04:24 +00002245 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246 }
Collin Winter828f04a2007-08-31 00:04:24 +00002247 ADDOP_I(c, RAISE_VARARGS, 1);
Neal Norwitz51abbc72005-12-18 07:06:23 +00002248 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249 return 1;
2250}
2251
2252static int
2253compiler_visit_stmt(struct compiler *c, stmt_ty s)
2254{
2255 int i, n;
2256
Thomas Wouters89f507f2006-12-13 04:49:30 +00002257 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002259 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002264 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002266 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 if (c->u->u_ste->ste_type != FunctionBlock)
2268 return compiler_error(c, "'return' outside function");
2269 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 VISIT(c, expr, s->v.Return.value);
2271 }
2272 else
2273 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2274 ADDOP(c, RETURN_VALUE);
2275 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002276 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277 VISIT_SEQ(c, expr, s->v.Delete.targets)
2278 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002279 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 n = asdl_seq_LEN(s->v.Assign.targets);
2281 VISIT(c, expr, s->v.Assign.value);
2282 for (i = 0; i < n; i++) {
2283 if (i < n - 1)
2284 ADDOP(c, DUP_TOP);
2285 VISIT(c, expr,
2286 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2287 }
2288 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002289 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002295 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002297 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 n = 0;
Collin Winter828f04a2007-08-31 00:04:24 +00002299 if (s->v.Raise.exc) {
2300 VISIT(c, expr, s->v.Raise.exc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301 n++;
Collin Winter828f04a2007-08-31 00:04:24 +00002302 if (s->v.Raise.cause) {
2303 VISIT(c, expr, s->v.Raise.cause);
2304 n++;
2305 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 }
2307 ADDOP_I(c, RAISE_VARARGS, n);
2308 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002309 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002311 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002313 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002315 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002317 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002319 case Global_kind:
Jeremy Hylton81e95022007-02-27 06:50:52 +00002320 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002322 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002324 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 ADDOP(c, PRINT_EXPR);
2326 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002327 else if (s->v.Expr.value->kind != Str_kind &&
2328 s->v.Expr.value->kind != Num_kind) {
2329 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 ADDOP(c, POP_TOP);
2331 }
2332 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002333 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002335 case Break_kind:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002336 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 return compiler_error(c, "'break' outside loop");
2338 ADDOP(c, BREAK_LOOP);
2339 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002340 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002342 case With_kind:
2343 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344 }
2345 return 1;
2346}
2347
2348static int
2349unaryop(unaryop_ty op)
2350{
2351 switch (op) {
2352 case Invert:
2353 return UNARY_INVERT;
2354 case Not:
2355 return UNARY_NOT;
2356 case UAdd:
2357 return UNARY_POSITIVE;
2358 case USub:
2359 return UNARY_NEGATIVE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002360 default:
2361 PyErr_Format(PyExc_SystemError,
2362 "unary op %d should not be possible", op);
2363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365}
2366
2367static int
2368binop(struct compiler *c, operator_ty op)
2369{
2370 switch (op) {
2371 case Add:
2372 return BINARY_ADD;
2373 case Sub:
2374 return BINARY_SUBTRACT;
2375 case Mult:
2376 return BINARY_MULTIPLY;
2377 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002378 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379 case Mod:
2380 return BINARY_MODULO;
2381 case Pow:
2382 return BINARY_POWER;
2383 case LShift:
2384 return BINARY_LSHIFT;
2385 case RShift:
2386 return BINARY_RSHIFT;
2387 case BitOr:
2388 return BINARY_OR;
2389 case BitXor:
2390 return BINARY_XOR;
2391 case BitAnd:
2392 return BINARY_AND;
2393 case FloorDiv:
2394 return BINARY_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002395 default:
2396 PyErr_Format(PyExc_SystemError,
2397 "binary op %d should not be possible", op);
2398 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400}
2401
2402static int
2403cmpop(cmpop_ty op)
2404{
2405 switch (op) {
2406 case Eq:
2407 return PyCmp_EQ;
2408 case NotEq:
2409 return PyCmp_NE;
2410 case Lt:
2411 return PyCmp_LT;
2412 case LtE:
2413 return PyCmp_LE;
2414 case Gt:
2415 return PyCmp_GT;
2416 case GtE:
2417 return PyCmp_GE;
2418 case Is:
2419 return PyCmp_IS;
2420 case IsNot:
2421 return PyCmp_IS_NOT;
2422 case In:
2423 return PyCmp_IN;
2424 case NotIn:
2425 return PyCmp_NOT_IN;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002426 default:
2427 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002429}
2430
2431static int
2432inplace_binop(struct compiler *c, operator_ty op)
2433{
2434 switch (op) {
2435 case Add:
2436 return INPLACE_ADD;
2437 case Sub:
2438 return INPLACE_SUBTRACT;
2439 case Mult:
2440 return INPLACE_MULTIPLY;
2441 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002442 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443 case Mod:
2444 return INPLACE_MODULO;
2445 case Pow:
2446 return INPLACE_POWER;
2447 case LShift:
2448 return INPLACE_LSHIFT;
2449 case RShift:
2450 return INPLACE_RSHIFT;
2451 case BitOr:
2452 return INPLACE_OR;
2453 case BitXor:
2454 return INPLACE_XOR;
2455 case BitAnd:
2456 return INPLACE_AND;
2457 case FloorDiv:
2458 return INPLACE_FLOOR_DIVIDE;
Martin v. Löwis618dc5e2008-03-30 20:03:44 +00002459 default:
2460 PyErr_Format(PyExc_SystemError,
2461 "inplace binary op %d should not be possible", op);
2462 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464}
2465
2466static int
2467compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2468{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002469 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2471
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002472 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002473 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 /* XXX AugStore isn't used anywhere! */
2475
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002476 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002477 if (!mangled)
2478 return 0;
2479
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480 op = 0;
2481 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002482 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 switch (scope) {
2484 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002485 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 optype = OP_DEREF;
2487 break;
2488 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002489 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490 optype = OP_DEREF;
2491 break;
2492 case LOCAL:
2493 if (c->u->u_ste->ste_type == FunctionBlock)
2494 optype = OP_FAST;
2495 break;
2496 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002497 if (c->u->u_ste->ste_type == FunctionBlock &&
2498 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 optype = OP_GLOBAL;
2500 break;
2501 case GLOBAL_EXPLICIT:
2502 optype = OP_GLOBAL;
2503 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002504 default:
2505 /* scope can be 0 */
2506 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 }
2508
2509 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwis5b222132007-06-10 09:51:05 +00002510 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511
2512 switch (optype) {
2513 case OP_DEREF:
2514 switch (ctx) {
2515 case Load: op = LOAD_DEREF; break;
2516 case Store: op = STORE_DEREF; break;
2517 case AugLoad:
2518 case AugStore:
2519 break;
2520 case Del:
2521 PyErr_Format(PyExc_SyntaxError,
Walter Dörwald573c08c2007-05-25 15:46:59 +00002522 "can not delete variable '%S' referenced "
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523 "in nested scope",
Walter Dörwald573c08c2007-05-25 15:46:59 +00002524 name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002525 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002528 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002529 PyErr_SetString(PyExc_SystemError,
2530 "param invalid for deref variable");
2531 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 }
2533 break;
2534 case OP_FAST:
2535 switch (ctx) {
2536 case Load: op = LOAD_FAST; break;
2537 case Store: op = STORE_FAST; break;
2538 case Del: op = DELETE_FAST; break;
2539 case AugLoad:
2540 case AugStore:
2541 break;
2542 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002543 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002544 PyErr_SetString(PyExc_SystemError,
2545 "param invalid for local variable");
2546 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002548 ADDOP_O(c, op, mangled, varnames);
2549 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 return 1;
2551 case OP_GLOBAL:
2552 switch (ctx) {
2553 case Load: op = LOAD_GLOBAL; break;
2554 case Store: op = STORE_GLOBAL; break;
2555 case Del: op = DELETE_GLOBAL; break;
2556 case AugLoad:
2557 case AugStore:
2558 break;
2559 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002560 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002561 PyErr_SetString(PyExc_SystemError,
2562 "param invalid for global variable");
2563 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 }
2565 break;
2566 case OP_NAME:
2567 switch (ctx) {
2568 case Load: op = LOAD_NAME; break;
2569 case Store: op = STORE_NAME; break;
2570 case Del: op = DELETE_NAME; break;
2571 case AugLoad:
2572 case AugStore:
2573 break;
2574 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002575 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002576 PyErr_SetString(PyExc_SystemError,
2577 "param invalid for name variable");
2578 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579 }
2580 break;
2581 }
2582
2583 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002584 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002585 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002586 if (arg < 0)
2587 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002588 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589}
2590
2591static int
2592compiler_boolop(struct compiler *c, expr_ty e)
2593{
2594 basicblock *end;
2595 int jumpi, i, n;
2596 asdl_seq *s;
2597
2598 assert(e->kind == BoolOp_kind);
2599 if (e->v.BoolOp.op == And)
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002600 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 else
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002602 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002604 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002605 return 0;
2606 s = e->v.BoolOp.values;
2607 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002608 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002610 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002611 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002613 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 compiler_use_next_block(c, end);
2615 return 1;
2616}
2617
2618static int
2619compiler_list(struct compiler *c, expr_ty e)
2620{
2621 int n = asdl_seq_LEN(e->v.List.elts);
2622 if (e->v.List.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002623 int i, seen_star = 0;
2624 for (i = 0; i < n; i++) {
2625 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2626 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002627 if ((i >= (1 << 8)) ||
2628 (n-i-1 >= (INT_MAX >> 8)))
2629 return compiler_error(c,
2630 "too many expressions in "
2631 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002632 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2633 seen_star = 1;
2634 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2635 } else if (elt->kind == Starred_kind) {
2636 return compiler_error(c,
2637 "two starred expressions in assignment");
2638 }
2639 }
2640 if (!seen_star) {
2641 ADDOP_I(c, UNPACK_SEQUENCE, n);
2642 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643 }
2644 VISIT_SEQ(c, expr, e->v.List.elts);
2645 if (e->v.List.ctx == Load) {
2646 ADDOP_I(c, BUILD_LIST, n);
2647 }
2648 return 1;
2649}
2650
2651static int
2652compiler_tuple(struct compiler *c, expr_ty e)
2653{
2654 int n = asdl_seq_LEN(e->v.Tuple.elts);
2655 if (e->v.Tuple.ctx == Store) {
Guido van Rossum0368b722007-05-11 16:50:42 +00002656 int i, seen_star = 0;
2657 for (i = 0; i < n; i++) {
2658 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2659 if (elt->kind == Starred_kind && !seen_star) {
Thomas Woutersdeef6742008-03-14 17:16:59 +00002660 if ((i >= (1 << 8)) ||
2661 (n-i-1 >= (INT_MAX >> 8)))
2662 return compiler_error(c,
2663 "too many expressions in "
2664 "star-unpacking assignment");
Guido van Rossum0368b722007-05-11 16:50:42 +00002665 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2666 seen_star = 1;
2667 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2668 } else if (elt->kind == Starred_kind) {
2669 return compiler_error(c,
2670 "two starred expressions in assignment");
2671 }
2672 }
2673 if (!seen_star) {
2674 ADDOP_I(c, UNPACK_SEQUENCE, n);
2675 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 }
2677 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2678 if (e->v.Tuple.ctx == Load) {
2679 ADDOP_I(c, BUILD_TUPLE, n);
2680 }
2681 return 1;
2682}
2683
2684static int
2685compiler_compare(struct compiler *c, expr_ty e)
2686{
2687 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002688 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689
2690 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2691 VISIT(c, expr, e->v.Compare.left);
2692 n = asdl_seq_LEN(e->v.Compare.ops);
2693 assert(n > 0);
2694 if (n > 1) {
2695 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002696 if (cleanup == NULL)
2697 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002698 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002699 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 }
2701 for (i = 1; i < n; i++) {
2702 ADDOP(c, DUP_TOP);
2703 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002705 cmpop((cmpop_ty)(asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002706 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002707 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002710 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002711 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002713 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002715 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 if (n > 1) {
2717 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002718 if (end == NULL)
2719 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 ADDOP_JREL(c, JUMP_FORWARD, end);
2721 compiler_use_next_block(c, cleanup);
2722 ADDOP(c, ROT_TWO);
2723 ADDOP(c, POP_TOP);
2724 compiler_use_next_block(c, end);
2725 }
2726 return 1;
2727}
2728
2729static int
2730compiler_call(struct compiler *c, expr_ty e)
2731{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 VISIT(c, expr, e->v.Call.func);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002733 return compiler_call_helper(c, 0,
2734 e->v.Call.args,
2735 e->v.Call.keywords,
2736 e->v.Call.starargs,
2737 e->v.Call.kwargs);
2738}
2739
2740/* shared code between compiler_call and compiler_class */
2741static int
2742compiler_call_helper(struct compiler *c,
2743 int n, /* Args already pushed */
2744 asdl_seq *args,
2745 asdl_seq *keywords,
2746 expr_ty starargs,
2747 expr_ty kwargs)
2748{
2749 int code = 0;
2750
2751 n += asdl_seq_LEN(args);
2752 VISIT_SEQ(c, expr, args);
2753 if (keywords) {
2754 VISIT_SEQ(c, keyword, keywords);
2755 n |= asdl_seq_LEN(keywords) << 8;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002757 if (starargs) {
2758 VISIT(c, expr, starargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759 code |= 1;
2760 }
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002761 if (kwargs) {
2762 VISIT(c, expr, kwargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763 code |= 2;
2764 }
2765 switch (code) {
2766 case 0:
2767 ADDOP_I(c, CALL_FUNCTION, n);
2768 break;
2769 case 1:
2770 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2771 break;
2772 case 2:
2773 ADDOP_I(c, CALL_FUNCTION_KW, n);
2774 break;
2775 case 3:
2776 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2777 break;
2778 }
2779 return 1;
2780}
2781
Nick Coghlan650f0d02007-04-15 12:05:43 +00002782
2783/* List and set comprehensions and generator expressions work by creating a
2784 nested function to perform the actual iteration. This means that the
2785 iteration variables don't leak into the current scope.
2786 The defined function is called immediately following its definition, with the
2787 result of that call being the result of the expression.
2788 The LC/SC version returns the populated container, while the GE version is
2789 flagged in symtable.c as a generator, so it returns the generator object
2790 when the function is called.
2791 This code *knows* that the loop cannot contain break, continue, or return,
2792 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2793
2794 Possible cleanups:
2795 - iterate over the generator sequence instead of using recursion
2796*/
2797
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798static int
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002799compiler_comprehension_generator(struct compiler *c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002800 asdl_seq *generators, int gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002801 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802{
2803 /* generate code for the iterator, then each of the ifs,
2804 and then write to the element */
2805
Nick Coghlan650f0d02007-04-15 12:05:43 +00002806 comprehension_ty gen;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002808 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809
2810 start = compiler_new_block(c);
2811 skip = compiler_new_block(c);
2812 if_cleanup = compiler_new_block(c);
2813 anchor = compiler_new_block(c);
2814
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Nick Coghlan650f0d02007-04-15 12:05:43 +00002816 anchor == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818
Nick Coghlan650f0d02007-04-15 12:05:43 +00002819 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821 if (gen_index == 0) {
2822 /* Receive outermost iter as an implicit argument */
2823 c->u->u_argcount = 1;
2824 ADDOP_I(c, LOAD_FAST, 0);
2825 }
2826 else {
2827 /* Sub-iter - calculate on the fly */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002828 VISIT(c, expr, gen->iter);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829 ADDOP(c, GET_ITER);
2830 }
2831 compiler_use_next_block(c, start);
2832 ADDOP_JREL(c, FOR_ITER, anchor);
2833 NEXT_BLOCK(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002834 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002836 /* XXX this needs to be cleaned up...a lot! */
Nick Coghlan650f0d02007-04-15 12:05:43 +00002837 n = asdl_seq_LEN(gen->ifs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838 for (i = 0; i < n; i++) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002839 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 VISIT(c, expr, e);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002841 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842 NEXT_BLOCK(c);
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002846 if (!compiler_comprehension_generator(c,
Nick Coghlan650f0d02007-04-15 12:05:43 +00002847 generators, gen_index,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002848 elt, val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002849 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002850
Nick Coghlan650f0d02007-04-15 12:05:43 +00002851 /* only append after the last for generator */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002852 if (gen_index >= asdl_seq_LEN(generators)) {
Nick Coghlan650f0d02007-04-15 12:05:43 +00002853 /* comprehension specific code */
2854 switch (type) {
2855 case COMP_GENEXP:
2856 VISIT(c, expr, elt);
2857 ADDOP(c, YIELD_VALUE);
2858 ADDOP(c, POP_TOP);
2859 break;
2860 case COMP_LISTCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002861 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002862 ADDOP_I(c, LIST_APPEND, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002863 break;
2864 case COMP_SETCOMP:
Nick Coghlan650f0d02007-04-15 12:05:43 +00002865 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002866 ADDOP_I(c, SET_ADD, gen_index + 1);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002867 break;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002868 case COMP_DICTCOMP:
Guido van Rossum992d4a32007-07-11 13:09:30 +00002869 /* With 'd[k] = v', v is evaluated before k, so we do
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002870 the same. */
Guido van Rossum992d4a32007-07-11 13:09:30 +00002871 VISIT(c, expr, val);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002872 VISIT(c, expr, elt);
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002873 ADDOP_I(c, MAP_ADD, gen_index + 1);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002874 break;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002875 default:
2876 return 0;
2877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
2879 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002880 }
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002881 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2883 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884
2885 return 1;
2886}
2887
2888static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002889compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002890 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002891{
2892 PyCodeObject *co = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002893 expr_ty outermost_iter;
2894
2895 outermost_iter = ((comprehension_ty)
2896 asdl_seq_GET(generators, 0))->iter;
2897
2898 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2899 goto error;
2900
2901 if (type != COMP_GENEXP) {
Guido van Rossum992d4a32007-07-11 13:09:30 +00002902 int op;
Guido van Rossum992d4a32007-07-11 13:09:30 +00002903 switch (type) {
2904 case COMP_LISTCOMP:
2905 op = BUILD_LIST;
2906 break;
2907 case COMP_SETCOMP:
2908 op = BUILD_SET;
2909 break;
2910 case COMP_DICTCOMP:
2911 op = BUILD_MAP;
2912 break;
2913 default:
2914 PyErr_Format(PyExc_SystemError,
2915 "unknown comprehension type %d", type);
2916 goto error_in_scope;
2917 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002918
Guido van Rossum992d4a32007-07-11 13:09:30 +00002919 ADDOP_I(c, op, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002920 }
2921
Antoine Pitrouf289ae62008-12-18 11:06:25 +00002922 if (!compiler_comprehension_generator(c, generators, 0, elt,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002923 val, type))
Nick Coghlan650f0d02007-04-15 12:05:43 +00002924 goto error_in_scope;
2925
2926 if (type != COMP_GENEXP) {
2927 ADDOP(c, RETURN_VALUE);
2928 }
2929
2930 co = assemble(c, 1);
2931 compiler_exit_scope(c);
2932 if (co == NULL)
2933 goto error;
2934
2935 if (!compiler_make_closure(c, co, 0))
2936 goto error;
2937 Py_DECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002938
2939 VISIT(c, expr, outermost_iter);
2940 ADDOP(c, GET_ITER);
2941 ADDOP_I(c, CALL_FUNCTION, 1);
2942 return 1;
2943error_in_scope:
2944 compiler_exit_scope(c);
2945error:
2946 Py_XDECREF(co);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002947 return 0;
2948}
2949
2950static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951compiler_genexp(struct compiler *c, expr_ty e)
2952{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002953 static identifier name;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002954 if (!name) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +00002955 name = PyUnicode_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002956 if (!name)
2957 return 0;
2958 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002959 assert(e->kind == GeneratorExp_kind);
2960 return compiler_comprehension(c, e, COMP_GENEXP, name,
2961 e->v.GeneratorExp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002962 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963}
2964
2965static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002966compiler_listcomp(struct compiler *c, expr_ty e)
2967{
2968 static identifier name;
2969 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002970 name = PyUnicode_FromString("<listcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002971 if (!name)
2972 return 0;
2973 }
2974 assert(e->kind == ListComp_kind);
2975 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2976 e->v.ListComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002977 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002978}
2979
2980static int
2981compiler_setcomp(struct compiler *c, expr_ty e)
2982{
2983 static identifier name;
2984 if (!name) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002985 name = PyUnicode_FromString("<setcomp>");
Nick Coghlan650f0d02007-04-15 12:05:43 +00002986 if (!name)
2987 return 0;
2988 }
2989 assert(e->kind == SetComp_kind);
2990 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2991 e->v.SetComp.generators,
Guido van Rossum992d4a32007-07-11 13:09:30 +00002992 e->v.SetComp.elt, NULL);
2993}
2994
2995
2996static int
2997compiler_dictcomp(struct compiler *c, expr_ty e)
2998{
2999 static identifier name;
3000 if (!name) {
Neal Norwitz41103bf2007-08-24 23:12:06 +00003001 name = PyUnicode_FromString("<dictcomp>");
Guido van Rossum992d4a32007-07-11 13:09:30 +00003002 if (!name)
3003 return 0;
3004 }
3005 assert(e->kind == DictComp_kind);
3006 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3007 e->v.DictComp.generators,
3008 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003009}
3010
3011
3012static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013compiler_visit_keyword(struct compiler *c, keyword_ty k)
3014{
3015 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3016 VISIT(c, expr, k->value);
3017 return 1;
3018}
3019
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003020/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 whether they are true or false.
3022
3023 Return values: 1 for true, 0 for false, -1 for non-constant.
3024 */
3025
3026static int
3027expr_constant(expr_ty e)
3028{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003029 char *id;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00003031 case Ellipsis_kind:
3032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 case Num_kind:
3034 return PyObject_IsTrue(e->v.Num.n);
3035 case Str_kind:
3036 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003037 case Name_kind:
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003038 /* optimize away names that can't be reassigned */
Christian Heimes72b710a2008-05-26 13:28:38 +00003039 id = PyBytes_AS_STRING(
Guido van Rossumbdbb3952007-06-14 00:28:01 +00003040 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003041 if (strcmp(id, "True") == 0) return 1;
3042 if (strcmp(id, "False") == 0) return 0;
3043 if (strcmp(id, "None") == 0) return 0;
3044 if (strcmp(id, "__debug__") == 0)
3045 return ! Py_OptimizeFlag;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003046 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 default:
3048 return -1;
3049 }
3050}
3051
Guido van Rossumc2e20742006-02-27 22:32:47 +00003052/*
3053 Implements the with statement from PEP 343.
3054
3055 The semantics outlined in that PEP are as follows:
3056
3057 with EXPR as VAR:
3058 BLOCK
3059
3060 It is implemented roughly as:
3061
Thomas Wouters477c8d52006-05-27 19:21:47 +00003062 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003063 exit = context.__exit__ # not calling it
3064 value = context.__enter__()
3065 try:
3066 VAR = value # if VAR present in the syntax
3067 BLOCK
3068 finally:
3069 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003073 exit(*exc)
3074 */
3075static int
3076compiler_with(struct compiler *c, stmt_ty s)
3077{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003078 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079 basicblock *block, *finally;
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003080 identifier tmpvalue = NULL, tmpexit = NULL;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081
3082 assert(s->kind == With_kind);
3083
Guido van Rossumc2e20742006-02-27 22:32:47 +00003084 if (!enter_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003085 enter_attr = PyUnicode_InternFromString("__enter__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003086 if (!enter_attr)
3087 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003088 }
3089 if (!exit_attr) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003090 exit_attr = PyUnicode_InternFromString("__exit__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003091 if (!exit_attr)
3092 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003093 }
3094
3095 block = compiler_new_block(c);
3096 finally = compiler_new_block(c);
3097 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003098 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003099
Guido van Rossumc2e20742006-02-27 22:32:47 +00003100 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003101 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003102 We need to do this rather than preserving it on the stack
3103 because SETUP_FINALLY remembers the stack level.
3104 We need to do the assignment *inside* the try/finally
3105 so that context.__exit__() is called when the assignment
3106 fails. But we need to call context.__enter__() *before*
3107 the try/finally so that if it fails we won't call
3108 context.__exit__().
3109 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003110 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003111 if (tmpvalue == NULL)
3112 return 0;
3113 PyArena_AddPyObject(c->c_arena, tmpvalue);
3114 }
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003115 tmpexit = compiler_new_tmpname(c);
3116 if (tmpexit == NULL)
3117 return 0;
3118 PyArena_AddPyObject(c->c_arena, tmpexit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003119
Thomas Wouters477c8d52006-05-27 19:21:47 +00003120 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003121 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003122
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003123 /* Squirrel away context.__exit__ by stuffing it under context */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003124 ADDOP(c, DUP_TOP);
3125 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003126 if (!compiler_nameop(c, tmpexit, Store))
3127 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003128
3129 /* Call context.__enter__() */
3130 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3131 ADDOP_I(c, CALL_FUNCTION, 0);
3132
3133 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 /* Store it in tmpvalue */
3135 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003136 return 0;
3137 }
3138 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003139 /* Discard result from context.__enter__() */
3140 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003141 }
3142
3143 /* Start the try block */
3144 ADDOP_JREL(c, SETUP_FINALLY, finally);
3145
3146 compiler_use_next_block(c, block);
3147 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003149 }
3150
3151 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003152 /* Bind saved result of context.__enter__() to VAR */
3153 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003154 !compiler_nameop(c, tmpvalue, Del))
3155 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003157 }
3158
3159 /* BLOCK code */
3160 VISIT_SEQ(c, stmt, s->v.With.body);
3161
3162 /* End of try block; start the finally block */
3163 ADDOP(c, POP_BLOCK);
3164 compiler_pop_fblock(c, FINALLY_TRY, block);
3165
3166 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3167 compiler_use_next_block(c, finally);
3168 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003170
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003171 /* Finally block starts; context.__exit__ is on the stack under
3172 the exception or return information. Just issue our magic
3173 opcode. */
Benjamin Petersoneec3d712008-06-11 15:59:43 +00003174 if (!compiler_nameop(c, tmpexit, Load) ||
3175 !compiler_nameop(c, tmpexit, Del))
3176 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003177 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003178
3179 /* Finally block ends. */
3180 ADDOP(c, END_FINALLY);
3181 compiler_pop_fblock(c, FINALLY_END, finally);
3182 return 1;
3183}
3184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185static int
3186compiler_visit_expr(struct compiler *c, expr_ty e)
3187{
3188 int i, n;
3189
Thomas Wouters89f507f2006-12-13 04:49:30 +00003190 /* If expr e has a different line number than the last expr/stmt,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003191 set a new line number for the next instruction.
3192 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 if (e->lineno > c->u->u_lineno) {
3194 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003195 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 }
3197 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003200 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201 VISIT(c, expr, e->v.BinOp.left);
3202 VISIT(c, expr, e->v.BinOp.right);
3203 ADDOP(c, binop(c, e->v.BinOp.op));
3204 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 VISIT(c, expr, e->v.UnaryOp.operand);
3207 ADDOP(c, unaryop(e->v.UnaryOp.op));
3208 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003211 case IfExp_kind:
3212 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003213 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214 n = asdl_seq_LEN(e->v.Dict.values);
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003215 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216 for (i = 0; i < n; 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.values, i));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003219 VISIT(c, expr,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003220 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Christian Heimes99170a52007-12-19 02:07:34 +00003221 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 }
3223 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003224 case Set_kind:
3225 n = asdl_seq_LEN(e->v.Set.elts);
3226 VISIT_SEQ(c, expr, e->v.Set.elts);
3227 ADDOP_I(c, BUILD_SET, n);
3228 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003229 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 return compiler_genexp(c, e);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003231 case ListComp_kind:
3232 return compiler_listcomp(c, e);
3233 case SetComp_kind:
3234 return compiler_setcomp(c, e);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003235 case DictComp_kind:
3236 return compiler_dictcomp(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237 case Yield_kind:
3238 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003239 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240 if (e->v.Yield.value) {
3241 VISIT(c, expr, e->v.Yield.value);
3242 }
3243 else {
3244 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3245 }
3246 ADDOP(c, YIELD_VALUE);
3247 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003248 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003250 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003252 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3254 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003255 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3257 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003258 case Bytes_kind:
3259 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
Thomas Wouters00e41de2007-02-23 19:56:57 +00003260 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003261 case Ellipsis_kind:
3262 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3263 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003265 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266 if (e->v.Attribute.ctx != AugStore)
3267 VISIT(c, expr, e->v.Attribute.value);
3268 switch (e->v.Attribute.ctx) {
3269 case AugLoad:
3270 ADDOP(c, DUP_TOP);
3271 /* Fall through to load */
3272 case Load:
3273 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3274 break;
3275 case AugStore:
3276 ADDOP(c, ROT_TWO);
3277 /* Fall through to save */
3278 case Store:
3279 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3280 break;
3281 case Del:
3282 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3283 break;
3284 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003285 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003286 PyErr_SetString(PyExc_SystemError,
3287 "param invalid in attribute expression");
3288 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289 }
3290 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003291 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 switch (e->v.Subscript.ctx) {
3293 case AugLoad:
3294 VISIT(c, expr, e->v.Subscript.value);
3295 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3296 break;
3297 case Load:
3298 VISIT(c, expr, e->v.Subscript.value);
3299 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3300 break;
3301 case AugStore:
3302 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3303 break;
3304 case Store:
3305 VISIT(c, expr, e->v.Subscript.value);
3306 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3307 break;
3308 case Del:
3309 VISIT(c, expr, e->v.Subscript.value);
3310 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3311 break;
3312 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003313 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003314 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003315 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003316 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317 }
3318 break;
Guido van Rossum0368b722007-05-11 16:50:42 +00003319 case Starred_kind:
3320 switch (e->v.Starred.ctx) {
3321 case Store:
3322 /* In all legitimate cases, the Starred node was already replaced
3323 * by compiler_list/compiler_tuple. XXX: is that okay? */
3324 return compiler_error(c,
3325 "starred assignment target must be in a list or tuple");
3326 default:
3327 return compiler_error(c,
3328 "can use starred expression only as assignment target");
3329 }
3330 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003331 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3333 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003334 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003336 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337 return compiler_tuple(c, e);
3338 }
3339 return 1;
3340}
3341
3342static int
3343compiler_augassign(struct compiler *c, stmt_ty s)
3344{
3345 expr_ty e = s->v.AugAssign.target;
3346 expr_ty auge;
3347
3348 assert(s->kind == AugAssign_kind);
3349
3350 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003351 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003353 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003354 if (auge == NULL)
3355 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003356 VISIT(c, expr, auge);
3357 VISIT(c, expr, s->v.AugAssign.value);
3358 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3359 auge->v.Attribute.ctx = AugStore;
3360 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003361 break;
3362 case Subscript_kind:
3363 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003364 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003365 if (auge == NULL)
3366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003367 VISIT(c, expr, auge);
3368 VISIT(c, expr, s->v.AugAssign.value);
3369 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003370 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003372 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003373 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003374 if (!compiler_nameop(c, e->v.Name.id, Load))
3375 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003376 VISIT(c, expr, s->v.AugAssign.value);
3377 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3378 return compiler_nameop(c, e->v.Name.id, Store);
3379 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003380 PyErr_Format(PyExc_SystemError,
3381 "invalid node type (%d) for augmented assignment",
3382 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003383 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 }
3385 return 1;
3386}
3387
3388static int
3389compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3390{
3391 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003392 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3393 PyErr_SetString(PyExc_SystemError,
3394 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003395 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003396 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003397 f = &c->u->u_fblock[c->u->u_nfblocks++];
3398 f->fb_type = t;
3399 f->fb_block = b;
3400 return 1;
3401}
3402
3403static void
3404compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3405{
3406 struct compiler_unit *u = c->u;
3407 assert(u->u_nfblocks > 0);
3408 u->u_nfblocks--;
3409 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3410 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3411}
3412
Thomas Wouters89f507f2006-12-13 04:49:30 +00003413static int
3414compiler_in_loop(struct compiler *c) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003415 int i;
3416 struct compiler_unit *u = c->u;
3417 for (i = 0; i < u->u_nfblocks; ++i) {
3418 if (u->u_fblock[i].fb_type == LOOP)
3419 return 1;
3420 }
3421 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003422}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423/* Raises a SyntaxError and returns 0.
3424 If something goes wrong, a different exception may be raised.
3425*/
3426
3427static int
3428compiler_error(struct compiler *c, const char *errstr)
3429{
3430 PyObject *loc;
3431 PyObject *u = NULL, *v = NULL;
3432
3433 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3434 if (!loc) {
3435 Py_INCREF(Py_None);
3436 loc = Py_None;
3437 }
3438 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3439 Py_None, loc);
3440 if (!u)
3441 goto exit;
3442 v = Py_BuildValue("(zO)", errstr, u);
3443 if (!v)
3444 goto exit;
3445 PyErr_SetObject(PyExc_SyntaxError, v);
3446 exit:
3447 Py_DECREF(loc);
3448 Py_XDECREF(u);
3449 Py_XDECREF(v);
3450 return 0;
3451}
3452
3453static int
3454compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003459 /* XXX this code is duplicated */
3460 switch (ctx) {
3461 case AugLoad: /* fall through to Load */
3462 case Load: op = BINARY_SUBSCR; break;
3463 case AugStore:/* fall through to Store */
3464 case Store: op = STORE_SUBSCR; break;
3465 case Del: op = DELETE_SUBSCR; break;
3466 case Param:
3467 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003468 "invalid %s kind %d in subscript\n",
3469 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 return 0;
3471 }
3472 if (ctx == AugLoad) {
3473 ADDOP_I(c, DUP_TOPX, 2);
3474 }
3475 else if (ctx == AugStore) {
3476 ADDOP(c, ROT_THREE);
3477 }
3478 ADDOP(c, op);
3479 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480}
3481
3482static int
3483compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3484{
3485 int n = 2;
3486 assert(s->kind == Slice_kind);
3487
3488 /* only handles the cases where BUILD_SLICE is emitted */
3489 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003490 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491 }
3492 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003497 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498 }
3499 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003500 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003501 }
3502
3503 if (s->v.Slice.step) {
3504 n++;
3505 VISIT(c, expr, s->v.Slice.step);
3506 }
3507 ADDOP_I(c, BUILD_SLICE, n);
3508 return 1;
3509}
3510
3511static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3513 expr_context_ty ctx)
3514{
3515 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 case Slice_kind:
3517 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518 case Index_kind:
3519 VISIT(c, expr, s->v.Index.value);
3520 break;
3521 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003522 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003523 PyErr_SetString(PyExc_SystemError,
3524 "extended slice invalid in nested slice");
3525 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526 }
3527 return 1;
3528}
3529
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530static int
3531compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3532{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003533 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003535 case Index_kind:
3536 kindname = "index";
3537 if (ctx != AugStore) {
3538 VISIT(c, expr, s->v.Index.value);
3539 }
3540 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003542 kindname = "slice";
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003543 if (ctx != AugStore) {
3544 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 return 0;
3546 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003547 break;
3548 case ExtSlice_kind:
3549 kindname = "extended slice";
3550 if (ctx != AugStore) {
3551 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3552 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003553 slice_ty sub = (slice_ty)asdl_seq_GET(
Guido van Rossumd8faa362007-04-27 19:54:29 +00003554 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003555 if (!compiler_visit_nested_slice(c, sub, ctx))
3556 return 0;
3557 }
3558 ADDOP_I(c, BUILD_TUPLE, n);
3559 }
3560 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003561 default:
3562 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003563 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003564 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003566 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567}
3568
Thomas Wouters89f507f2006-12-13 04:49:30 +00003569/* End of the compiler section, beginning of the assembler section */
3570
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571/* do depth-first search of basic block graph, starting with block.
3572 post records the block indices in post-order.
3573
3574 XXX must handle implicit jumps from one block to next
3575*/
3576
Thomas Wouters89f507f2006-12-13 04:49:30 +00003577struct assembler {
3578 PyObject *a_bytecode; /* string containing bytecode */
3579 int a_offset; /* offset into bytecode */
3580 int a_nblocks; /* number of reachable blocks */
3581 basicblock **a_postorder; /* list of blocks in dfs postorder */
3582 PyObject *a_lnotab; /* string containing lnotab */
3583 int a_lnotab_off; /* offset into lnotab */
3584 int a_lineno; /* last lineno of emitted instruction */
3585 int a_lineno_off; /* bytecode offset of last lineno */
3586};
3587
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588static void
3589dfs(struct compiler *c, basicblock *b, struct assembler *a)
3590{
3591 int i;
3592 struct instr *instr = NULL;
3593
3594 if (b->b_seen)
3595 return;
3596 b->b_seen = 1;
3597 if (b->b_next != NULL)
3598 dfs(c, b->b_next, a);
3599 for (i = 0; i < b->b_iused; i++) {
3600 instr = &b->b_instr[i];
3601 if (instr->i_jrel || instr->i_jabs)
3602 dfs(c, instr->i_target, a);
3603 }
3604 a->a_postorder[a->a_nblocks++] = b;
3605}
3606
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003607static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3609{
3610 int i;
3611 struct instr *instr;
3612 if (b->b_seen || b->b_startdepth >= depth)
3613 return maxdepth;
3614 b->b_seen = 1;
3615 b->b_startdepth = depth;
3616 for (i = 0; i < b->b_iused; i++) {
3617 instr = &b->b_instr[i];
3618 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3619 if (depth > maxdepth)
3620 maxdepth = depth;
3621 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3622 if (instr->i_jrel || instr->i_jabs) {
3623 maxdepth = stackdepth_walk(c, instr->i_target,
3624 depth, maxdepth);
3625 if (instr->i_opcode == JUMP_ABSOLUTE ||
3626 instr->i_opcode == JUMP_FORWARD) {
3627 goto out; /* remaining code is dead */
3628 }
3629 }
3630 }
3631 if (b->b_next)
3632 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3633out:
3634 b->b_seen = 0;
3635 return maxdepth;
3636}
3637
3638/* Find the flow path that needs the largest stack. We assume that
3639 * cycles in the flow graph have no net effect on the stack depth.
3640 */
3641static int
3642stackdepth(struct compiler *c)
3643{
3644 basicblock *b, *entryblock;
3645 entryblock = NULL;
3646 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3647 b->b_seen = 0;
3648 b->b_startdepth = INT_MIN;
3649 entryblock = b;
3650 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003651 if (!entryblock)
3652 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 return stackdepth_walk(c, entryblock, 0, 0);
3654}
3655
3656static int
3657assemble_init(struct assembler *a, int nblocks, int firstlineno)
3658{
3659 memset(a, 0, sizeof(struct assembler));
3660 a->a_lineno = firstlineno;
Christian Heimes72b710a2008-05-26 13:28:38 +00003661 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662 if (!a->a_bytecode)
3663 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003664 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003665 if (!a->a_lnotab)
3666 return 0;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003667 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3668 PyErr_NoMemory();
3669 return 0;
3670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003672 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003673 if (!a->a_postorder) {
3674 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003676 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677 return 1;
3678}
3679
3680static void
3681assemble_free(struct assembler *a)
3682{
3683 Py_XDECREF(a->a_bytecode);
3684 Py_XDECREF(a->a_lnotab);
3685 if (a->a_postorder)
3686 PyObject_Free(a->a_postorder);
3687}
3688
3689/* Return the size of a basic block in bytes. */
3690
3691static int
3692instrsize(struct instr *instr)
3693{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003694 if (!instr->i_hasarg)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003695 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003696 if (instr->i_oparg > 0xffff)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00003697 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3698 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003699}
3700
3701static int
3702blocksize(basicblock *b)
3703{
3704 int i;
3705 int size = 0;
3706
3707 for (i = 0; i < b->b_iused; i++)
3708 size += instrsize(&b->b_instr[i]);
3709 return size;
3710}
3711
3712/* All about a_lnotab.
3713
3714c_lnotab is an array of unsigned bytes disguised as a Python string.
3715It is used to map bytecode offsets to source code line #s (when needed
3716for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003717
Tim Peters2a7f3842001-06-09 09:26:21 +00003718The array is conceptually a list of
3719 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003720pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003721
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003722 byte code offset source code line number
3723 0 1
3724 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003725 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003726 350 307
3727 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003728
3729The first trick is that these numbers aren't stored, only the increments
3730from one row to the next (this doesn't really work, but it's a start):
3731
3732 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3733
3734The second trick is that an unsigned byte can't hold negative values, or
3735values larger than 255, so (a) there's a deep assumption that byte code
3736offsets and their corresponding line #s both increase monotonically, and (b)
3737if at least one column jumps by more than 255 from one row to the next, more
3738than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003739from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003740part. A user of c_lnotab desiring to find the source line number
3741corresponding to a bytecode address A should do something like this
3742
3743 lineno = addr = 0
3744 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003745 addr += addr_incr
3746 if addr > A:
3747 return lineno
3748 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003749
3750In order for this to work, when the addr field increments by more than 255,
3751the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003752increment is < 256. So, in the example above, assemble_lnotab (it used
3753to be called com_set_lineno) should not (as was actually done until 2.2)
3754expand 300, 300 to 255, 255, 45, 45,
Guido van Rossumd8faa362007-04-27 19:54:29 +00003755 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003756*/
3757
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003758static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003760{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 int d_bytecode, d_lineno;
3762 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003763 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764
3765 d_bytecode = a->a_offset - a->a_lineno_off;
3766 d_lineno = i->i_lineno - a->a_lineno;
3767
3768 assert(d_bytecode >= 0);
3769 assert(d_lineno >= 0);
3770
Christian Heimes2202f872008-02-06 14:31:34 +00003771 if(d_bytecode == 0 && d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003772 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003773
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003775 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003777 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003779 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003781 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003782 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003783 else {
3784 PyErr_NoMemory();
3785 return 0;
3786 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003787 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003789 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003790 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003791 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003792 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793 *lnotab++ = 255;
3794 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003795 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 d_bytecode -= ncodes * 255;
3797 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003798 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799 assert(d_bytecode <= 255);
3800 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003801 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802 nbytes = a->a_lnotab_off + 2 * ncodes;
Christian Heimes72b710a2008-05-26 13:28:38 +00003803 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 if (nbytes >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003805 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806 len = nbytes;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003807 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808 len *= 2;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003809 else {
3810 PyErr_NoMemory();
3811 return 0;
3812 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003813 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003815 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003816 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003817 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003819 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003821 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003823 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003824 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 d_lineno -= ncodes * 255;
3826 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003827 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003828
Christian Heimes72b710a2008-05-26 13:28:38 +00003829 len = PyBytes_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830 if (a->a_lnotab_off + 2 >= len) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003831 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003832 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003833 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003834 lnotab = (unsigned char *)
Christian Heimes72b710a2008-05-26 13:28:38 +00003835 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003837 a->a_lnotab_off += 2;
3838 if (d_bytecode) {
3839 *lnotab++ = d_bytecode;
3840 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003841 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003842 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 *lnotab++ = 0;
3844 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003845 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846 a->a_lineno = i->i_lineno;
3847 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003848 return 1;
3849}
3850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851/* assemble_emit()
3852 Extend the bytecode with a new instruction.
3853 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003854*/
3855
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003856static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003858{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003859 int size, arg = 0, ext = 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003860 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 char *code;
3862
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003863 size = instrsize(i);
3864 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003866 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003867 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003869 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 if (a->a_offset + size >= len) {
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00003871 if (len > PY_SSIZE_T_MAX / 2)
3872 return 0;
Christian Heimes72b710a2008-05-26 13:28:38 +00003873 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003874 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003875 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003876 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003878 if (size == 6) {
3879 assert(i->i_hasarg);
3880 *code++ = (char)EXTENDED_ARG;
3881 *code++ = ext & 0xff;
3882 *code++ = ext >> 8;
3883 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003884 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003886 if (i->i_hasarg) {
3887 assert(size == 3 || size == 6);
3888 *code++ = arg & 0xff;
3889 *code++ = arg >> 8;
3890 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003892}
3893
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003894static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003896{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003898 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003899 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 /* Compute the size of each block and fixup jump args.
3902 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003903start:
3904 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003906 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003907 bsize = blocksize(b);
3908 b->b_offset = totsize;
3909 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003910 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003911 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003912 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3913 bsize = b->b_offset;
3914 for (i = 0; i < b->b_iused; i++) {
3915 struct instr *instr = &b->b_instr[i];
3916 /* Relative jumps are computed relative to
3917 the instruction pointer after fetching
3918 the jump instruction.
3919 */
3920 bsize += instrsize(instr);
3921 if (instr->i_jabs)
3922 instr->i_oparg = instr->i_target->b_offset;
3923 else if (instr->i_jrel) {
3924 int delta = instr->i_target->b_offset - bsize;
3925 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003926 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003927 else
3928 continue;
3929 if (instr->i_oparg > 0xffff)
3930 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003931 }
3932 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003933
3934 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003935 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003936 with a better solution.
3937
3938 In the meantime, should the goto be dropped in favor
3939 of a loop?
3940
3941 The issue is that in the first loop blocksize() is called
3942 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003943 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003944 i_oparg is calculated in the second loop above.
3945
3946 So we loop until we stop seeing new EXTENDED_ARGs.
3947 The only EXTENDED_ARGs that could be popping up are
3948 ones in jump instructions. So this should converge
3949 fairly quickly.
3950 */
3951 if (last_extended_arg_count != extended_arg_count) {
3952 last_extended_arg_count = extended_arg_count;
3953 goto start;
3954 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003955}
3956
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003957static PyObject *
3958dict_keys_inorder(PyObject *dict, int offset)
3959{
3960 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003961 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003962
3963 tuple = PyTuple_New(size);
3964 if (tuple == NULL)
3965 return NULL;
3966 while (PyDict_Next(dict, &pos, &k, &v)) {
Christian Heimes217cfd12007-12-02 14:31:20 +00003967 i = PyLong_AS_LONG(v);
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003968 /* The keys of the dictionary are tuples. (see compiler_add_o)
3969 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003970 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003971 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003972 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003973 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003974 PyTuple_SET_ITEM(tuple, i - offset, k);
3975 }
3976 return tuple;
3977}
3978
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003979static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003981{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003982 PySTEntryObject *ste = c->u->u_ste;
3983 int flags = 0, n;
3984 if (ste->ste_type != ModuleBlock)
3985 flags |= CO_NEWLOCALS;
3986 if (ste->ste_type == FunctionBlock) {
3987 if (!ste->ste_unoptimized)
3988 flags |= CO_OPTIMIZED;
3989 if (ste->ste_nested)
3990 flags |= CO_NESTED;
3991 if (ste->ste_generator)
3992 flags |= CO_GENERATOR;
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00003993 if (ste->ste_varargs)
3994 flags |= CO_VARARGS;
3995 if (ste->ste_varkeywords)
3996 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003997 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003998
3999 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004000 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004001
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004002 n = PyDict_Size(c->u->u_freevars);
4003 if (n < 0)
4004 return -1;
4005 if (n == 0) {
4006 n = PyDict_Size(c->u->u_cellvars);
4007 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004008 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009 if (n == 0) {
4010 flags |= CO_NOFREE;
4011 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004012 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004013
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004014 return flags;
4015}
4016
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017static PyCodeObject *
4018makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004019{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020 PyObject *tmp;
4021 PyCodeObject *co = NULL;
4022 PyObject *consts = NULL;
4023 PyObject *names = NULL;
4024 PyObject *varnames = NULL;
4025 PyObject *filename = NULL;
4026 PyObject *name = NULL;
4027 PyObject *freevars = NULL;
4028 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004029 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004031
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004032 tmp = dict_keys_inorder(c->u->u_consts, 0);
4033 if (!tmp)
4034 goto error;
4035 consts = PySequence_List(tmp); /* optimize_code requires a list */
4036 Py_DECREF(tmp);
4037
4038 names = dict_keys_inorder(c->u->u_names, 0);
4039 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4040 if (!consts || !names || !varnames)
4041 goto error;
4042
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004043 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4044 if (!cellvars)
4045 goto error;
4046 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4047 if (!freevars)
4048 goto error;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00004049 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004050 if (!filename)
4051 goto error;
4052
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004053 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004054 flags = compute_code_flags(c);
4055 if (flags < 0)
4056 goto error;
4057
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004058 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004059 if (!bytecode)
4060 goto error;
4061
4062 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4063 if (!tmp)
4064 goto error;
4065 Py_DECREF(consts);
4066 consts = tmp;
4067
Guido van Rossum4f72a782006-10-27 23:31:49 +00004068 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4069 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070 bytecode, consts, names, varnames,
4071 freevars, cellvars,
4072 filename, c->u->u_name,
4073 c->u->u_firstlineno,
4074 a->a_lnotab);
4075 error:
4076 Py_XDECREF(consts);
4077 Py_XDECREF(names);
4078 Py_XDECREF(varnames);
4079 Py_XDECREF(filename);
4080 Py_XDECREF(name);
4081 Py_XDECREF(freevars);
4082 Py_XDECREF(cellvars);
4083 Py_XDECREF(bytecode);
4084 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004085}
4086
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004087
4088/* For debugging purposes only */
4089#if 0
4090static void
4091dump_instr(const struct instr *i)
4092{
4093 const char *jrel = i->i_jrel ? "jrel " : "";
4094 const char *jabs = i->i_jabs ? "jabs " : "";
4095 char arg[128];
4096
4097 *arg = '\0';
4098 if (i->i_hasarg)
4099 sprintf(arg, "arg: %d ", i->i_oparg);
4100
4101 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4102 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4103}
4104
4105static void
4106dump_basicblock(const basicblock *b)
4107{
4108 const char *seen = b->b_seen ? "seen " : "";
4109 const char *b_return = b->b_return ? "return " : "";
4110 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4111 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4112 if (b->b_instr) {
4113 int i;
4114 for (i = 0; i < b->b_iused; i++) {
4115 fprintf(stderr, " [%02d] ", i);
4116 dump_instr(b->b_instr + i);
4117 }
4118 }
4119}
4120#endif
4121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122static PyCodeObject *
4123assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004124{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004125 basicblock *b, *entryblock;
4126 struct assembler a;
4127 int i, j, nblocks;
4128 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004129
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130 /* Make sure every block that falls off the end returns None.
4131 XXX NEXT_BLOCK() isn't quite right, because if the last
4132 block ends with a jump or return b_next shouldn't set.
4133 */
4134 if (!c->u->u_curblock->b_return) {
4135 NEXT_BLOCK(c);
4136 if (addNone)
4137 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4138 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004139 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141 nblocks = 0;
4142 entryblock = NULL;
4143 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4144 nblocks++;
4145 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004146 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004147
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004148 /* Set firstlineno if it wasn't explicitly set. */
4149 if (!c->u->u_firstlineno) {
4150 if (entryblock && entryblock->b_instr)
4151 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4152 else
4153 c->u->u_firstlineno = 1;
4154 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004155 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4156 goto error;
4157 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004158
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004160 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 /* Emit code in reverse postorder from dfs. */
4163 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004164 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165 for (j = 0; j < b->b_iused; j++)
4166 if (!assemble_emit(&a, &b->b_instr[j]))
4167 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004168 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004169
Christian Heimes72b710a2008-05-26 13:28:38 +00004170 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004171 goto error;
Christian Heimes72b710a2008-05-26 13:28:38 +00004172 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004174
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004175 co = makecode(c, &a);
4176 error:
4177 assemble_free(&a);
4178 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004179}