blob: 83c9e0211ed8fcf0372363a5d2dc504e18d57a1e [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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
50 unsigned i_hasarg : 1;
51 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. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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. */
72 unsigned b_seen : 1;
73 /* b_return is true if a RETURN_VALUE opcode is inserted. */
74 unsigned b_return : 1;
75 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
78 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 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 enum fblocktype fb_type;
92 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000093};
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 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 PyObject *u_name;
102 /* The following fields are dicts that map objects to
103 the index of them in co_XXX. The index is used as
104 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 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 int u_argcount; /* number of arguments for block */
115 int u_kwonlyargcount; /* number of keyword only arguments for block */
116 /* Pointer to the most recently allocated block. By following b_list
117 members, you can reach all early allocated blocks. */
118 basicblock *u_blocks;
119 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 int u_nfblocks;
122 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 int u_firstlineno; /* the first lineno of the block */
125 int u_lineno; /* the lineno for the current stmt */
126 int u_lineno_set; /* boolean to indicate whether instr
127 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128};
129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000132The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000134managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135*/
136
137struct compiler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 const char *c_filename;
139 struct symtable *c_st;
140 PyFutureFeatures *c_future; /* pointer to module's __future__ */
141 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 int c_interactive; /* true if in interactive mode */
144 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 struct compiler_unit *u; /* compiler state for current block */
147 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
148 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149};
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151static int compiler_enter_scope(struct compiler *, identifier, void *, int);
152static void compiler_free(struct compiler *);
153static basicblock *compiler_new_block(struct compiler *);
154static int compiler_next_instr(struct compiler *, basicblock *);
155static int compiler_addop(struct compiler *, int);
156static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
157static int compiler_addop_i(struct compiler *, int, int);
158static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159static basicblock *compiler_use_new_block(struct compiler *);
160static int compiler_error(struct compiler *, const char *);
161static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
162
163static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
164static int compiler_visit_stmt(struct compiler *, stmt_ty);
165static int compiler_visit_keyword(struct compiler *, keyword_ty);
166static int compiler_visit_expr(struct compiler *, expr_ty);
167static int compiler_augassign(struct compiler *, stmt_ty);
168static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170
171static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175/* Returns true if there is a loop on the fblock stack. */
176static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177
178static int inplace_binop(struct compiler *, operator_ty);
179static int expr_constant(expr_ty e);
180
Guido van Rossumc2e20742006-02-27 22:32:47 +0000181static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000182static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 asdl_seq *args,
184 asdl_seq *keywords,
185 expr_ty starargs,
186 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static PyCodeObject *assemble(struct compiler *, int addNone);
189static PyObject *__doc__;
190
Benjamin Petersonb173f782009-05-05 22:31:58 +0000191#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Name mangling: __private becomes _classname__private.
197 This is independent from how the name is used. */
198 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
199 Py_UNICODE *buffer;
200 size_t nlen, plen;
201 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
202 name == NULL || name[0] != '_' || name[1] != '_') {
203 Py_INCREF(ident);
204 return ident;
205 }
206 p = PyUnicode_AS_UNICODE(privateobj);
207 nlen = Py_UNICODE_strlen(name);
208 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 The only time a name with a dot can occur is when
211 we are compiling an import statement that has a
212 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 TODO(jhylton): Decide whether we want to support
215 mangling of the module name, e.g. __M.X.
216 */
217 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
218 || Py_UNICODE_strchr(name, '.')) {
219 Py_INCREF(ident);
220 return ident; /* Don't mangle __whatever__ */
221 }
222 /* Strip leading underscores from class name */
223 while (*p == '_')
224 p++;
225 if (*p == 0) {
226 Py_INCREF(ident);
227 return ident; /* Don't mangle if class is just underscores */
228 }
229 plen = Py_UNICODE_strlen(p);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 assert(1 <= PY_SSIZE_T_MAX - nlen);
232 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
235 if (!ident)
236 return 0;
237 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
238 buffer = PyUnicode_AS_UNICODE(ident);
239 buffer[0] = '_';
240 Py_UNICODE_strncpy(buffer+1, p, plen);
241 Py_UNICODE_strcpy(buffer+1+plen, name);
242 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000243}
244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245static int
246compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 c->c_stack = PyList_New(0);
251 if (!c->c_stack)
252 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255}
256
257PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000258PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 struct compiler c;
262 PyCodeObject *co = NULL;
263 PyCompilerFlags local_flags;
264 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (!__doc__) {
267 __doc__ = PyUnicode_InternFromString("__doc__");
268 if (!__doc__)
269 return NULL;
270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (!compiler_init(&c))
273 return NULL;
274 c.c_filename = filename;
275 c.c_arena = arena;
276 c.c_future = PyFuture_FromAST(mod, filename);
277 if (c.c_future == NULL)
278 goto finally;
279 if (!flags) {
280 local_flags.cf_flags = 0;
281 flags = &local_flags;
282 }
283 merged = c.c_future->ff_features | flags->cf_flags;
284 c.c_future->ff_features = merged;
285 flags->cf_flags = merged;
286 c.c_flags = flags;
287 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 c.c_st = PySymtable_Build(mod, filename, c.c_future);
290 if (c.c_st == NULL) {
291 if (!PyErr_Occurred())
292 PyErr_SetString(PyExc_SystemError, "no symtable");
293 goto finally;
294 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297
Thomas Wouters1175c432006-02-27 22:49:54 +0000298 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 compiler_free(&c);
300 assert(co || PyErr_Occurred());
301 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302}
303
304PyCodeObject *
305PyNode_Compile(struct _node *n, const char *filename)
306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 PyCodeObject *co = NULL;
308 mod_ty mod;
309 PyArena *arena = PyArena_New();
310 if (!arena)
311 return NULL;
312 mod = PyAST_FromNode(n, NULL, filename, arena);
313 if (mod)
314 co = PyAST_Compile(mod, filename, NULL, arena);
315 PyArena_Free(arena);
316 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000317}
318
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000319static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 if (c->c_st)
323 PySymtable_Free(c->c_st);
324 if (c->c_future)
325 PyObject_Free(c->c_future);
326 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000327}
328
Guido van Rossum79f25d91997-04-29 20:08:16 +0000329static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000330list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 Py_ssize_t i, n;
333 PyObject *v, *k;
334 PyObject *dict = PyDict_New();
335 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 n = PyList_Size(list);
338 for (i = 0; i < n; i++) {
339 v = PyLong_FromLong(i);
340 if (!v) {
341 Py_DECREF(dict);
342 return NULL;
343 }
344 k = PyList_GET_ITEM(list, i);
345 k = PyTuple_Pack(2, k, k->ob_type);
346 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
347 Py_XDECREF(k);
348 Py_DECREF(v);
349 Py_DECREF(dict);
350 return NULL;
351 }
352 Py_DECREF(k);
353 Py_DECREF(v);
354 }
355 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356}
357
358/* Return new dict containing names from src that match scope(s).
359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000362values are integers, starting at offset and increasing by one for
363each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000364*/
365
366static PyObject *
367dictbytype(PyObject *src, int scope_type, int flag, int offset)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 Py_ssize_t pos = 0, i = offset, scope;
370 PyObject *k, *v, *dest = PyDict_New();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 assert(offset >= 0);
373 if (dest == NULL)
374 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 while (PyDict_Next(src, &pos, &k, &v)) {
377 /* XXX this should probably be a macro in symtable.h */
378 long vi;
379 assert(PyLong_Check(v));
380 vi = PyLong_AS_LONG(v);
381 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (scope == scope_type || vi & flag) {
384 PyObject *tuple, *item = PyLong_FromLong(i);
385 if (item == NULL) {
386 Py_DECREF(dest);
387 return NULL;
388 }
389 i++;
390 tuple = PyTuple_Pack(2, k, k->ob_type);
391 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
392 Py_DECREF(item);
393 Py_DECREF(dest);
394 Py_XDECREF(tuple);
395 return NULL;
396 }
397 Py_DECREF(item);
398 Py_DECREF(tuple);
399 }
400 }
401 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000402}
403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404static void
405compiler_unit_check(struct compiler_unit *u)
406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 basicblock *block;
408 for (block = u->u_blocks; block != NULL; block = block->b_list) {
409 assert((void *)block != (void *)0xcbcbcbcb);
410 assert((void *)block != (void *)0xfbfbfbfb);
411 assert((void *)block != (void *)0xdbdbdbdb);
412 if (block->b_instr != NULL) {
413 assert(block->b_ialloc > 0);
414 assert(block->b_iused > 0);
415 assert(block->b_ialloc >= block->b_iused);
416 }
417 else {
418 assert (block->b_iused == 0);
419 assert (block->b_ialloc == 0);
420 }
421 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422}
423
424static void
425compiler_unit_free(struct compiler_unit *u)
426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 compiler_unit_check(u);
430 b = u->u_blocks;
431 while (b != NULL) {
432 if (b->b_instr)
433 PyObject_Free((void *)b->b_instr);
434 next = b->b_list;
435 PyObject_Free((void *)b);
436 b = next;
437 }
438 Py_CLEAR(u->u_ste);
439 Py_CLEAR(u->u_name);
440 Py_CLEAR(u->u_consts);
441 Py_CLEAR(u->u_names);
442 Py_CLEAR(u->u_varnames);
443 Py_CLEAR(u->u_freevars);
444 Py_CLEAR(u->u_cellvars);
445 Py_CLEAR(u->u_private);
446 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447}
448
449static int
450compiler_enter_scope(struct compiler *c, identifier name, void *key,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
456 struct compiler_unit));
457 if (!u) {
458 PyErr_NoMemory();
459 return 0;
460 }
461 memset(u, 0, sizeof(struct compiler_unit));
462 u->u_argcount = 0;
463 u->u_kwonlyargcount = 0;
464 u->u_ste = PySymtable_Lookup(c->c_st, key);
465 if (!u->u_ste) {
466 compiler_unit_free(u);
467 return 0;
468 }
469 Py_INCREF(name);
470 u->u_name = name;
471 u->u_varnames = list2dict(u->u_ste->ste_varnames);
472 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
473 if (!u->u_varnames || !u->u_cellvars) {
474 compiler_unit_free(u);
475 return 0;
476 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
479 PyDict_Size(u->u_cellvars));
480 if (!u->u_freevars) {
481 compiler_unit_free(u);
482 return 0;
483 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 u->u_blocks = NULL;
486 u->u_nfblocks = 0;
487 u->u_firstlineno = lineno;
488 u->u_lineno = 0;
489 u->u_lineno_set = 0;
490 u->u_consts = PyDict_New();
491 if (!u->u_consts) {
492 compiler_unit_free(u);
493 return 0;
494 }
495 u->u_names = PyDict_New();
496 if (!u->u_names) {
497 compiler_unit_free(u);
498 return 0;
499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Push the old compiler_unit on the stack. */
504 if (c->u) {
505 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
506 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
507 Py_XDECREF(capsule);
508 compiler_unit_free(u);
509 return 0;
510 }
511 Py_DECREF(capsule);
512 u->u_private = c->u->u_private;
513 Py_XINCREF(u->u_private);
514 }
515 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 c->c_nestlevel++;
518 if (compiler_use_new_block(c) == NULL)
519 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000522}
523
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525compiler_exit_scope(struct compiler *c)
526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 int n;
528 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 c->c_nestlevel--;
531 compiler_unit_free(c->u);
532 /* Restore c->u to the parent unit. */
533 n = PyList_GET_SIZE(c->c_stack) - 1;
534 if (n >= 0) {
535 capsule = PyList_GET_ITEM(c->c_stack, n);
536 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
537 assert(c->u);
538 /* we are deleting from a list so this really shouldn't fail */
539 if (PySequence_DelItem(c->c_stack, n) < 0)
540 Py_FatalError("compiler_exit_scope()");
541 compiler_unit_check(c->u);
542 }
543 else
544 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546}
547
548/* Allocate a new block and return a pointer to it.
549 Returns NULL on error.
550*/
551
552static basicblock *
553compiler_new_block(struct compiler *c)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 basicblock *b;
556 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 u = c->u;
559 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
560 if (b == NULL) {
561 PyErr_NoMemory();
562 return NULL;
563 }
564 memset((void *)b, 0, sizeof(basicblock));
565 /* Extend the singly linked list of blocks with new block. */
566 b->b_list = u->u_blocks;
567 u->u_blocks = b;
568 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569}
570
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000571static basicblock *
572compiler_use_new_block(struct compiler *c)
573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 basicblock *block = compiler_new_block(c);
575 if (block == NULL)
576 return NULL;
577 c->u->u_curblock = block;
578 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579}
580
581static basicblock *
582compiler_next_block(struct compiler *c)
583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 basicblock *block = compiler_new_block(c);
585 if (block == NULL)
586 return NULL;
587 c->u->u_curblock->b_next = block;
588 c->u->u_curblock = block;
589 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000590}
591
592static basicblock *
593compiler_use_next_block(struct compiler *c, basicblock *block)
594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 assert(block != NULL);
596 c->u->u_curblock->b_next = block;
597 c->u->u_curblock = block;
598 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599}
600
601/* Returns the offset of the next instruction in the current block's
602 b_instr array. Resizes the b_instr as necessary.
603 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
606static int
607compiler_next_instr(struct compiler *c, basicblock *b)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 assert(b != NULL);
610 if (b->b_instr == NULL) {
611 b->b_instr = (struct instr *)PyObject_Malloc(
612 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
613 if (b->b_instr == NULL) {
614 PyErr_NoMemory();
615 return -1;
616 }
617 b->b_ialloc = DEFAULT_BLOCK_SIZE;
618 memset((char *)b->b_instr, 0,
619 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
620 }
621 else if (b->b_iused == b->b_ialloc) {
622 struct instr *tmp;
623 size_t oldsize, newsize;
624 oldsize = b->b_ialloc * sizeof(struct instr);
625 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (oldsize > (PY_SIZE_MAX >> 1)) {
628 PyErr_NoMemory();
629 return -1;
630 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (newsize == 0) {
633 PyErr_NoMemory();
634 return -1;
635 }
636 b->b_ialloc <<= 1;
637 tmp = (struct instr *)PyObject_Realloc(
638 (void *)b->b_instr, newsize);
639 if (tmp == NULL) {
640 PyErr_NoMemory();
641 return -1;
642 }
643 b->b_instr = tmp;
644 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
645 }
646 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647}
648
Christian Heimes2202f872008-02-06 14:31:34 +0000649/* Set the i_lineno member of the instruction at offset off if the
650 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000651 already been set. If it has been set, the call has no effect.
652
Christian Heimes2202f872008-02-06 14:31:34 +0000653 The line number is reset in the following cases:
654 - when entering a new scope
655 - on each statement
656 - on each expression that start a new line
657 - before the "except" clause
658 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000660
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000661static void
662compiler_set_lineno(struct compiler *c, int off)
663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 basicblock *b;
665 if (c->u->u_lineno_set)
666 return;
667 c->u->u_lineno_set = 1;
668 b = c->u->u_curblock;
669 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
672static int
673opcode_stack_effect(int opcode, int oparg)
674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 switch (opcode) {
676 case POP_TOP:
677 return -1;
678 case ROT_TWO:
679 case ROT_THREE:
680 return 0;
681 case DUP_TOP:
682 return 1;
683 case ROT_FOUR:
684 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 case UNARY_POSITIVE:
687 case UNARY_NEGATIVE:
688 case UNARY_NOT:
689 case UNARY_INVERT:
690 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 case SET_ADD:
693 case LIST_APPEND:
694 return -1;
695 case MAP_ADD:
696 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 case BINARY_POWER:
699 case BINARY_MULTIPLY:
700 case BINARY_MODULO:
701 case BINARY_ADD:
702 case BINARY_SUBTRACT:
703 case BINARY_SUBSCR:
704 case BINARY_FLOOR_DIVIDE:
705 case BINARY_TRUE_DIVIDE:
706 return -1;
707 case INPLACE_FLOOR_DIVIDE:
708 case INPLACE_TRUE_DIVIDE:
709 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 case INPLACE_ADD:
712 case INPLACE_SUBTRACT:
713 case INPLACE_MULTIPLY:
714 case INPLACE_MODULO:
715 return -1;
716 case STORE_SUBSCR:
717 return -3;
718 case STORE_MAP:
719 return -2;
720 case DELETE_SUBSCR:
721 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 case BINARY_LSHIFT:
724 case BINARY_RSHIFT:
725 case BINARY_AND:
726 case BINARY_XOR:
727 case BINARY_OR:
728 return -1;
729 case INPLACE_POWER:
730 return -1;
731 case GET_ITER:
732 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 case PRINT_EXPR:
735 return -1;
736 case LOAD_BUILD_CLASS:
737 return 1;
738 case INPLACE_LSHIFT:
739 case INPLACE_RSHIFT:
740 case INPLACE_AND:
741 case INPLACE_XOR:
742 case INPLACE_OR:
743 return -1;
744 case BREAK_LOOP:
745 return 0;
746 case SETUP_WITH:
747 return 7;
748 case WITH_CLEANUP:
749 return -1; /* XXX Sometimes more */
750 case STORE_LOCALS:
751 return -1;
752 case RETURN_VALUE:
753 return -1;
754 case IMPORT_STAR:
755 return -1;
756 case YIELD_VALUE:
757 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 case POP_BLOCK:
760 return 0;
761 case POP_EXCEPT:
762 return 0; /* -3 except if bad bytecode */
763 case END_FINALLY:
764 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 case STORE_NAME:
767 return -1;
768 case DELETE_NAME:
769 return 0;
770 case UNPACK_SEQUENCE:
771 return oparg-1;
772 case UNPACK_EX:
773 return (oparg&0xFF) + (oparg>>8);
774 case FOR_ITER:
775 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 case STORE_ATTR:
778 return -2;
779 case DELETE_ATTR:
780 return -1;
781 case STORE_GLOBAL:
782 return -1;
783 case DELETE_GLOBAL:
784 return 0;
785 case DUP_TOPX:
786 return oparg;
787 case LOAD_CONST:
788 return 1;
789 case LOAD_NAME:
Benjamin Peterson013783c2010-07-20 22:37:19 +0000790 case LOAD_NAME_LOCAL_ONLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return 1;
792 case BUILD_TUPLE:
793 case BUILD_LIST:
794 case BUILD_SET:
795 return 1-oparg;
796 case BUILD_MAP:
797 return 1;
798 case LOAD_ATTR:
799 return 0;
800 case COMPARE_OP:
801 return -1;
802 case IMPORT_NAME:
803 return -1;
804 case IMPORT_FROM:
805 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 case JUMP_FORWARD:
808 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
809 case JUMP_IF_FALSE_OR_POP: /* "" */
810 case JUMP_ABSOLUTE:
811 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 case POP_JUMP_IF_FALSE:
814 case POP_JUMP_IF_TRUE:
815 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 case LOAD_GLOBAL:
818 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 case CONTINUE_LOOP:
821 return 0;
822 case SETUP_LOOP:
823 return 0;
824 case SETUP_EXCEPT:
825 case SETUP_FINALLY:
826 return 6; /* can push 3 values for the new exception
827 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 case LOAD_FAST:
830 return 1;
831 case STORE_FAST:
832 return -1;
833 case DELETE_FAST:
834 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 case RAISE_VARARGS:
837 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000838#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 case CALL_FUNCTION:
840 return -NARGS(oparg);
841 case CALL_FUNCTION_VAR:
842 case CALL_FUNCTION_KW:
843 return -NARGS(oparg)-1;
844 case CALL_FUNCTION_VAR_KW:
845 return -NARGS(oparg)-2;
846 case MAKE_FUNCTION:
847 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
848 case MAKE_CLOSURE:
849 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000850#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 case BUILD_SLICE:
852 if (oparg == 3)
853 return -2;
854 else
855 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 case LOAD_CLOSURE:
858 return 1;
859 case LOAD_DEREF:
860 return 1;
861 case STORE_DEREF:
862 return -1;
863 default:
864 fprintf(stderr, "opcode = %d\n", opcode);
865 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 }
868 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869}
870
871/* Add an opcode with no argument.
872 Returns 0 on failure, 1 on success.
873*/
874
875static int
876compiler_addop(struct compiler *c, int opcode)
877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 basicblock *b;
879 struct instr *i;
880 int off;
881 off = compiler_next_instr(c, c->u->u_curblock);
882 if (off < 0)
883 return 0;
884 b = c->u->u_curblock;
885 i = &b->b_instr[off];
886 i->i_opcode = opcode;
887 i->i_hasarg = 0;
888 if (opcode == RETURN_VALUE)
889 b->b_return = 1;
890 compiler_set_lineno(c, off);
891 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000892}
893
894static int
895compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 PyObject *t, *v;
898 Py_ssize_t arg;
899 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 /* necessary to make sure types aren't coerced (e.g., int and long) */
902 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
903 if (PyFloat_Check(o)) {
904 d = PyFloat_AS_DOUBLE(o);
905 /* all we need is to make the tuple different in either the 0.0
906 * or -0.0 case from all others, just to avoid the "coercion".
907 */
908 if (d == 0.0 && copysign(1.0, d) < 0.0)
909 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
910 else
911 t = PyTuple_Pack(2, o, o->ob_type);
912 }
913 else if (PyComplex_Check(o)) {
914 Py_complex z;
915 int real_negzero, imag_negzero;
916 /* For the complex case we must make complex(x, 0.)
917 different from complex(x, -0.) and complex(0., y)
918 different from complex(-0., y), for any x and y.
919 All four complex zeros must be distinguished.*/
920 z = PyComplex_AsCComplex(o);
921 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
922 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
923 if (real_negzero && imag_negzero) {
924 t = PyTuple_Pack(5, o, o->ob_type,
925 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000926 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 else if (imag_negzero) {
928 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000929 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 else if (real_negzero) {
931 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
932 }
933 else {
934 t = PyTuple_Pack(2, o, o->ob_type);
935 }
936 }
937 else {
938 t = PyTuple_Pack(2, o, o->ob_type);
939 }
940 if (t == NULL)
941 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 v = PyDict_GetItem(dict, t);
944 if (!v) {
945 if (PyErr_Occurred())
946 return -1;
947 arg = PyDict_Size(dict);
948 v = PyLong_FromLong(arg);
949 if (!v) {
950 Py_DECREF(t);
951 return -1;
952 }
953 if (PyDict_SetItem(dict, t, v) < 0) {
954 Py_DECREF(t);
955 Py_DECREF(v);
956 return -1;
957 }
958 Py_DECREF(v);
959 }
960 else
961 arg = PyLong_AsLong(v);
962 Py_DECREF(t);
963 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964}
965
966static int
967compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969{
970 int arg = compiler_add_o(c, dict, o);
971 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000972 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000973 return compiler_addop_i(c, opcode, arg);
974}
975
976static int
977compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979{
980 int arg;
981 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
982 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000983 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000984 arg = compiler_add_o(c, dict, mangled);
985 Py_DECREF(mangled);
986 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000987 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 return compiler_addop_i(c, opcode, arg);
989}
990
991/* Add an opcode with an integer argument.
992 Returns 0 on failure, 1 on success.
993*/
994
995static int
996compiler_addop_i(struct compiler *c, int opcode, int oparg)
997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 struct instr *i;
999 int off;
1000 off = compiler_next_instr(c, c->u->u_curblock);
1001 if (off < 0)
1002 return 0;
1003 i = &c->u->u_curblock->b_instr[off];
1004 i->i_opcode = opcode;
1005 i->i_oparg = oparg;
1006 i->i_hasarg = 1;
1007 compiler_set_lineno(c, off);
1008 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009}
1010
1011static int
1012compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 struct instr *i;
1015 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 assert(b != NULL);
1018 off = compiler_next_instr(c, c->u->u_curblock);
1019 if (off < 0)
1020 return 0;
1021 i = &c->u->u_curblock->b_instr[off];
1022 i->i_opcode = opcode;
1023 i->i_target = b;
1024 i->i_hasarg = 1;
1025 if (absolute)
1026 i->i_jabs = 1;
1027 else
1028 i->i_jrel = 1;
1029 compiler_set_lineno(c, off);
1030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031}
1032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1034 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035 it as the current block. NEXT_BLOCK() also creates an implicit jump
1036 from the current block to the new block.
1037*/
1038
Thomas Wouters89f507f2006-12-13 04:49:30 +00001039/* The returns inside these macros make it impossible to decref objects
1040 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041*/
1042
1043
1044#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (compiler_use_new_block((C)) == NULL) \
1046 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047}
1048
1049#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (compiler_next_block((C)) == NULL) \
1051 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052}
1053
1054#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (!compiler_addop((C), (OP))) \
1056 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057}
1058
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001059#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (!compiler_addop((C), (OP))) { \
1061 compiler_exit_scope(c); \
1062 return 0; \
1063 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001064}
1065
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1068 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069}
1070
1071#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1073 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074}
1075
1076#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 if (!compiler_addop_i((C), (OP), (O))) \
1078 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079}
1080
1081#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (!compiler_addop_j((C), (OP), (O), 1)) \
1083 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001084}
1085
1086#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (!compiler_addop_j((C), (OP), (O), 0)) \
1088 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089}
1090
1091/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1092 the ASDL name to synthesize the name of the C type and the visit function.
1093*/
1094
1095#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (!compiler_visit_ ## TYPE((C), (V))) \
1097 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098}
1099
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001100#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (!compiler_visit_ ## TYPE((C), (V))) { \
1102 compiler_exit_scope(c); \
1103 return 0; \
1104 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001105}
1106
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001107#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 if (!compiler_visit_slice((C), (V), (CTX))) \
1109 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001110}
1111
1112#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 int _i; \
1114 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1115 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1116 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1117 if (!compiler_visit_ ## TYPE((C), elt)) \
1118 return 0; \
1119 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120}
1121
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001122#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 int _i; \
1124 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1125 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1126 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1127 if (!compiler_visit_ ## TYPE((C), elt)) { \
1128 compiler_exit_scope(c); \
1129 return 0; \
1130 } \
1131 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001132}
1133
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134static int
1135compiler_isdocstring(stmt_ty s)
1136{
1137 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001138 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139 return s->v.Expr.value->kind == Str_kind;
1140}
1141
1142/* Compile a sequence of statements, checking for a docstring. */
1143
1144static int
1145compiler_body(struct compiler *c, asdl_seq *stmts)
1146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 int i = 0;
1148 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (!asdl_seq_LEN(stmts))
1151 return 1;
1152 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1153 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1154 /* don't generate docstrings if -OO */
1155 i = 1;
1156 VISIT(c, expr, st->v.Expr.value);
1157 if (!compiler_nameop(c, __doc__, Store))
1158 return 0;
1159 }
1160 for (; i < asdl_seq_LEN(stmts); i++)
1161 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1162 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163}
1164
1165static PyCodeObject *
1166compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 PyCodeObject *co;
1169 int addNone = 1;
1170 static PyObject *module;
1171 if (!module) {
1172 module = PyUnicode_InternFromString("<module>");
1173 if (!module)
1174 return NULL;
1175 }
1176 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1177 if (!compiler_enter_scope(c, module, mod, 0))
1178 return NULL;
1179 switch (mod->kind) {
1180 case Module_kind:
1181 if (!compiler_body(c, mod->v.Module.body)) {
1182 compiler_exit_scope(c);
1183 return 0;
1184 }
1185 break;
1186 case Interactive_kind:
1187 c->c_interactive = 1;
1188 VISIT_SEQ_IN_SCOPE(c, stmt,
1189 mod->v.Interactive.body);
1190 break;
1191 case Expression_kind:
1192 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1193 addNone = 0;
1194 break;
1195 case Suite_kind:
1196 PyErr_SetString(PyExc_SystemError,
1197 "suite should not be possible");
1198 return 0;
1199 default:
1200 PyErr_Format(PyExc_SystemError,
1201 "module kind %d should not be possible",
1202 mod->kind);
1203 return 0;
1204 }
1205 co = assemble(c, addNone);
1206 compiler_exit_scope(c);
1207 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001208}
1209
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210/* The test for LOCAL must come before the test for FREE in order to
1211 handle classes where name is both local and free. The local var is
1212 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001213*/
1214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215static int
1216get_ref_type(struct compiler *c, PyObject *name)
1217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 int scope = PyST_GetScope(c->u->u_ste, name);
1219 if (scope == 0) {
1220 char buf[350];
1221 PyOS_snprintf(buf, sizeof(buf),
1222 "unknown scope for %.100s in %.100s(%s) in %s\n"
1223 "symbols: %s\nlocals: %s\nglobals: %s",
1224 PyBytes_AS_STRING(name),
1225 PyBytes_AS_STRING(c->u->u_name),
1226 PyObject_REPR(c->u->u_ste->ste_id),
1227 c->c_filename,
1228 PyObject_REPR(c->u->u_ste->ste_symbols),
1229 PyObject_REPR(c->u->u_varnames),
1230 PyObject_REPR(c->u->u_names)
1231 );
1232 Py_FatalError(buf);
1233 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
1238static int
1239compiler_lookup_arg(PyObject *dict, PyObject *name)
1240{
1241 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001242 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001244 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001246 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001248 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001249 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252static int
1253compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 int i, free = PyCode_GetNumFree(co);
1256 if (free == 0) {
1257 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1258 ADDOP_I(c, MAKE_FUNCTION, args);
1259 return 1;
1260 }
1261 for (i = 0; i < free; ++i) {
1262 /* Bypass com_addop_varname because it will generate
1263 LOAD_DEREF but LOAD_CLOSURE is needed.
1264 */
1265 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1266 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 /* Special case: If a class contains a method with a
1269 free variable that has the same name as a method,
1270 the name will be considered free *and* local in the
1271 class. It should be handled by the closure, as
1272 well as by the normal name loookup logic.
1273 */
1274 reftype = get_ref_type(c, name);
1275 if (reftype == CELL)
1276 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1277 else /* (reftype == FREE) */
1278 arg = compiler_lookup_arg(c->u->u_freevars, name);
1279 if (arg == -1) {
1280 fprintf(stderr,
1281 "lookup %s in %s %d %d\n"
1282 "freevars of %s: %s\n",
1283 PyObject_REPR(name),
1284 PyBytes_AS_STRING(c->u->u_name),
1285 reftype, arg,
1286 _PyUnicode_AsString(co->co_name),
1287 PyObject_REPR(co->co_freevars));
1288 Py_FatalError("compiler_make_closure()");
1289 }
1290 ADDOP_I(c, LOAD_CLOSURE, arg);
1291 }
1292 ADDOP_I(c, BUILD_TUPLE, free);
1293 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1294 ADDOP_I(c, MAKE_CLOSURE, args);
1295 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296}
1297
1298static int
1299compiler_decorators(struct compiler *c, asdl_seq* decos)
1300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (!decos)
1304 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1307 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1308 }
1309 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
1312static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001313compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 int i, default_count = 0;
1317 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1318 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1319 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1320 if (default_) {
1321 ADDOP_O(c, LOAD_CONST, arg->arg, consts);
1322 if (!compiler_visit_expr(c, default_)) {
1323 return -1;
1324 }
1325 default_count++;
1326 }
1327 }
1328 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001329}
1330
1331static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001332compiler_visit_argannotation(struct compiler *c, identifier id,
1333 expr_ty annotation, PyObject *names)
1334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (annotation) {
1336 VISIT(c, expr, annotation);
1337 if (PyList_Append(names, id))
1338 return -1;
1339 }
1340 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001341}
1342
1343static int
1344compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1345 PyObject *names)
1346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 int i, error;
1348 for (i = 0; i < asdl_seq_LEN(args); i++) {
1349 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1350 error = compiler_visit_argannotation(
1351 c,
1352 arg->arg,
1353 arg->annotation,
1354 names);
1355 if (error)
1356 return error;
1357 }
1358 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001359}
1360
1361static int
1362compiler_visit_annotations(struct compiler *c, arguments_ty args,
1363 expr_ty returns)
1364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 /* Push arg annotations and a list of the argument names. Return the #
1366 of items pushed. The expressions are evaluated out-of-order wrt the
1367 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1370 */
1371 static identifier return_str;
1372 PyObject *names;
1373 int len;
1374 names = PyList_New(0);
1375 if (!names)
1376 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (compiler_visit_argannotations(c, args->args, names))
1379 goto error;
1380 if (args->varargannotation &&
1381 compiler_visit_argannotation(c, args->vararg,
1382 args->varargannotation, names))
1383 goto error;
1384 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1385 goto error;
1386 if (args->kwargannotation &&
1387 compiler_visit_argannotation(c, args->kwarg,
1388 args->kwargannotation, names))
1389 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (!return_str) {
1392 return_str = PyUnicode_InternFromString("return");
1393 if (!return_str)
1394 goto error;
1395 }
1396 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1397 goto error;
1398 }
1399
1400 len = PyList_GET_SIZE(names);
1401 if (len > 65534) {
1402 /* len must fit in 16 bits, and len is incremented below */
1403 PyErr_SetString(PyExc_SyntaxError,
1404 "too many annotations");
1405 goto error;
1406 }
1407 if (len) {
1408 /* convert names to a tuple and place on stack */
1409 PyObject *elt;
1410 int i;
1411 PyObject *s = PyTuple_New(len);
1412 if (!s)
1413 goto error;
1414 for (i = 0; i < len; i++) {
1415 elt = PyList_GET_ITEM(names, i);
1416 Py_INCREF(elt);
1417 PyTuple_SET_ITEM(s, i, elt);
1418 }
1419 ADDOP_O(c, LOAD_CONST, s, consts);
1420 Py_DECREF(s);
1421 len++; /* include the just-pushed tuple */
1422 }
1423 Py_DECREF(names);
1424 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001425
1426error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 Py_DECREF(names);
1428 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001429}
1430
1431static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432compiler_function(struct compiler *c, stmt_ty s)
1433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 PyCodeObject *co;
1435 PyObject *first_const = Py_None;
1436 arguments_ty args = s->v.FunctionDef.args;
1437 expr_ty returns = s->v.FunctionDef.returns;
1438 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1439 stmt_ty st;
1440 int i, n, docstring, kw_default_count = 0, arglength;
1441 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (!compiler_decorators(c, decos))
1446 return 0;
1447 if (args->kwonlyargs) {
1448 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1449 args->kw_defaults);
1450 if (res < 0)
1451 return 0;
1452 kw_default_count = res;
1453 }
1454 if (args->defaults)
1455 VISIT_SEQ(c, expr, args->defaults);
1456 num_annotations = compiler_visit_annotations(c, args, returns);
1457 if (num_annotations < 0)
1458 return 0;
1459 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1462 s->lineno))
1463 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1466 docstring = compiler_isdocstring(st);
1467 if (docstring && Py_OptimizeFlag < 2)
1468 first_const = st->v.Expr.value->v.Str.s;
1469 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1470 compiler_exit_scope(c);
1471 return 0;
1472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 c->u->u_argcount = asdl_seq_LEN(args->args);
1475 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1476 n = asdl_seq_LEN(s->v.FunctionDef.body);
1477 /* if there was a docstring, we need to skip the first statement */
1478 for (i = docstring; i < n; i++) {
1479 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1480 VISIT_IN_SCOPE(c, stmt, st);
1481 }
1482 co = assemble(c, 1);
1483 compiler_exit_scope(c);
1484 if (co == NULL)
1485 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 arglength = asdl_seq_LEN(args->defaults);
1488 arglength |= kw_default_count << 8;
1489 arglength |= num_annotations << 16;
1490 compiler_make_closure(c, co, arglength);
1491 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 /* decorators */
1494 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1495 ADDOP_I(c, CALL_FUNCTION, 1);
1496 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499}
1500
1501static int
1502compiler_class(struct compiler *c, stmt_ty s)
1503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 PyCodeObject *co;
1505 PyObject *str;
1506 int i;
1507 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!compiler_decorators(c, decos))
1510 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 /* ultimately generate code for:
1513 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1514 where:
1515 <func> is a function/closure created from the class body;
1516 it has a single argument (__locals__) where the dict
1517 (or MutableSequence) representing the locals is passed
1518 <name> is the class name
1519 <bases> is the positional arguments and *varargs argument
1520 <keywords> is the keyword arguments and **kwds argument
1521 This borrows from compiler_call.
1522 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 /* 1. compile the class body into a code object */
1525 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1526 return 0;
1527 /* this block represents what we do in the new scope */
1528 {
1529 /* use the class name for name mangling */
1530 Py_INCREF(s->v.ClassDef.name);
1531 Py_XDECREF(c->u->u_private);
1532 c->u->u_private = s->v.ClassDef.name;
1533 /* force it to have one mandatory argument */
1534 c->u->u_argcount = 1;
1535 /* load the first argument (__locals__) ... */
1536 ADDOP_I(c, LOAD_FAST, 0);
1537 /* ... and store it into f_locals */
1538 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1539 /* load (global) __name__ ... */
1540 str = PyUnicode_InternFromString("__name__");
1541 if (!str || !compiler_nameop(c, str, Load)) {
1542 Py_XDECREF(str);
1543 compiler_exit_scope(c);
1544 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001545 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 Py_DECREF(str);
1547 /* ... and store it as __module__ */
1548 str = PyUnicode_InternFromString("__module__");
1549 if (!str || !compiler_nameop(c, str, Store)) {
1550 Py_XDECREF(str);
1551 compiler_exit_scope(c);
1552 return 0;
1553 }
1554 Py_DECREF(str);
1555 /* compile the body proper */
1556 if (!compiler_body(c, s->v.ClassDef.body)) {
1557 compiler_exit_scope(c);
1558 return 0;
1559 }
1560 /* return the (empty) __class__ cell */
1561 str = PyUnicode_InternFromString("__class__");
1562 if (str == NULL) {
1563 compiler_exit_scope(c);
1564 return 0;
1565 }
1566 i = compiler_lookup_arg(c->u->u_cellvars, str);
1567 Py_DECREF(str);
1568 if (i == -1) {
1569 /* This happens when nobody references the cell */
1570 PyErr_Clear();
1571 /* Return None */
1572 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1573 }
1574 else {
1575 /* Return the cell where to store __class__ */
1576 ADDOP_I(c, LOAD_CLOSURE, i);
1577 }
1578 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1579 /* create the code object */
1580 co = assemble(c, 1);
1581 }
1582 /* leave the new scope */
1583 compiler_exit_scope(c);
1584 if (co == NULL)
1585 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 /* 2. load the 'build_class' function */
1588 ADDOP(c, LOAD_BUILD_CLASS);
1589
1590 /* 3. load a function (or closure) made from the code object */
1591 compiler_make_closure(c, co, 0);
1592 Py_DECREF(co);
1593
1594 /* 4. load class name */
1595 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1596
1597 /* 5. generate the rest of the code for the call */
1598 if (!compiler_call_helper(c, 2,
1599 s->v.ClassDef.bases,
1600 s->v.ClassDef.keywords,
1601 s->v.ClassDef.starargs,
1602 s->v.ClassDef.kwargs))
1603 return 0;
1604
1605 /* 6. apply decorators */
1606 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1607 ADDOP_I(c, CALL_FUNCTION, 1);
1608 }
1609
1610 /* 7. store into <name> */
1611 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1612 return 0;
1613 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001614}
1615
1616static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001617compiler_ifexp(struct compiler *c, expr_ty e)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 basicblock *end, *next;
1620
1621 assert(e->kind == IfExp_kind);
1622 end = compiler_new_block(c);
1623 if (end == NULL)
1624 return 0;
1625 next = compiler_new_block(c);
1626 if (next == NULL)
1627 return 0;
1628 VISIT(c, expr, e->v.IfExp.test);
1629 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1630 VISIT(c, expr, e->v.IfExp.body);
1631 ADDOP_JREL(c, JUMP_FORWARD, end);
1632 compiler_use_next_block(c, next);
1633 VISIT(c, expr, e->v.IfExp.orelse);
1634 compiler_use_next_block(c, end);
1635 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001636}
1637
1638static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639compiler_lambda(struct compiler *c, expr_ty e)
1640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 PyCodeObject *co;
1642 static identifier name;
1643 int kw_default_count = 0, arglength;
1644 arguments_ty args = e->v.Lambda.args;
1645 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 if (!name) {
1648 name = PyUnicode_InternFromString("<lambda>");
1649 if (!name)
1650 return 0;
1651 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 if (args->kwonlyargs) {
1654 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1655 args->kw_defaults);
1656 if (res < 0) return 0;
1657 kw_default_count = res;
1658 }
1659 if (args->defaults)
1660 VISIT_SEQ(c, expr, args->defaults);
1661 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1662 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 /* Make None the first constant, so the lambda can't have a
1665 docstring. */
1666 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1667 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 c->u->u_argcount = asdl_seq_LEN(args->args);
1670 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1671 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1672 if (c->u->u_ste->ste_generator) {
1673 ADDOP_IN_SCOPE(c, POP_TOP);
1674 }
1675 else {
1676 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1677 }
1678 co = assemble(c, 1);
1679 compiler_exit_scope(c);
1680 if (co == NULL)
1681 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 arglength = asdl_seq_LEN(args->defaults);
1684 arglength |= kw_default_count << 8;
1685 compiler_make_closure(c, co, arglength);
1686 Py_DECREF(co);
1687
1688 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689}
1690
1691static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692compiler_if(struct compiler *c, stmt_ty s)
1693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 basicblock *end, *next;
1695 int constant;
1696 assert(s->kind == If_kind);
1697 end = compiler_new_block(c);
1698 if (end == NULL)
1699 return 0;
1700
1701 constant = expr_constant(s->v.If.test);
1702 /* constant = 0: "if 0"
1703 * constant = 1: "if 1", "if 2", ...
1704 * constant = -1: rest */
1705 if (constant == 0) {
1706 if (s->v.If.orelse)
1707 VISIT_SEQ(c, stmt, s->v.If.orelse);
1708 } else if (constant == 1) {
1709 VISIT_SEQ(c, stmt, s->v.If.body);
1710 } else {
1711 if (s->v.If.orelse) {
1712 next = compiler_new_block(c);
1713 if (next == NULL)
1714 return 0;
1715 }
1716 else
1717 next = end;
1718 VISIT(c, expr, s->v.If.test);
1719 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1720 VISIT_SEQ(c, stmt, s->v.If.body);
1721 ADDOP_JREL(c, JUMP_FORWARD, end);
1722 if (s->v.If.orelse) {
1723 compiler_use_next_block(c, next);
1724 VISIT_SEQ(c, stmt, s->v.If.orelse);
1725 }
1726 }
1727 compiler_use_next_block(c, end);
1728 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001729}
1730
1731static int
1732compiler_for(struct compiler *c, stmt_ty s)
1733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 start = compiler_new_block(c);
1737 cleanup = compiler_new_block(c);
1738 end = compiler_new_block(c);
1739 if (start == NULL || end == NULL || cleanup == NULL)
1740 return 0;
1741 ADDOP_JREL(c, SETUP_LOOP, end);
1742 if (!compiler_push_fblock(c, LOOP, start))
1743 return 0;
1744 VISIT(c, expr, s->v.For.iter);
1745 ADDOP(c, GET_ITER);
1746 compiler_use_next_block(c, start);
1747 ADDOP_JREL(c, FOR_ITER, cleanup);
1748 VISIT(c, expr, s->v.For.target);
1749 VISIT_SEQ(c, stmt, s->v.For.body);
1750 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1751 compiler_use_next_block(c, cleanup);
1752 ADDOP(c, POP_BLOCK);
1753 compiler_pop_fblock(c, LOOP, start);
1754 VISIT_SEQ(c, stmt, s->v.For.orelse);
1755 compiler_use_next_block(c, end);
1756 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757}
1758
1759static int
1760compiler_while(struct compiler *c, stmt_ty s)
1761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 basicblock *loop, *orelse, *end, *anchor = NULL;
1763 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (constant == 0) {
1766 if (s->v.While.orelse)
1767 VISIT_SEQ(c, stmt, s->v.While.orelse);
1768 return 1;
1769 }
1770 loop = compiler_new_block(c);
1771 end = compiler_new_block(c);
1772 if (constant == -1) {
1773 anchor = compiler_new_block(c);
1774 if (anchor == NULL)
1775 return 0;
1776 }
1777 if (loop == NULL || end == NULL)
1778 return 0;
1779 if (s->v.While.orelse) {
1780 orelse = compiler_new_block(c);
1781 if (orelse == NULL)
1782 return 0;
1783 }
1784 else
1785 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 ADDOP_JREL(c, SETUP_LOOP, end);
1788 compiler_use_next_block(c, loop);
1789 if (!compiler_push_fblock(c, LOOP, loop))
1790 return 0;
1791 if (constant == -1) {
1792 VISIT(c, expr, s->v.While.test);
1793 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1794 }
1795 VISIT_SEQ(c, stmt, s->v.While.body);
1796 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* XXX should the two POP instructions be in a separate block
1799 if there is no else clause ?
1800 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (constant == -1) {
1803 compiler_use_next_block(c, anchor);
1804 ADDOP(c, POP_BLOCK);
1805 }
1806 compiler_pop_fblock(c, LOOP, loop);
1807 if (orelse != NULL) /* what if orelse is just pass? */
1808 VISIT_SEQ(c, stmt, s->v.While.orelse);
1809 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812}
1813
1814static int
1815compiler_continue(struct compiler *c)
1816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1818 static const char IN_FINALLY_ERROR_MSG[] =
1819 "'continue' not supported inside 'finally' clause";
1820 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (!c->u->u_nfblocks)
1823 return compiler_error(c, LOOP_ERROR_MSG);
1824 i = c->u->u_nfblocks - 1;
1825 switch (c->u->u_fblock[i].fb_type) {
1826 case LOOP:
1827 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1828 break;
1829 case EXCEPT:
1830 case FINALLY_TRY:
1831 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1832 /* Prevent continue anywhere under a finally
1833 even if hidden in a sub-try or except. */
1834 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1835 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1836 }
1837 if (i == -1)
1838 return compiler_error(c, LOOP_ERROR_MSG);
1839 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1840 break;
1841 case FINALLY_END:
1842 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846}
1847
1848/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849
1850 SETUP_FINALLY L
1851 <code for body>
1852 POP_BLOCK
1853 LOAD_CONST <None>
1854 L: <code for finalbody>
1855 END_FINALLY
1856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857 The special instructions use the block stack. Each block
1858 stack entry contains the instruction that created it (here
1859 SETUP_FINALLY), the level of the value stack at the time the
1860 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Pushes the current value stack level and the label
1864 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 Pops en entry from the block stack, and pops the value
1867 stack until its level is the same as indicated on the
1868 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 Pops a variable number of entries from the *value* stack
1871 and re-raises the exception they specify. The number of
1872 entries popped depends on the (pseudo) exception type.
1873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874 The block stack is unwound when an exception is raised:
1875 when a SETUP_FINALLY entry is found, the exception is pushed
1876 onto the value stack (and the exception condition is cleared),
1877 and the interpreter jumps to the label gotten from the block
1878 stack.
1879*/
1880
1881static int
1882compiler_try_finally(struct compiler *c, stmt_ty s)
1883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 basicblock *body, *end;
1885 body = compiler_new_block(c);
1886 end = compiler_new_block(c);
1887 if (body == NULL || end == NULL)
1888 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 ADDOP_JREL(c, SETUP_FINALLY, end);
1891 compiler_use_next_block(c, body);
1892 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1893 return 0;
1894 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1895 ADDOP(c, POP_BLOCK);
1896 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1899 compiler_use_next_block(c, end);
1900 if (!compiler_push_fblock(c, FINALLY_END, end))
1901 return 0;
1902 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1903 ADDOP(c, END_FINALLY);
1904 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907}
1908
1909/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001910 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911 (The contents of the value stack is shown in [], with the top
1912 at the right; 'tb' is trace-back info, 'val' the exception's
1913 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914
1915 Value stack Label Instruction Argument
1916 [] SETUP_EXCEPT L1
1917 [] <code for S>
1918 [] POP_BLOCK
1919 [] JUMP_FORWARD L0
1920
1921 [tb, val, exc] L1: DUP )
1922 [tb, val, exc, exc] <evaluate E1> )
1923 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1924 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1925 [tb, val, exc] POP
1926 [tb, val] <assign to V1> (or POP if no V1)
1927 [tb] POP
1928 [] <code for S1>
1929 JUMP_FORWARD L0
1930
1931 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932 .............................etc.......................
1933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1935
1936 [] L0: <next statement>
1937
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 Of course, parts are not generated if Vi or Ei is not present.
1939*/
1940static int
1941compiler_try_except(struct compiler *c, stmt_ty s)
1942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 basicblock *body, *orelse, *except, *end;
1944 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 body = compiler_new_block(c);
1947 except = compiler_new_block(c);
1948 orelse = compiler_new_block(c);
1949 end = compiler_new_block(c);
1950 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1951 return 0;
1952 ADDOP_JREL(c, SETUP_EXCEPT, except);
1953 compiler_use_next_block(c, body);
1954 if (!compiler_push_fblock(c, EXCEPT, body))
1955 return 0;
1956 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1957 ADDOP(c, POP_BLOCK);
1958 compiler_pop_fblock(c, EXCEPT, body);
1959 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1960 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1961 compiler_use_next_block(c, except);
1962 for (i = 0; i < n; i++) {
1963 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1964 s->v.TryExcept.handlers, i);
1965 if (!handler->v.ExceptHandler.type && i < n-1)
1966 return compiler_error(c, "default 'except:' must be last");
1967 c->u->u_lineno_set = 0;
1968 c->u->u_lineno = handler->lineno;
1969 except = compiler_new_block(c);
1970 if (except == NULL)
1971 return 0;
1972 if (handler->v.ExceptHandler.type) {
1973 ADDOP(c, DUP_TOP);
1974 VISIT(c, expr, handler->v.ExceptHandler.type);
1975 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1976 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
1977 }
1978 ADDOP(c, POP_TOP);
1979 if (handler->v.ExceptHandler.name) {
1980 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 cleanup_end = compiler_new_block(c);
1983 cleanup_body = compiler_new_block(c);
1984 if(!(cleanup_end || cleanup_body))
1985 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
1988 ADDOP(c, POP_TOP);
1989
1990 /*
1991 try:
1992 # body
1993 except type as name:
1994 try:
1995 # body
1996 finally:
1997 name = None
1998 del name
1999 */
2000
2001 /* second try: */
2002 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2003 compiler_use_next_block(c, cleanup_body);
2004 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2005 return 0;
2006
2007 /* second # body */
2008 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2009 ADDOP(c, POP_BLOCK);
2010 ADDOP(c, POP_EXCEPT);
2011 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2012
2013 /* finally: */
2014 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2015 compiler_use_next_block(c, cleanup_end);
2016 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2017 return 0;
2018
2019 /* name = None */
2020 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2021 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2022
2023 /* del name */
2024 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
2025
2026 ADDOP(c, END_FINALLY);
2027 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
2028 }
2029 else {
2030 basicblock *cleanup_body;
2031
2032 cleanup_body = compiler_new_block(c);
2033 if(!cleanup_body)
2034 return 0;
2035
Guido van Rossumb940e112007-01-10 16:19:56 +00002036 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 ADDOP(c, POP_TOP);
2038 compiler_use_next_block(c, cleanup_body);
2039 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2040 return 0;
2041 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2042 ADDOP(c, POP_EXCEPT);
2043 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
2044 }
2045 ADDOP_JREL(c, JUMP_FORWARD, end);
2046 compiler_use_next_block(c, except);
2047 }
2048 ADDOP(c, END_FINALLY);
2049 compiler_use_next_block(c, orelse);
2050 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2051 compiler_use_next_block(c, end);
2052 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053}
2054
2055static int
2056compiler_import_as(struct compiler *c, identifier name, identifier asname)
2057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 /* The IMPORT_NAME opcode was already generated. This function
2059 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 If there is a dot in name, we need to split it and emit a
2062 LOAD_ATTR for each name.
2063 */
2064 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2065 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
2066 if (dot) {
2067 /* Consume the base module name to get the first attribute */
2068 src = dot + 1;
2069 while (dot) {
2070 /* NB src is only defined when dot != NULL */
2071 PyObject *attr;
2072 dot = Py_UNICODE_strchr(src, '.');
2073 attr = PyUnicode_FromUnicode(src,
2074 dot ? dot - src : Py_UNICODE_strlen(src));
2075 if (!attr)
2076 return -1;
2077 ADDOP_O(c, LOAD_ATTR, attr, names);
2078 Py_DECREF(attr);
2079 src = dot + 1;
2080 }
2081 }
2082 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083}
2084
2085static int
2086compiler_import(struct compiler *c, stmt_ty s)
2087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* The Import node stores a module name like a.b.c as a single
2089 string. This is convenient for all cases except
2090 import a.b.c as d
2091 where we need to parse that string to extract the individual
2092 module names.
2093 XXX Perhaps change the representation to make this case simpler?
2094 */
2095 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 for (i = 0; i < n; i++) {
2098 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2099 int r;
2100 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 level = PyLong_FromLong(0);
2103 if (level == NULL)
2104 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 ADDOP_O(c, LOAD_CONST, level, consts);
2107 Py_DECREF(level);
2108 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2109 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (alias->asname) {
2112 r = compiler_import_as(c, alias->name, alias->asname);
2113 if (!r)
2114 return r;
2115 }
2116 else {
2117 identifier tmp = alias->name;
2118 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2119 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
2120 if (dot)
2121 tmp = PyUnicode_FromUnicode(base,
2122 dot - base);
2123 r = compiler_nameop(c, tmp, Store);
2124 if (dot) {
2125 Py_DECREF(tmp);
2126 }
2127 if (!r)
2128 return r;
2129 }
2130 }
2131 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132}
2133
2134static int
2135compiler_from_import(struct compiler *c, stmt_ty s)
2136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 PyObject *names = PyTuple_New(n);
2140 PyObject *level;
2141 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 if (!empty_string) {
2144 empty_string = PyUnicode_FromString("");
2145 if (!empty_string)
2146 return 0;
2147 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (!names)
2150 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 level = PyLong_FromLong(s->v.ImportFrom.level);
2153 if (!level) {
2154 Py_DECREF(names);
2155 return 0;
2156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 /* build up the names */
2159 for (i = 0; i < n; i++) {
2160 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2161 Py_INCREF(alias->name);
2162 PyTuple_SET_ITEM(names, i, alias->name);
2163 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2166 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2167 Py_DECREF(level);
2168 Py_DECREF(names);
2169 return compiler_error(c, "from __future__ imports must occur "
2170 "at the beginning of the file");
2171 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 ADDOP_O(c, LOAD_CONST, level, consts);
2174 Py_DECREF(level);
2175 ADDOP_O(c, LOAD_CONST, names, consts);
2176 Py_DECREF(names);
2177 if (s->v.ImportFrom.module) {
2178 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2179 }
2180 else {
2181 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2182 }
2183 for (i = 0; i < n; i++) {
2184 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2185 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
2188 assert(n == 1);
2189 ADDOP(c, IMPORT_STAR);
2190 return 1;
2191 }
2192
2193 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2194 store_name = alias->name;
2195 if (alias->asname)
2196 store_name = alias->asname;
2197
2198 if (!compiler_nameop(c, store_name, Store)) {
2199 Py_DECREF(names);
2200 return 0;
2201 }
2202 }
2203 /* remove imported module */
2204 ADDOP(c, POP_TOP);
2205 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002206}
2207
2208static int
2209compiler_assert(struct compiler *c, stmt_ty s)
2210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 static PyObject *assertion_error = NULL;
2212 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (Py_OptimizeFlag)
2215 return 1;
2216 if (assertion_error == NULL) {
2217 assertion_error = PyUnicode_InternFromString("AssertionError");
2218 if (assertion_error == NULL)
2219 return 0;
2220 }
2221 if (s->v.Assert.test->kind == Tuple_kind &&
2222 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2223 const char* msg =
2224 "assertion is always true, perhaps remove parentheses?";
2225 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2226 c->u->u_lineno, NULL, NULL) == -1)
2227 return 0;
2228 }
2229 VISIT(c, expr, s->v.Assert.test);
2230 end = compiler_new_block(c);
2231 if (end == NULL)
2232 return 0;
2233 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2234 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2235 if (s->v.Assert.msg) {
2236 VISIT(c, expr, s->v.Assert.msg);
2237 ADDOP_I(c, CALL_FUNCTION, 1);
2238 }
2239 ADDOP_I(c, RAISE_VARARGS, 1);
2240 compiler_use_next_block(c, end);
2241 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242}
2243
2244static int
2245compiler_visit_stmt(struct compiler *c, stmt_ty s)
2246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* Always assign a lineno to the next instruction for a stmt. */
2250 c->u->u_lineno = s->lineno;
2251 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 switch (s->kind) {
2254 case FunctionDef_kind:
2255 return compiler_function(c, s);
2256 case ClassDef_kind:
2257 return compiler_class(c, s);
2258 case Return_kind:
2259 if (c->u->u_ste->ste_type != FunctionBlock)
2260 return compiler_error(c, "'return' outside function");
2261 if (s->v.Return.value) {
2262 VISIT(c, expr, s->v.Return.value);
2263 }
2264 else
2265 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2266 ADDOP(c, RETURN_VALUE);
2267 break;
2268 case Delete_kind:
2269 VISIT_SEQ(c, expr, s->v.Delete.targets)
2270 break;
2271 case Assign_kind:
2272 n = asdl_seq_LEN(s->v.Assign.targets);
2273 VISIT(c, expr, s->v.Assign.value);
2274 for (i = 0; i < n; i++) {
2275 if (i < n - 1)
2276 ADDOP(c, DUP_TOP);
2277 VISIT(c, expr,
2278 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2279 }
2280 break;
2281 case AugAssign_kind:
2282 return compiler_augassign(c, s);
2283 case For_kind:
2284 return compiler_for(c, s);
2285 case While_kind:
2286 return compiler_while(c, s);
2287 case If_kind:
2288 return compiler_if(c, s);
2289 case Raise_kind:
2290 n = 0;
2291 if (s->v.Raise.exc) {
2292 VISIT(c, expr, s->v.Raise.exc);
2293 n++;
2294 if (s->v.Raise.cause) {
2295 VISIT(c, expr, s->v.Raise.cause);
2296 n++;
2297 }
2298 }
2299 ADDOP_I(c, RAISE_VARARGS, n);
2300 break;
2301 case TryExcept_kind:
2302 return compiler_try_except(c, s);
2303 case TryFinally_kind:
2304 return compiler_try_finally(c, s);
2305 case Assert_kind:
2306 return compiler_assert(c, s);
2307 case Import_kind:
2308 return compiler_import(c, s);
2309 case ImportFrom_kind:
2310 return compiler_from_import(c, s);
2311 case Global_kind:
2312 case Nonlocal_kind:
2313 break;
2314 case Expr_kind:
2315 if (c->c_interactive && c->c_nestlevel <= 1) {
2316 VISIT(c, expr, s->v.Expr.value);
2317 ADDOP(c, PRINT_EXPR);
2318 }
2319 else if (s->v.Expr.value->kind != Str_kind &&
2320 s->v.Expr.value->kind != Num_kind) {
2321 VISIT(c, expr, s->v.Expr.value);
2322 ADDOP(c, POP_TOP);
2323 }
2324 break;
2325 case Pass_kind:
2326 break;
2327 case Break_kind:
2328 if (!compiler_in_loop(c))
2329 return compiler_error(c, "'break' outside loop");
2330 ADDOP(c, BREAK_LOOP);
2331 break;
2332 case Continue_kind:
2333 return compiler_continue(c);
2334 case With_kind:
2335 return compiler_with(c, s);
2336 }
2337 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338}
2339
2340static int
2341unaryop(unaryop_ty op)
2342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 switch (op) {
2344 case Invert:
2345 return UNARY_INVERT;
2346 case Not:
2347 return UNARY_NOT;
2348 case UAdd:
2349 return UNARY_POSITIVE;
2350 case USub:
2351 return UNARY_NEGATIVE;
2352 default:
2353 PyErr_Format(PyExc_SystemError,
2354 "unary op %d should not be possible", op);
2355 return 0;
2356 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357}
2358
2359static int
2360binop(struct compiler *c, operator_ty op)
2361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 switch (op) {
2363 case Add:
2364 return BINARY_ADD;
2365 case Sub:
2366 return BINARY_SUBTRACT;
2367 case Mult:
2368 return BINARY_MULTIPLY;
2369 case Div:
2370 return BINARY_TRUE_DIVIDE;
2371 case Mod:
2372 return BINARY_MODULO;
2373 case Pow:
2374 return BINARY_POWER;
2375 case LShift:
2376 return BINARY_LSHIFT;
2377 case RShift:
2378 return BINARY_RSHIFT;
2379 case BitOr:
2380 return BINARY_OR;
2381 case BitXor:
2382 return BINARY_XOR;
2383 case BitAnd:
2384 return BINARY_AND;
2385 case FloorDiv:
2386 return BINARY_FLOOR_DIVIDE;
2387 default:
2388 PyErr_Format(PyExc_SystemError,
2389 "binary op %d should not be possible", op);
2390 return 0;
2391 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392}
2393
2394static int
2395cmpop(cmpop_ty op)
2396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 switch (op) {
2398 case Eq:
2399 return PyCmp_EQ;
2400 case NotEq:
2401 return PyCmp_NE;
2402 case Lt:
2403 return PyCmp_LT;
2404 case LtE:
2405 return PyCmp_LE;
2406 case Gt:
2407 return PyCmp_GT;
2408 case GtE:
2409 return PyCmp_GE;
2410 case Is:
2411 return PyCmp_IS;
2412 case IsNot:
2413 return PyCmp_IS_NOT;
2414 case In:
2415 return PyCmp_IN;
2416 case NotIn:
2417 return PyCmp_NOT_IN;
2418 default:
2419 return PyCmp_BAD;
2420 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421}
2422
2423static int
2424inplace_binop(struct compiler *c, operator_ty op)
2425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 switch (op) {
2427 case Add:
2428 return INPLACE_ADD;
2429 case Sub:
2430 return INPLACE_SUBTRACT;
2431 case Mult:
2432 return INPLACE_MULTIPLY;
2433 case Div:
2434 return INPLACE_TRUE_DIVIDE;
2435 case Mod:
2436 return INPLACE_MODULO;
2437 case Pow:
2438 return INPLACE_POWER;
2439 case LShift:
2440 return INPLACE_LSHIFT;
2441 case RShift:
2442 return INPLACE_RSHIFT;
2443 case BitOr:
2444 return INPLACE_OR;
2445 case BitXor:
2446 return INPLACE_XOR;
2447 case BitAnd:
2448 return INPLACE_AND;
2449 case FloorDiv:
2450 return INPLACE_FLOOR_DIVIDE;
2451 default:
2452 PyErr_Format(PyExc_SystemError,
2453 "inplace binary op %d should not be possible", op);
2454 return 0;
2455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456}
2457
2458static int
2459compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 int op, scope, arg;
2462 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyObject *dict = c->u->u_names;
2465 PyObject *mangled;
2466 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 mangled = _Py_Mangle(c->u->u_private, name);
2469 if (!mangled)
2470 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 op = 0;
2473 optype = OP_NAME;
2474 scope = PyST_GetScope(c->u->u_ste, mangled);
2475 switch (scope) {
2476 case FREE:
2477 dict = c->u->u_freevars;
2478 optype = OP_DEREF;
2479 break;
2480 case CELL:
2481 dict = c->u->u_cellvars;
2482 optype = OP_DEREF;
2483 break;
2484 case LOCAL:
Benjamin Peterson013783c2010-07-20 22:37:19 +00002485 case LOCAL_ONLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (c->u->u_ste->ste_type == FunctionBlock)
2487 optype = OP_FAST;
2488 break;
2489 case GLOBAL_IMPLICIT:
2490 if (c->u->u_ste->ste_type == FunctionBlock &&
2491 !c->u->u_ste->ste_unoptimized)
2492 optype = OP_GLOBAL;
2493 break;
2494 case GLOBAL_EXPLICIT:
2495 optype = OP_GLOBAL;
2496 break;
2497 default:
2498 /* scope can be 0 */
2499 break;
2500 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* XXX Leave assert here, but handle __doc__ and the like better */
2503 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 switch (optype) {
2506 case OP_DEREF:
2507 switch (ctx) {
2508 case Load: op = LOAD_DEREF; break;
2509 case Store: op = STORE_DEREF; break;
2510 case AugLoad:
2511 case AugStore:
2512 break;
2513 case Del:
2514 PyErr_Format(PyExc_SyntaxError,
2515 "can not delete variable '%S' referenced "
2516 "in nested scope",
2517 name);
2518 Py_DECREF(mangled);
2519 return 0;
2520 case Param:
2521 default:
2522 PyErr_SetString(PyExc_SystemError,
2523 "param invalid for deref variable");
2524 return 0;
2525 }
2526 break;
2527 case OP_FAST:
2528 switch (ctx) {
2529 case Load: op = LOAD_FAST; break;
2530 case Store: op = STORE_FAST; break;
2531 case Del: op = DELETE_FAST; break;
2532 case AugLoad:
2533 case AugStore:
2534 break;
2535 case Param:
2536 default:
2537 PyErr_SetString(PyExc_SystemError,
2538 "param invalid for local variable");
2539 return 0;
2540 }
2541 ADDOP_O(c, op, mangled, varnames);
2542 Py_DECREF(mangled);
2543 return 1;
2544 case OP_GLOBAL:
2545 switch (ctx) {
2546 case Load: op = LOAD_GLOBAL; break;
2547 case Store: op = STORE_GLOBAL; break;
2548 case Del: op = DELETE_GLOBAL; break;
2549 case AugLoad:
2550 case AugStore:
2551 break;
2552 case Param:
2553 default:
2554 PyErr_SetString(PyExc_SystemError,
2555 "param invalid for global variable");
2556 return 0;
2557 }
2558 break;
2559 case OP_NAME:
2560 switch (ctx) {
Benjamin Peterson013783c2010-07-20 22:37:19 +00002561 case Load: op = (scope == LOCAL_ONLY) ? LOAD_NAME_LOCAL_ONLY : LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 case Store: op = STORE_NAME; break;
2563 case Del: op = DELETE_NAME; break;
2564 case AugLoad:
2565 case AugStore:
2566 break;
2567 case Param:
2568 default:
2569 PyErr_SetString(PyExc_SystemError,
2570 "param invalid for name variable");
2571 return 0;
2572 }
2573 break;
2574 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 assert(op);
2577 arg = compiler_add_o(c, dict, mangled);
2578 Py_DECREF(mangled);
2579 if (arg < 0)
2580 return 0;
2581 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582}
2583
2584static int
2585compiler_boolop(struct compiler *c, expr_ty e)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 basicblock *end;
2588 int jumpi, i, n;
2589 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 assert(e->kind == BoolOp_kind);
2592 if (e->v.BoolOp.op == And)
2593 jumpi = JUMP_IF_FALSE_OR_POP;
2594 else
2595 jumpi = JUMP_IF_TRUE_OR_POP;
2596 end = compiler_new_block(c);
2597 if (end == NULL)
2598 return 0;
2599 s = e->v.BoolOp.values;
2600 n = asdl_seq_LEN(s) - 1;
2601 assert(n >= 0);
2602 for (i = 0; i < n; ++i) {
2603 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2604 ADDOP_JABS(c, jumpi, end);
2605 }
2606 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2607 compiler_use_next_block(c, end);
2608 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609}
2610
2611static int
2612compiler_list(struct compiler *c, expr_ty e)
2613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 int n = asdl_seq_LEN(e->v.List.elts);
2615 if (e->v.List.ctx == Store) {
2616 int i, seen_star = 0;
2617 for (i = 0; i < n; i++) {
2618 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2619 if (elt->kind == Starred_kind && !seen_star) {
2620 if ((i >= (1 << 8)) ||
2621 (n-i-1 >= (INT_MAX >> 8)))
2622 return compiler_error(c,
2623 "too many expressions in "
2624 "star-unpacking assignment");
2625 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2626 seen_star = 1;
2627 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2628 } else if (elt->kind == Starred_kind) {
2629 return compiler_error(c,
2630 "two starred expressions in assignment");
2631 }
2632 }
2633 if (!seen_star) {
2634 ADDOP_I(c, UNPACK_SEQUENCE, n);
2635 }
2636 }
2637 VISIT_SEQ(c, expr, e->v.List.elts);
2638 if (e->v.List.ctx == Load) {
2639 ADDOP_I(c, BUILD_LIST, n);
2640 }
2641 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642}
2643
2644static int
2645compiler_tuple(struct compiler *c, expr_ty e)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 int n = asdl_seq_LEN(e->v.Tuple.elts);
2648 if (e->v.Tuple.ctx == Store) {
2649 int i, seen_star = 0;
2650 for (i = 0; i < n; i++) {
2651 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2652 if (elt->kind == Starred_kind && !seen_star) {
2653 if ((i >= (1 << 8)) ||
2654 (n-i-1 >= (INT_MAX >> 8)))
2655 return compiler_error(c,
2656 "too many expressions in "
2657 "star-unpacking assignment");
2658 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2659 seen_star = 1;
2660 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2661 } else if (elt->kind == Starred_kind) {
2662 return compiler_error(c,
2663 "two starred expressions in assignment");
2664 }
2665 }
2666 if (!seen_star) {
2667 ADDOP_I(c, UNPACK_SEQUENCE, n);
2668 }
2669 }
2670 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2671 if (e->v.Tuple.ctx == Load) {
2672 ADDOP_I(c, BUILD_TUPLE, n);
2673 }
2674 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675}
2676
2677static int
2678compiler_compare(struct compiler *c, expr_ty e)
2679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 int i, n;
2681 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2684 VISIT(c, expr, e->v.Compare.left);
2685 n = asdl_seq_LEN(e->v.Compare.ops);
2686 assert(n > 0);
2687 if (n > 1) {
2688 cleanup = compiler_new_block(c);
2689 if (cleanup == NULL)
2690 return 0;
2691 VISIT(c, expr,
2692 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2693 }
2694 for (i = 1; i < n; i++) {
2695 ADDOP(c, DUP_TOP);
2696 ADDOP(c, ROT_THREE);
2697 ADDOP_I(c, COMPARE_OP,
2698 cmpop((cmpop_ty)(asdl_seq_GET(
2699 e->v.Compare.ops, i - 1))));
2700 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2701 NEXT_BLOCK(c);
2702 if (i < (n - 1))
2703 VISIT(c, expr,
2704 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2705 }
2706 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2707 ADDOP_I(c, COMPARE_OP,
2708 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2709 if (n > 1) {
2710 basicblock *end = compiler_new_block(c);
2711 if (end == NULL)
2712 return 0;
2713 ADDOP_JREL(c, JUMP_FORWARD, end);
2714 compiler_use_next_block(c, cleanup);
2715 ADDOP(c, ROT_TWO);
2716 ADDOP(c, POP_TOP);
2717 compiler_use_next_block(c, end);
2718 }
2719 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720}
2721
2722static int
2723compiler_call(struct compiler *c, expr_ty e)
2724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 VISIT(c, expr, e->v.Call.func);
2726 return compiler_call_helper(c, 0,
2727 e->v.Call.args,
2728 e->v.Call.keywords,
2729 e->v.Call.starargs,
2730 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002731}
2732
2733/* shared code between compiler_call and compiler_class */
2734static int
2735compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 int n, /* Args already pushed */
2737 asdl_seq *args,
2738 asdl_seq *keywords,
2739 expr_ty starargs,
2740 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 n += asdl_seq_LEN(args);
2745 VISIT_SEQ(c, expr, args);
2746 if (keywords) {
2747 VISIT_SEQ(c, keyword, keywords);
2748 n |= asdl_seq_LEN(keywords) << 8;
2749 }
2750 if (starargs) {
2751 VISIT(c, expr, starargs);
2752 code |= 1;
2753 }
2754 if (kwargs) {
2755 VISIT(c, expr, kwargs);
2756 code |= 2;
2757 }
2758 switch (code) {
2759 case 0:
2760 ADDOP_I(c, CALL_FUNCTION, n);
2761 break;
2762 case 1:
2763 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2764 break;
2765 case 2:
2766 ADDOP_I(c, CALL_FUNCTION_KW, n);
2767 break;
2768 case 3:
2769 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2770 break;
2771 }
2772 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773}
2774
Nick Coghlan650f0d02007-04-15 12:05:43 +00002775
2776/* List and set comprehensions and generator expressions work by creating a
2777 nested function to perform the actual iteration. This means that the
2778 iteration variables don't leak into the current scope.
2779 The defined function is called immediately following its definition, with the
2780 result of that call being the result of the expression.
2781 The LC/SC version returns the populated container, while the GE version is
2782 flagged in symtable.c as a generator, so it returns the generator object
2783 when the function is called.
2784 This code *knows* that the loop cannot contain break, continue, or return,
2785 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2786
2787 Possible cleanups:
2788 - iterate over the generator sequence instead of using recursion
2789*/
2790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792compiler_comprehension_generator(struct compiler *c,
2793 asdl_seq *generators, int gen_index,
2794 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 /* generate code for the iterator, then each of the ifs,
2797 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 comprehension_ty gen;
2800 basicblock *start, *anchor, *skip, *if_cleanup;
2801 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 start = compiler_new_block(c);
2804 skip = compiler_new_block(c);
2805 if_cleanup = compiler_new_block(c);
2806 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2809 anchor == NULL)
2810 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 if (gen_index == 0) {
2815 /* Receive outermost iter as an implicit argument */
2816 c->u->u_argcount = 1;
2817 ADDOP_I(c, LOAD_FAST, 0);
2818 }
2819 else {
2820 /* Sub-iter - calculate on the fly */
2821 VISIT(c, expr, gen->iter);
2822 ADDOP(c, GET_ITER);
2823 }
2824 compiler_use_next_block(c, start);
2825 ADDOP_JREL(c, FOR_ITER, anchor);
2826 NEXT_BLOCK(c);
2827 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 /* XXX this needs to be cleaned up...a lot! */
2830 n = asdl_seq_LEN(gen->ifs);
2831 for (i = 0; i < n; i++) {
2832 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2833 VISIT(c, expr, e);
2834 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2835 NEXT_BLOCK(c);
2836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 if (++gen_index < asdl_seq_LEN(generators))
2839 if (!compiler_comprehension_generator(c,
2840 generators, gen_index,
2841 elt, val, type))
2842 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 /* only append after the last for generator */
2845 if (gen_index >= asdl_seq_LEN(generators)) {
2846 /* comprehension specific code */
2847 switch (type) {
2848 case COMP_GENEXP:
2849 VISIT(c, expr, elt);
2850 ADDOP(c, YIELD_VALUE);
2851 ADDOP(c, POP_TOP);
2852 break;
2853 case COMP_LISTCOMP:
2854 VISIT(c, expr, elt);
2855 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2856 break;
2857 case COMP_SETCOMP:
2858 VISIT(c, expr, elt);
2859 ADDOP_I(c, SET_ADD, gen_index + 1);
2860 break;
2861 case COMP_DICTCOMP:
2862 /* With 'd[k] = v', v is evaluated before k, so we do
2863 the same. */
2864 VISIT(c, expr, val);
2865 VISIT(c, expr, elt);
2866 ADDOP_I(c, MAP_ADD, gen_index + 1);
2867 break;
2868 default:
2869 return 0;
2870 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 compiler_use_next_block(c, skip);
2873 }
2874 compiler_use_next_block(c, if_cleanup);
2875 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2876 compiler_use_next_block(c, anchor);
2877
2878 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879}
2880
2881static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002882compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 PyCodeObject *co = NULL;
2886 expr_ty outermost_iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 outermost_iter = ((comprehension_ty)
2889 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2892 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (type != COMP_GENEXP) {
2895 int op;
2896 switch (type) {
2897 case COMP_LISTCOMP:
2898 op = BUILD_LIST;
2899 break;
2900 case COMP_SETCOMP:
2901 op = BUILD_SET;
2902 break;
2903 case COMP_DICTCOMP:
2904 op = BUILD_MAP;
2905 break;
2906 default:
2907 PyErr_Format(PyExc_SystemError,
2908 "unknown comprehension type %d", type);
2909 goto error_in_scope;
2910 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 ADDOP_I(c, op, 0);
2913 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 if (!compiler_comprehension_generator(c, generators, 0, elt,
2916 val, type))
2917 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 if (type != COMP_GENEXP) {
2920 ADDOP(c, RETURN_VALUE);
2921 }
2922
2923 co = assemble(c, 1);
2924 compiler_exit_scope(c);
2925 if (co == NULL)
2926 goto error;
2927
2928 if (!compiler_make_closure(c, co, 0))
2929 goto error;
2930 Py_DECREF(co);
2931
2932 VISIT(c, expr, outermost_iter);
2933 ADDOP(c, GET_ITER);
2934 ADDOP_I(c, CALL_FUNCTION, 1);
2935 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002936error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002938error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 Py_XDECREF(co);
2940 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002941}
2942
2943static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944compiler_genexp(struct compiler *c, expr_ty e)
2945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 static identifier name;
2947 if (!name) {
2948 name = PyUnicode_FromString("<genexpr>");
2949 if (!name)
2950 return 0;
2951 }
2952 assert(e->kind == GeneratorExp_kind);
2953 return compiler_comprehension(c, e, COMP_GENEXP, name,
2954 e->v.GeneratorExp.generators,
2955 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956}
2957
2958static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002959compiler_listcomp(struct compiler *c, expr_ty e)
2960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 static identifier name;
2962 if (!name) {
2963 name = PyUnicode_FromString("<listcomp>");
2964 if (!name)
2965 return 0;
2966 }
2967 assert(e->kind == ListComp_kind);
2968 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2969 e->v.ListComp.generators,
2970 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002971}
2972
2973static int
2974compiler_setcomp(struct compiler *c, expr_ty e)
2975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 static identifier name;
2977 if (!name) {
2978 name = PyUnicode_FromString("<setcomp>");
2979 if (!name)
2980 return 0;
2981 }
2982 assert(e->kind == SetComp_kind);
2983 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2984 e->v.SetComp.generators,
2985 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00002986}
2987
2988
2989static int
2990compiler_dictcomp(struct compiler *c, expr_ty e)
2991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 static identifier name;
2993 if (!name) {
2994 name = PyUnicode_FromString("<dictcomp>");
2995 if (!name)
2996 return 0;
2997 }
2998 assert(e->kind == DictComp_kind);
2999 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3000 e->v.DictComp.generators,
3001 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003002}
3003
3004
3005static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006compiler_visit_keyword(struct compiler *c, keyword_ty k)
3007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3009 VISIT(c, expr, k->value);
3010 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011}
3012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 whether they are true or false.
3015
3016 Return values: 1 for true, 0 for false, -1 for non-constant.
3017 */
3018
3019static int
3020expr_constant(expr_ty e)
3021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 char *id;
3023 switch (e->kind) {
3024 case Ellipsis_kind:
3025 return 1;
3026 case Num_kind:
3027 return PyObject_IsTrue(e->v.Num.n);
3028 case Str_kind:
3029 return PyObject_IsTrue(e->v.Str.s);
3030 case Name_kind:
3031 /* optimize away names that can't be reassigned */
3032 id = PyBytes_AS_STRING(
3033 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
3034 if (strcmp(id, "True") == 0) return 1;
3035 if (strcmp(id, "False") == 0) return 0;
3036 if (strcmp(id, "None") == 0) return 0;
3037 if (strcmp(id, "__debug__") == 0)
3038 return ! Py_OptimizeFlag;
3039 /* fall through */
3040 default:
3041 return -1;
3042 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043}
3044
Guido van Rossumc2e20742006-02-27 22:32:47 +00003045/*
3046 Implements the with statement from PEP 343.
3047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003049
3050 with EXPR as VAR:
3051 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052
Guido van Rossumc2e20742006-02-27 22:32:47 +00003053 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054
Thomas Wouters477c8d52006-05-27 19:21:47 +00003055 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003056 exit = context.__exit__ # not calling it
3057 value = context.__enter__()
3058 try:
3059 VAR = value # if VAR present in the syntax
3060 BLOCK
3061 finally:
3062 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003064 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003066 exit(*exc)
3067 */
3068static int
3069compiler_with(struct compiler *c, stmt_ty s)
3070{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003071 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003072
3073 assert(s->kind == With_kind);
3074
Guido van Rossumc2e20742006-02-27 22:32:47 +00003075 block = compiler_new_block(c);
3076 finally = compiler_new_block(c);
3077 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003078 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003079
Thomas Wouters477c8d52006-05-27 19:21:47 +00003080 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003081 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003082 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003083
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003084 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003085 compiler_use_next_block(c, block);
3086 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003087 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003088 }
3089
3090 if (s->v.With.optional_vars) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003091 VISIT(c, expr, s->v.With.optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003092 }
3093 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003095 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003096 }
3097
3098 /* BLOCK code */
3099 VISIT_SEQ(c, stmt, s->v.With.body);
3100
3101 /* End of try block; start the finally block */
3102 ADDOP(c, POP_BLOCK);
3103 compiler_pop_fblock(c, FINALLY_TRY, block);
3104
3105 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3106 compiler_use_next_block(c, finally);
3107 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003108 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003109
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003110 /* Finally block starts; context.__exit__ is on the stack under
3111 the exception or return information. Just issue our magic
3112 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003113 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003114
3115 /* Finally block ends. */
3116 ADDOP(c, END_FINALLY);
3117 compiler_pop_fblock(c, FINALLY_END, finally);
3118 return 1;
3119}
3120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121static int
3122compiler_visit_expr(struct compiler *c, expr_ty e)
3123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 /* If expr e has a different line number than the last expr/stmt,
3127 set a new line number for the next instruction.
3128 */
3129 if (e->lineno > c->u->u_lineno) {
3130 c->u->u_lineno = e->lineno;
3131 c->u->u_lineno_set = 0;
3132 }
3133 switch (e->kind) {
3134 case BoolOp_kind:
3135 return compiler_boolop(c, e);
3136 case BinOp_kind:
3137 VISIT(c, expr, e->v.BinOp.left);
3138 VISIT(c, expr, e->v.BinOp.right);
3139 ADDOP(c, binop(c, e->v.BinOp.op));
3140 break;
3141 case UnaryOp_kind:
3142 VISIT(c, expr, e->v.UnaryOp.operand);
3143 ADDOP(c, unaryop(e->v.UnaryOp.op));
3144 break;
3145 case Lambda_kind:
3146 return compiler_lambda(c, e);
3147 case IfExp_kind:
3148 return compiler_ifexp(c, e);
3149 case Dict_kind:
3150 n = asdl_seq_LEN(e->v.Dict.values);
3151 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3152 for (i = 0; i < n; i++) {
3153 VISIT(c, expr,
3154 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3155 VISIT(c, expr,
3156 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3157 ADDOP(c, STORE_MAP);
3158 }
3159 break;
3160 case Set_kind:
3161 n = asdl_seq_LEN(e->v.Set.elts);
3162 VISIT_SEQ(c, expr, e->v.Set.elts);
3163 ADDOP_I(c, BUILD_SET, n);
3164 break;
3165 case GeneratorExp_kind:
3166 return compiler_genexp(c, e);
3167 case ListComp_kind:
3168 return compiler_listcomp(c, e);
3169 case SetComp_kind:
3170 return compiler_setcomp(c, e);
3171 case DictComp_kind:
3172 return compiler_dictcomp(c, e);
3173 case Yield_kind:
3174 if (c->u->u_ste->ste_type != FunctionBlock)
3175 return compiler_error(c, "'yield' outside function");
3176 if (e->v.Yield.value) {
3177 VISIT(c, expr, e->v.Yield.value);
3178 }
3179 else {
3180 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3181 }
3182 ADDOP(c, YIELD_VALUE);
3183 break;
3184 case Compare_kind:
3185 return compiler_compare(c, e);
3186 case Call_kind:
3187 return compiler_call(c, e);
3188 case Num_kind:
3189 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3190 break;
3191 case Str_kind:
3192 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3193 break;
3194 case Bytes_kind:
3195 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3196 break;
3197 case Ellipsis_kind:
3198 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3199 break;
3200 /* The following exprs can be assignment targets. */
3201 case Attribute_kind:
3202 if (e->v.Attribute.ctx != AugStore)
3203 VISIT(c, expr, e->v.Attribute.value);
3204 switch (e->v.Attribute.ctx) {
3205 case AugLoad:
3206 ADDOP(c, DUP_TOP);
3207 /* Fall through to load */
3208 case Load:
3209 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3210 break;
3211 case AugStore:
3212 ADDOP(c, ROT_TWO);
3213 /* Fall through to save */
3214 case Store:
3215 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3216 break;
3217 case Del:
3218 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3219 break;
3220 case Param:
3221 default:
3222 PyErr_SetString(PyExc_SystemError,
3223 "param invalid in attribute expression");
3224 return 0;
3225 }
3226 break;
3227 case Subscript_kind:
3228 switch (e->v.Subscript.ctx) {
3229 case AugLoad:
3230 VISIT(c, expr, e->v.Subscript.value);
3231 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3232 break;
3233 case Load:
3234 VISIT(c, expr, e->v.Subscript.value);
3235 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3236 break;
3237 case AugStore:
3238 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3239 break;
3240 case Store:
3241 VISIT(c, expr, e->v.Subscript.value);
3242 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3243 break;
3244 case Del:
3245 VISIT(c, expr, e->v.Subscript.value);
3246 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3247 break;
3248 case Param:
3249 default:
3250 PyErr_SetString(PyExc_SystemError,
3251 "param invalid in subscript expression");
3252 return 0;
3253 }
3254 break;
3255 case Starred_kind:
3256 switch (e->v.Starred.ctx) {
3257 case Store:
3258 /* In all legitimate cases, the Starred node was already replaced
3259 * by compiler_list/compiler_tuple. XXX: is that okay? */
3260 return compiler_error(c,
3261 "starred assignment target must be in a list or tuple");
3262 default:
3263 return compiler_error(c,
3264 "can use starred expression only as assignment target");
3265 }
3266 break;
3267 case Name_kind:
3268 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3269 /* child nodes of List and Tuple will have expr_context set */
3270 case List_kind:
3271 return compiler_list(c, e);
3272 case Tuple_kind:
3273 return compiler_tuple(c, e);
3274 }
3275 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276}
3277
3278static int
3279compiler_augassign(struct compiler *c, stmt_ty s)
3280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 expr_ty e = s->v.AugAssign.target;
3282 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 switch (e->kind) {
3287 case Attribute_kind:
3288 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3289 AugLoad, e->lineno, e->col_offset, c->c_arena);
3290 if (auge == NULL)
3291 return 0;
3292 VISIT(c, expr, auge);
3293 VISIT(c, expr, s->v.AugAssign.value);
3294 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3295 auge->v.Attribute.ctx = AugStore;
3296 VISIT(c, expr, auge);
3297 break;
3298 case Subscript_kind:
3299 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3300 AugLoad, e->lineno, e->col_offset, c->c_arena);
3301 if (auge == NULL)
3302 return 0;
3303 VISIT(c, expr, auge);
3304 VISIT(c, expr, s->v.AugAssign.value);
3305 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3306 auge->v.Subscript.ctx = AugStore;
3307 VISIT(c, expr, auge);
3308 break;
3309 case Name_kind:
3310 if (!compiler_nameop(c, e->v.Name.id, Load))
3311 return 0;
3312 VISIT(c, expr, s->v.AugAssign.value);
3313 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3314 return compiler_nameop(c, e->v.Name.id, Store);
3315 default:
3316 PyErr_Format(PyExc_SystemError,
3317 "invalid node type (%d) for augmented assignment",
3318 e->kind);
3319 return 0;
3320 }
3321 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322}
3323
3324static int
3325compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 struct fblockinfo *f;
3328 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3329 PyErr_SetString(PyExc_SystemError,
3330 "too many statically nested blocks");
3331 return 0;
3332 }
3333 f = &c->u->u_fblock[c->u->u_nfblocks++];
3334 f->fb_type = t;
3335 f->fb_block = b;
3336 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337}
3338
3339static void
3340compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 struct compiler_unit *u = c->u;
3343 assert(u->u_nfblocks > 0);
3344 u->u_nfblocks--;
3345 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3346 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347}
3348
Thomas Wouters89f507f2006-12-13 04:49:30 +00003349static int
3350compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 int i;
3352 struct compiler_unit *u = c->u;
3353 for (i = 0; i < u->u_nfblocks; ++i) {
3354 if (u->u_fblock[i].fb_type == LOOP)
3355 return 1;
3356 }
3357 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003358}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359/* Raises a SyntaxError and returns 0.
3360 If something goes wrong, a different exception may be raised.
3361*/
3362
3363static int
3364compiler_error(struct compiler *c, const char *errstr)
3365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 PyObject *loc;
3367 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3370 if (!loc) {
3371 Py_INCREF(Py_None);
3372 loc = Py_None;
3373 }
3374 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3375 Py_None, loc);
3376 if (!u)
3377 goto exit;
3378 v = Py_BuildValue("(zO)", errstr, u);
3379 if (!v)
3380 goto exit;
3381 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 Py_DECREF(loc);
3384 Py_XDECREF(u);
3385 Py_XDECREF(v);
3386 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387}
3388
3389static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390compiler_handle_subscr(struct compiler *c, const char *kind,
3391 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 /* XXX this code is duplicated */
3396 switch (ctx) {
3397 case AugLoad: /* fall through to Load */
3398 case Load: op = BINARY_SUBSCR; break;
3399 case AugStore:/* fall through to Store */
3400 case Store: op = STORE_SUBSCR; break;
3401 case Del: op = DELETE_SUBSCR; break;
3402 case Param:
3403 PyErr_Format(PyExc_SystemError,
3404 "invalid %s kind %d in subscript\n",
3405 kind, ctx);
3406 return 0;
3407 }
3408 if (ctx == AugLoad) {
3409 ADDOP_I(c, DUP_TOPX, 2);
3410 }
3411 else if (ctx == AugStore) {
3412 ADDOP(c, ROT_THREE);
3413 }
3414 ADDOP(c, op);
3415 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003416}
3417
3418static int
3419compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 int n = 2;
3422 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 /* only handles the cases where BUILD_SLICE is emitted */
3425 if (s->v.Slice.lower) {
3426 VISIT(c, expr, s->v.Slice.lower);
3427 }
3428 else {
3429 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3430 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 if (s->v.Slice.upper) {
3433 VISIT(c, expr, s->v.Slice.upper);
3434 }
3435 else {
3436 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3437 }
3438
3439 if (s->v.Slice.step) {
3440 n++;
3441 VISIT(c, expr, s->v.Slice.step);
3442 }
3443 ADDOP_I(c, BUILD_SLICE, n);
3444 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003445}
3446
3447static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3449 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 switch (s->kind) {
3452 case Slice_kind:
3453 return compiler_slice(c, s, ctx);
3454 case Index_kind:
3455 VISIT(c, expr, s->v.Index.value);
3456 break;
3457 case ExtSlice_kind:
3458 default:
3459 PyErr_SetString(PyExc_SystemError,
3460 "extended slice invalid in nested slice");
3461 return 0;
3462 }
3463 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003464}
3465
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466static int
3467compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 char * kindname = NULL;
3470 switch (s->kind) {
3471 case Index_kind:
3472 kindname = "index";
3473 if (ctx != AugStore) {
3474 VISIT(c, expr, s->v.Index.value);
3475 }
3476 break;
3477 case Slice_kind:
3478 kindname = "slice";
3479 if (ctx != AugStore) {
3480 if (!compiler_slice(c, s, ctx))
3481 return 0;
3482 }
3483 break;
3484 case ExtSlice_kind:
3485 kindname = "extended slice";
3486 if (ctx != AugStore) {
3487 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3488 for (i = 0; i < n; i++) {
3489 slice_ty sub = (slice_ty)asdl_seq_GET(
3490 s->v.ExtSlice.dims, i);
3491 if (!compiler_visit_nested_slice(c, sub, ctx))
3492 return 0;
3493 }
3494 ADDOP_I(c, BUILD_TUPLE, n);
3495 }
3496 break;
3497 default:
3498 PyErr_Format(PyExc_SystemError,
3499 "invalid subscript kind %d", s->kind);
3500 return 0;
3501 }
3502 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503}
3504
Thomas Wouters89f507f2006-12-13 04:49:30 +00003505/* End of the compiler section, beginning of the assembler section */
3506
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507/* do depth-first search of basic block graph, starting with block.
3508 post records the block indices in post-order.
3509
3510 XXX must handle implicit jumps from one block to next
3511*/
3512
Thomas Wouters89f507f2006-12-13 04:49:30 +00003513struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 PyObject *a_bytecode; /* string containing bytecode */
3515 int a_offset; /* offset into bytecode */
3516 int a_nblocks; /* number of reachable blocks */
3517 basicblock **a_postorder; /* list of blocks in dfs postorder */
3518 PyObject *a_lnotab; /* string containing lnotab */
3519 int a_lnotab_off; /* offset into lnotab */
3520 int a_lineno; /* last lineno of emitted instruction */
3521 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003522};
3523
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524static void
3525dfs(struct compiler *c, basicblock *b, struct assembler *a)
3526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 int i;
3528 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 if (b->b_seen)
3531 return;
3532 b->b_seen = 1;
3533 if (b->b_next != NULL)
3534 dfs(c, b->b_next, a);
3535 for (i = 0; i < b->b_iused; i++) {
3536 instr = &b->b_instr[i];
3537 if (instr->i_jrel || instr->i_jabs)
3538 dfs(c, instr->i_target, a);
3539 }
3540 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541}
3542
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003543static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 int i, target_depth;
3547 struct instr *instr;
3548 if (b->b_seen || b->b_startdepth >= depth)
3549 return maxdepth;
3550 b->b_seen = 1;
3551 b->b_startdepth = depth;
3552 for (i = 0; i < b->b_iused; i++) {
3553 instr = &b->b_instr[i];
3554 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3555 if (depth > maxdepth)
3556 maxdepth = depth;
3557 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3558 if (instr->i_jrel || instr->i_jabs) {
3559 target_depth = depth;
3560 if (instr->i_opcode == FOR_ITER) {
3561 target_depth = depth-2;
3562 } else if (instr->i_opcode == SETUP_FINALLY ||
3563 instr->i_opcode == SETUP_EXCEPT) {
3564 target_depth = depth+3;
3565 if (target_depth > maxdepth)
3566 maxdepth = target_depth;
3567 }
3568 maxdepth = stackdepth_walk(c, instr->i_target,
3569 target_depth, maxdepth);
3570 if (instr->i_opcode == JUMP_ABSOLUTE ||
3571 instr->i_opcode == JUMP_FORWARD) {
3572 goto out; /* remaining code is dead */
3573 }
3574 }
3575 }
3576 if (b->b_next)
3577 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 b->b_seen = 0;
3580 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581}
3582
3583/* Find the flow path that needs the largest stack. We assume that
3584 * cycles in the flow graph have no net effect on the stack depth.
3585 */
3586static int
3587stackdepth(struct compiler *c)
3588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 basicblock *b, *entryblock;
3590 entryblock = NULL;
3591 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3592 b->b_seen = 0;
3593 b->b_startdepth = INT_MIN;
3594 entryblock = b;
3595 }
3596 if (!entryblock)
3597 return 0;
3598 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599}
3600
3601static int
3602assemble_init(struct assembler *a, int nblocks, int firstlineno)
3603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 memset(a, 0, sizeof(struct assembler));
3605 a->a_lineno = firstlineno;
3606 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3607 if (!a->a_bytecode)
3608 return 0;
3609 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3610 if (!a->a_lnotab)
3611 return 0;
3612 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3613 PyErr_NoMemory();
3614 return 0;
3615 }
3616 a->a_postorder = (basicblock **)PyObject_Malloc(
3617 sizeof(basicblock *) * nblocks);
3618 if (!a->a_postorder) {
3619 PyErr_NoMemory();
3620 return 0;
3621 }
3622 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623}
3624
3625static void
3626assemble_free(struct assembler *a)
3627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 Py_XDECREF(a->a_bytecode);
3629 Py_XDECREF(a->a_lnotab);
3630 if (a->a_postorder)
3631 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632}
3633
3634/* Return the size of a basic block in bytes. */
3635
3636static int
3637instrsize(struct instr *instr)
3638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 if (!instr->i_hasarg)
3640 return 1; /* 1 byte for the opcode*/
3641 if (instr->i_oparg > 0xffff)
3642 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3643 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644}
3645
3646static int
3647blocksize(basicblock *b)
3648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 int i;
3650 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 for (i = 0; i < b->b_iused; i++)
3653 size += instrsize(&b->b_instr[i]);
3654 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655}
3656
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003657/* Appends a pair to the end of the line number table, a_lnotab, representing
3658 the instruction's bytecode offset and line number. See
3659 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003660
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003661static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 int d_bytecode, d_lineno;
3665 int len;
3666 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 d_bytecode = a->a_offset - a->a_lineno_off;
3669 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 assert(d_bytecode >= 0);
3672 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 if(d_bytecode == 0 && d_lineno == 0)
3675 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 if (d_bytecode > 255) {
3678 int j, nbytes, ncodes = d_bytecode / 255;
3679 nbytes = a->a_lnotab_off + 2 * ncodes;
3680 len = PyBytes_GET_SIZE(a->a_lnotab);
3681 if (nbytes >= len) {
3682 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3683 len = nbytes;
3684 else if (len <= INT_MAX / 2)
3685 len *= 2;
3686 else {
3687 PyErr_NoMemory();
3688 return 0;
3689 }
3690 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3691 return 0;
3692 }
3693 lnotab = (unsigned char *)
3694 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3695 for (j = 0; j < ncodes; j++) {
3696 *lnotab++ = 255;
3697 *lnotab++ = 0;
3698 }
3699 d_bytecode -= ncodes * 255;
3700 a->a_lnotab_off += ncodes * 2;
3701 }
3702 assert(d_bytecode <= 255);
3703 if (d_lineno > 255) {
3704 int j, nbytes, ncodes = d_lineno / 255;
3705 nbytes = a->a_lnotab_off + 2 * ncodes;
3706 len = PyBytes_GET_SIZE(a->a_lnotab);
3707 if (nbytes >= len) {
3708 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3709 len = nbytes;
3710 else if (len <= INT_MAX / 2)
3711 len *= 2;
3712 else {
3713 PyErr_NoMemory();
3714 return 0;
3715 }
3716 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3717 return 0;
3718 }
3719 lnotab = (unsigned char *)
3720 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3721 *lnotab++ = d_bytecode;
3722 *lnotab++ = 255;
3723 d_bytecode = 0;
3724 for (j = 1; j < ncodes; j++) {
3725 *lnotab++ = 0;
3726 *lnotab++ = 255;
3727 }
3728 d_lineno -= ncodes * 255;
3729 a->a_lnotab_off += ncodes * 2;
3730 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 len = PyBytes_GET_SIZE(a->a_lnotab);
3733 if (a->a_lnotab_off + 2 >= len) {
3734 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3735 return 0;
3736 }
3737 lnotab = (unsigned char *)
3738 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 a->a_lnotab_off += 2;
3741 if (d_bytecode) {
3742 *lnotab++ = d_bytecode;
3743 *lnotab++ = d_lineno;
3744 }
3745 else { /* First line of a block; def stmt, etc. */
3746 *lnotab++ = 0;
3747 *lnotab++ = d_lineno;
3748 }
3749 a->a_lineno = i->i_lineno;
3750 a->a_lineno_off = a->a_offset;
3751 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003752}
3753
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754/* assemble_emit()
3755 Extend the bytecode with a new instruction.
3756 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003757*/
3758
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003759static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 int size, arg = 0, ext = 0;
3763 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3764 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 size = instrsize(i);
3767 if (i->i_hasarg) {
3768 arg = i->i_oparg;
3769 ext = arg >> 16;
3770 }
3771 if (i->i_lineno && !assemble_lnotab(a, i))
3772 return 0;
3773 if (a->a_offset + size >= len) {
3774 if (len > PY_SSIZE_T_MAX / 2)
3775 return 0;
3776 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3777 return 0;
3778 }
3779 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3780 a->a_offset += size;
3781 if (size == 6) {
3782 assert(i->i_hasarg);
3783 *code++ = (char)EXTENDED_ARG;
3784 *code++ = ext & 0xff;
3785 *code++ = ext >> 8;
3786 arg &= 0xffff;
3787 }
3788 *code++ = i->i_opcode;
3789 if (i->i_hasarg) {
3790 assert(size == 3 || size == 6);
3791 *code++ = arg & 0xff;
3792 *code++ = arg >> 8;
3793 }
3794 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003795}
3796
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003797static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 basicblock *b;
3801 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3802 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 /* Compute the size of each block and fixup jump args.
3805 Replace block pointer with position in bytecode. */
3806 do {
3807 totsize = 0;
3808 for (i = a->a_nblocks - 1; i >= 0; i--) {
3809 b = a->a_postorder[i];
3810 bsize = blocksize(b);
3811 b->b_offset = totsize;
3812 totsize += bsize;
3813 }
3814 last_extended_arg_count = extended_arg_count;
3815 extended_arg_count = 0;
3816 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3817 bsize = b->b_offset;
3818 for (i = 0; i < b->b_iused; i++) {
3819 struct instr *instr = &b->b_instr[i];
3820 /* Relative jumps are computed relative to
3821 the instruction pointer after fetching
3822 the jump instruction.
3823 */
3824 bsize += instrsize(instr);
3825 if (instr->i_jabs)
3826 instr->i_oparg = instr->i_target->b_offset;
3827 else if (instr->i_jrel) {
3828 int delta = instr->i_target->b_offset - bsize;
3829 instr->i_oparg = delta;
3830 }
3831 else
3832 continue;
3833 if (instr->i_oparg > 0xffff)
3834 extended_arg_count++;
3835 }
3836 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 /* XXX: This is an awful hack that could hurt performance, but
3839 on the bright side it should work until we come up
3840 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 The issue is that in the first loop blocksize() is called
3843 which calls instrsize() which requires i_oparg be set
3844 appropriately. There is a bootstrap problem because
3845 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 So we loop until we stop seeing new EXTENDED_ARGs.
3848 The only EXTENDED_ARGs that could be popping up are
3849 ones in jump instructions. So this should converge
3850 fairly quickly.
3851 */
3852 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003853}
3854
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003855static PyObject *
3856dict_keys_inorder(PyObject *dict, int offset)
3857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 PyObject *tuple, *k, *v;
3859 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 tuple = PyTuple_New(size);
3862 if (tuple == NULL)
3863 return NULL;
3864 while (PyDict_Next(dict, &pos, &k, &v)) {
3865 i = PyLong_AS_LONG(v);
3866 /* The keys of the dictionary are tuples. (see compiler_add_o)
3867 The object we want is always first, though. */
3868 k = PyTuple_GET_ITEM(k, 0);
3869 Py_INCREF(k);
3870 assert((i - offset) < size);
3871 assert((i - offset) >= 0);
3872 PyTuple_SET_ITEM(tuple, i - offset, k);
3873 }
3874 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003875}
3876
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003877static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 PySTEntryObject *ste = c->u->u_ste;
3881 int flags = 0, n;
3882 if (ste->ste_type != ModuleBlock)
3883 flags |= CO_NEWLOCALS;
3884 if (ste->ste_type == FunctionBlock) {
3885 if (!ste->ste_unoptimized)
3886 flags |= CO_OPTIMIZED;
3887 if (ste->ste_nested)
3888 flags |= CO_NESTED;
3889 if (ste->ste_generator)
3890 flags |= CO_GENERATOR;
3891 if (ste->ste_varargs)
3892 flags |= CO_VARARGS;
3893 if (ste->ste_varkeywords)
3894 flags |= CO_VARKEYWORDS;
3895 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 /* (Only) inherit compilerflags in PyCF_MASK */
3898 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 n = PyDict_Size(c->u->u_freevars);
3901 if (n < 0)
3902 return -1;
3903 if (n == 0) {
3904 n = PyDict_Size(c->u->u_cellvars);
3905 if (n < 0)
3906 return -1;
3907 if (n == 0) {
3908 flags |= CO_NOFREE;
3909 }
3910 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003913}
3914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915static PyCodeObject *
3916makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 PyObject *tmp;
3919 PyCodeObject *co = NULL;
3920 PyObject *consts = NULL;
3921 PyObject *names = NULL;
3922 PyObject *varnames = NULL;
3923 PyObject *filename = NULL;
3924 PyObject *name = NULL;
3925 PyObject *freevars = NULL;
3926 PyObject *cellvars = NULL;
3927 PyObject *bytecode = NULL;
3928 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 tmp = dict_keys_inorder(c->u->u_consts, 0);
3931 if (!tmp)
3932 goto error;
3933 consts = PySequence_List(tmp); /* optimize_code requires a list */
3934 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 names = dict_keys_inorder(c->u->u_names, 0);
3937 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3938 if (!consts || !names || !varnames)
3939 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3942 if (!cellvars)
3943 goto error;
3944 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3945 if (!freevars)
3946 goto error;
Victor Stinner0fe25a42010-06-17 23:08:50 +00003947 filename = PyUnicode_FromString(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 if (!filename)
3949 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 nlocals = PyDict_Size(c->u->u_varnames);
3952 flags = compute_code_flags(c);
3953 if (flags < 0)
3954 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3957 if (!bytecode)
3958 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3961 if (!tmp)
3962 goto error;
3963 Py_DECREF(consts);
3964 consts = tmp;
3965
3966 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3967 nlocals, stackdepth(c), flags,
3968 bytecode, consts, names, varnames,
3969 freevars, cellvars,
3970 filename, c->u->u_name,
3971 c->u->u_firstlineno,
3972 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003973 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 Py_XDECREF(consts);
3975 Py_XDECREF(names);
3976 Py_XDECREF(varnames);
3977 Py_XDECREF(filename);
3978 Py_XDECREF(name);
3979 Py_XDECREF(freevars);
3980 Py_XDECREF(cellvars);
3981 Py_XDECREF(bytecode);
3982 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003983}
3984
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003985
3986/* For debugging purposes only */
3987#if 0
3988static void
3989dump_instr(const struct instr *i)
3990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 const char *jrel = i->i_jrel ? "jrel " : "";
3992 const char *jabs = i->i_jabs ? "jabs " : "";
3993 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 *arg = '\0';
3996 if (i->i_hasarg)
3997 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4000 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004001}
4002
4003static void
4004dump_basicblock(const basicblock *b)
4005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 const char *seen = b->b_seen ? "seen " : "";
4007 const char *b_return = b->b_return ? "return " : "";
4008 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4009 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4010 if (b->b_instr) {
4011 int i;
4012 for (i = 0; i < b->b_iused; i++) {
4013 fprintf(stderr, " [%02d] ", i);
4014 dump_instr(b->b_instr + i);
4015 }
4016 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004017}
4018#endif
4019
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020static PyCodeObject *
4021assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 basicblock *b, *entryblock;
4024 struct assembler a;
4025 int i, j, nblocks;
4026 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 /* Make sure every block that falls off the end returns None.
4029 XXX NEXT_BLOCK() isn't quite right, because if the last
4030 block ends with a jump or return b_next shouldn't set.
4031 */
4032 if (!c->u->u_curblock->b_return) {
4033 NEXT_BLOCK(c);
4034 if (addNone)
4035 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4036 ADDOP(c, RETURN_VALUE);
4037 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 nblocks = 0;
4040 entryblock = NULL;
4041 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4042 nblocks++;
4043 entryblock = b;
4044 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 /* Set firstlineno if it wasn't explicitly set. */
4047 if (!c->u->u_firstlineno) {
4048 if (entryblock && entryblock->b_instr)
4049 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4050 else
4051 c->u->u_firstlineno = 1;
4052 }
4053 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4054 goto error;
4055 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 /* Can't modify the bytecode after computing jump offsets. */
4058 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 /* Emit code in reverse postorder from dfs. */
4061 for (i = a.a_nblocks - 1; i >= 0; i--) {
4062 b = a.a_postorder[i];
4063 for (j = 0; j < b->b_iused; j++)
4064 if (!assemble_emit(&a, &b->b_instr[j]))
4065 goto error;
4066 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4069 goto error;
4070 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4071 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004074 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004075 assemble_free(&a);
4076 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004077}