blob: 01b9fe049f67c4264df988c10af188dff9c9eeb0 [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 Pitrouc83ea132010-05-09 14:46:46 +00008 * 2. Builds a symbol table. See symtable.c.
Neal Norwitzf733a012006-10-29 18:30:10 +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 Pitrouc83ea132010-05-09 14:46:46 +000011 * this file.
Neal Norwitzf733a012006-10-29 18:30:10 +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
Neal Norwitzf733a012006-10-29 18:30:10 +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
Alexandre Vassalottib6465472010-01-11 22:36:12 +000042#define COMP_GENEXP 0
43#define COMP_SETCOMP 1
44#define COMP_DICTCOMP 2
45
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046struct instr {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000047 unsigned i_jabs : 1;
48 unsigned i_jrel : 1;
49 unsigned i_hasarg : 1;
50 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000057 /* Each basicblock in a compilation unit is linked via b_list in the
58 reverse order that the block are allocated. b_list points to the next
59 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000060 struct basicblock_ *b_list;
61 /* number of instructions used */
62 int b_iused;
63 /* length of instruction array (b_instr) */
64 int b_ialloc;
65 /* pointer to an array of instructions, initially NULL */
66 struct instr *b_instr;
67 /* If b_next is non-NULL, it is a pointer to the next
68 block reached by normal control flow. */
69 struct basicblock_ *b_next;
70 /* b_seen is used to perform a DFS of basicblocks. */
71 unsigned b_seen : 1;
72 /* b_return is true if a RETURN_VALUE opcode is inserted. */
73 unsigned b_return : 1;
74 /* depth of stack upon entry of block, computed by stackdepth() */
75 int b_startdepth;
76 /* instruction offset for block, computed by assemble_jump_offsets() */
77 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078} basicblock;
79
80/* fblockinfo tracks the current frame block.
81
Jeremy Hyltone9357b22006-03-01 15:47:05 +000082A frame block is used to handle loops, try/except, and try/finally.
83It's called a frame block to distinguish it from a basic block in the
84compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085*/
86
87enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
88
89struct fblockinfo {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000090 enum fblocktype fb_type;
91 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000092};
93
94/* The following items change on entry and exit of code blocks.
95 They must be saved and restored when returning to a block.
96*/
97struct compiler_unit {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000098 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000100 PyObject *u_name;
101 /* The following fields are dicts that map objects to
102 the index of them in co_XXX. The index is used as
103 the argument for opcodes that refer to those collections.
104 */
105 PyObject *u_consts; /* all constants */
106 PyObject *u_names; /* all names */
107 PyObject *u_varnames; /* local variables */
108 PyObject *u_cellvars; /* cell variables */
109 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000111 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000112
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000113 int u_argcount; /* number of arguments for block */
114 /* Pointer to the most recently allocated block. By following b_list
115 members, you can reach all early allocated blocks. */
116 basicblock *u_blocks;
117 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000119 int u_nfblocks;
120 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000122 int u_firstlineno; /* the first lineno of the block */
123 int u_lineno; /* the lineno for the current stmt */
124 bool u_lineno_set; /* boolean to indicate whether instr
125 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126};
127
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000128/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000130The u pointer points to the current compilation unit, while units
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000131for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000132managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133*/
134
135struct compiler {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000136 const char *c_filename;
137 struct symtable *c_st;
138 PyFutureFeatures *c_future; /* pointer to module's __future__ */
139 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 int c_interactive; /* true if in interactive mode */
142 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000144 struct compiler_unit *u; /* compiler state for current block */
145 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
146 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147};
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149static int compiler_enter_scope(struct compiler *, identifier, void *, int);
150static void compiler_free(struct compiler *);
151static basicblock *compiler_new_block(struct compiler *);
152static int compiler_next_instr(struct compiler *, basicblock *);
153static int compiler_addop(struct compiler *, int);
154static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
155static int compiler_addop_i(struct compiler *, int, int);
156static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157static basicblock *compiler_use_new_block(struct compiler *);
158static int compiler_error(struct compiler *, const char *);
159static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
160
161static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
162static int compiler_visit_stmt(struct compiler *, stmt_ty);
163static int compiler_visit_keyword(struct compiler *, keyword_ty);
164static int compiler_visit_expr(struct compiler *, expr_ty);
165static int compiler_augassign(struct compiler *, stmt_ty);
166static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000167 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168
169static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000170 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000173/* Returns true if there is a loop on the fblock stack. */
174static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175
176static int inplace_binop(struct compiler *, operator_ty);
177static int expr_constant(expr_ty e);
178
Guido van Rossumc2e20742006-02-27 22:32:47 +0000179static int compiler_with(struct compiler *, stmt_ty);
180
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181static PyCodeObject *assemble(struct compiler *, int addNone);
182static PyObject *__doc__;
183
Larry Hastings402b73f2010-03-25 00:54:54 +0000184#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
185
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000187_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000188{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000189 /* Name mangling: __private becomes _classname__private.
190 This is independent from how the name is used. */
191 const char *p, *name = PyString_AsString(ident);
192 char *buffer;
193 size_t nlen, plen;
194 if (privateobj == NULL || !PyString_Check(privateobj) ||
195 name == NULL || name[0] != '_' || name[1] != '_') {
196 Py_INCREF(ident);
197 return ident;
198 }
199 p = PyString_AsString(privateobj);
200 nlen = strlen(name);
201 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000202
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000203 The only time a name with a dot can occur is when
204 we are compiling an import statement that has a
205 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000206
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000207 TODO(jhylton): Decide whether we want to support
208 mangling of the module name, e.g. __M.X.
209 */
210 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
211 || strchr(name, '.')) {
212 Py_INCREF(ident);
213 return ident; /* Don't mangle __whatever__ */
214 }
215 /* Strip leading underscores from class name */
216 while (*p == '_')
217 p++;
218 if (*p == '\0') {
219 Py_INCREF(ident);
220 return ident; /* Don't mangle if class is just underscores */
221 }
222 plen = strlen(p);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000223
Antoine Pitrou022db592013-04-06 21:21:04 +0200224 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
225 PyErr_SetString(PyExc_OverflowError,
226 "private identifier too large to be mangled");
227 return NULL;
228 }
Gregory P. Smith9d534572008-06-11 07:41:16 +0000229
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000230 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
231 if (!ident)
232 return 0;
233 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
234 buffer = PyString_AS_STRING(ident);
235 buffer[0] = '_';
236 strncpy(buffer+1, p, plen);
237 strcpy(buffer+1+plen, name);
238 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000239}
240
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241static int
242compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000243{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000244 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000245
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 c->c_stack = PyList_New(0);
247 if (!c->c_stack)
248 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000249
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251}
252
253PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000254PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000255 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 struct compiler c;
258 PyCodeObject *co = NULL;
259 PyCompilerFlags local_flags;
260 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000262 if (!__doc__) {
263 __doc__ = PyString_InternFromString("__doc__");
264 if (!__doc__)
265 return NULL;
266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 if (!compiler_init(&c))
269 return NULL;
270 c.c_filename = filename;
271 c.c_arena = arena;
272 c.c_future = PyFuture_FromAST(mod, filename);
273 if (c.c_future == NULL)
274 goto finally;
275 if (!flags) {
276 local_flags.cf_flags = 0;
277 flags = &local_flags;
278 }
279 merged = c.c_future->ff_features | flags->cf_flags;
280 c.c_future->ff_features = merged;
281 flags->cf_flags = merged;
282 c.c_flags = flags;
283 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000284
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000285 c.c_st = PySymtable_Build(mod, filename, c.c_future);
286 if (c.c_st == NULL) {
287 if (!PyErr_Occurred())
288 PyErr_SetString(PyExc_SystemError, "no symtable");
289 goto finally;
290 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293
Thomas Wouters1175c432006-02-27 22:49:54 +0000294 finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000295 compiler_free(&c);
296 assert(co || PyErr_Occurred());
297 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298}
299
300PyCodeObject *
301PyNode_Compile(struct _node *n, const char *filename)
302{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000303 PyCodeObject *co = NULL;
304 mod_ty mod;
305 PyArena *arena = PyArena_New();
306 if (!arena)
307 return NULL;
308 mod = PyAST_FromNode(n, NULL, filename, arena);
309 if (mod)
310 co = PyAST_Compile(mod, filename, NULL, arena);
311 PyArena_Free(arena);
312 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000313}
314
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000315static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000317{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000318 if (c->c_st)
319 PySymtable_Free(c->c_st);
320 if (c->c_future)
321 PyObject_Free(c->c_future);
322 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000323}
324
Guido van Rossum79f25d91997-04-29 20:08:16 +0000325static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000327{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 Py_ssize_t i, n;
329 PyObject *v, *k;
330 PyObject *dict = PyDict_New();
331 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000332
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000333 n = PyList_Size(list);
334 for (i = 0; i < n; i++) {
335 v = PyInt_FromLong(i);
336 if (!v) {
337 Py_DECREF(dict);
338 return NULL;
339 }
340 k = PyList_GET_ITEM(list, i);
341 k = PyTuple_Pack(2, k, k->ob_type);
342 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
343 Py_XDECREF(k);
344 Py_DECREF(v);
345 Py_DECREF(dict);
346 return NULL;
347 }
348 Py_DECREF(k);
349 Py_DECREF(v);
350 }
351 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352}
353
354/* Return new dict containing names from src that match scope(s).
355
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000356src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000357either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000358values are integers, starting at offset and increasing by one for
359each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360*/
361
362static PyObject *
363dictbytype(PyObject *src, int scope_type, int flag, int offset)
364{
Meador Inge0e3755e2012-07-18 17:48:34 -0500365 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000366 PyObject *k, *v, *dest = PyDict_New();
Meador Inge6642d1f2012-07-18 14:09:04 -0500367 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000369 assert(offset >= 0);
370 if (dest == NULL)
371 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Meador Inge6642d1f2012-07-18 14:09:04 -0500373 /* Sort the keys so that we have a deterministic order on the indexes
374 saved in the returned dictionary. These indexes are used as indexes
375 into the free and cell var storage. Therefore if they aren't
376 deterministic, then the generated bytecode is not deterministic.
377 */
378 sorted_keys = PyDict_Keys(src);
379 if (sorted_keys == NULL)
380 return NULL;
381 if (PyList_Sort(sorted_keys) != 0) {
382 Py_DECREF(sorted_keys);
383 return NULL;
384 }
Meador Ingeb8a56902012-07-18 16:32:37 -0500385 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge6642d1f2012-07-18 14:09:04 -0500386
387 for (key_i = 0; key_i < num_keys; key_i++) {
388 k = PyList_GET_ITEM(sorted_keys, key_i);
389 v = PyDict_GetItem(src, k);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000390 /* XXX this should probably be a macro in symtable.h */
391 assert(PyInt_Check(v));
392 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000394 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
395 PyObject *tuple, *item = PyInt_FromLong(i);
396 if (item == NULL) {
Meador Inge6642d1f2012-07-18 14:09:04 -0500397 Py_DECREF(sorted_keys);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000398 Py_DECREF(dest);
399 return NULL;
400 }
401 i++;
402 tuple = PyTuple_Pack(2, k, k->ob_type);
403 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge6642d1f2012-07-18 14:09:04 -0500404 Py_DECREF(sorted_keys);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000405 Py_DECREF(item);
406 Py_DECREF(dest);
407 Py_XDECREF(tuple);
408 return NULL;
409 }
410 Py_DECREF(item);
411 Py_DECREF(tuple);
412 }
413 }
Meador Inge6642d1f2012-07-18 14:09:04 -0500414 Py_DECREF(sorted_keys);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000415 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000416}
417
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418static void
419compiler_unit_check(struct compiler_unit *u)
420{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000421 basicblock *block;
422 for (block = u->u_blocks; block != NULL; block = block->b_list) {
423 assert((void *)block != (void *)0xcbcbcbcb);
424 assert((void *)block != (void *)0xfbfbfbfb);
425 assert((void *)block != (void *)0xdbdbdbdb);
426 if (block->b_instr != NULL) {
427 assert(block->b_ialloc > 0);
428 assert(block->b_iused > 0);
429 assert(block->b_ialloc >= block->b_iused);
430 }
431 else {
432 assert (block->b_iused == 0);
433 assert (block->b_ialloc == 0);
434 }
435 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436}
437
438static void
439compiler_unit_free(struct compiler_unit *u)
440{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000442
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000443 compiler_unit_check(u);
444 b = u->u_blocks;
445 while (b != NULL) {
446 if (b->b_instr)
447 PyObject_Free((void *)b->b_instr);
448 next = b->b_list;
449 PyObject_Free((void *)b);
450 b = next;
451 }
452 Py_CLEAR(u->u_ste);
453 Py_CLEAR(u->u_name);
454 Py_CLEAR(u->u_consts);
455 Py_CLEAR(u->u_names);
456 Py_CLEAR(u->u_varnames);
457 Py_CLEAR(u->u_freevars);
458 Py_CLEAR(u->u_cellvars);
459 Py_CLEAR(u->u_private);
460 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461}
462
463static int
464compiler_enter_scope(struct compiler *c, identifier name, void *key,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000467 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000469 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
470 struct compiler_unit));
471 if (!u) {
472 PyErr_NoMemory();
473 return 0;
474 }
475 memset(u, 0, sizeof(struct compiler_unit));
476 u->u_argcount = 0;
477 u->u_ste = PySymtable_Lookup(c->c_st, key);
478 if (!u->u_ste) {
479 compiler_unit_free(u);
480 return 0;
481 }
482 Py_INCREF(name);
483 u->u_name = name;
484 u->u_varnames = list2dict(u->u_ste->ste_varnames);
485 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
486 if (!u->u_varnames || !u->u_cellvars) {
487 compiler_unit_free(u);
488 return 0;
489 }
Neal Norwitzd12bd012006-07-21 07:59:47 +0000490
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000491 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
492 PyDict_Size(u->u_cellvars));
493 if (!u->u_freevars) {
494 compiler_unit_free(u);
495 return 0;
496 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 u->u_blocks = NULL;
499 u->u_nfblocks = 0;
500 u->u_firstlineno = lineno;
501 u->u_lineno = 0;
502 u->u_lineno_set = false;
503 u->u_consts = PyDict_New();
504 if (!u->u_consts) {
505 compiler_unit_free(u);
506 return 0;
507 }
508 u->u_names = PyDict_New();
509 if (!u->u_names) {
510 compiler_unit_free(u);
511 return 0;
512 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000513
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000514 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000516 /* Push the old compiler_unit on the stack. */
517 if (c->u) {
518 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
519 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
520 Py_XDECREF(capsule);
521 compiler_unit_free(u);
522 return 0;
523 }
524 Py_DECREF(capsule);
525 u->u_private = c->u->u_private;
526 Py_XINCREF(u->u_private);
527 }
528 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000530 c->c_nestlevel++;
531 if (compiler_use_new_block(c) == NULL)
532 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000534 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535}
536
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000537static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538compiler_exit_scope(struct compiler *c)
539{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000540 int n;
541 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000542
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 c->c_nestlevel--;
544 compiler_unit_free(c->u);
545 /* Restore c->u to the parent unit. */
546 n = PyList_GET_SIZE(c->c_stack) - 1;
547 if (n >= 0) {
548 capsule = PyList_GET_ITEM(c->c_stack, n);
549 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
550 assert(c->u);
551 /* we are deleting from a list so this really shouldn't fail */
552 if (PySequence_DelItem(c->c_stack, n) < 0)
553 Py_FatalError("compiler_exit_scope()");
554 compiler_unit_check(c->u);
555 }
556 else
557 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000558
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559}
560
561/* Allocate a new block and return a pointer to it.
562 Returns NULL on error.
563*/
564
565static basicblock *
566compiler_new_block(struct compiler *c)
567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 basicblock *b;
569 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000570
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000571 u = c->u;
572 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
573 if (b == NULL) {
574 PyErr_NoMemory();
575 return NULL;
576 }
577 memset((void *)b, 0, sizeof(basicblock));
578 /* Extend the singly linked list of blocks with new block. */
579 b->b_list = u->u_blocks;
580 u->u_blocks = b;
581 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000582}
583
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000584static basicblock *
585compiler_use_new_block(struct compiler *c)
586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000587 basicblock *block = compiler_new_block(c);
588 if (block == NULL)
589 return NULL;
590 c->u->u_curblock = block;
591 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000592}
593
594static basicblock *
595compiler_next_block(struct compiler *c)
596{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000597 basicblock *block = compiler_new_block(c);
598 if (block == NULL)
599 return NULL;
600 c->u->u_curblock->b_next = block;
601 c->u->u_curblock = block;
602 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603}
604
605static basicblock *
606compiler_use_next_block(struct compiler *c, basicblock *block)
607{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000608 assert(block != NULL);
609 c->u->u_curblock->b_next = block;
610 c->u->u_curblock = block;
611 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612}
613
614/* Returns the offset of the next instruction in the current block's
615 b_instr array. Resizes the b_instr as necessary.
616 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000617*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618
619static int
620compiler_next_instr(struct compiler *c, basicblock *b)
621{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000622 assert(b != NULL);
623 if (b->b_instr == NULL) {
624 b->b_instr = (struct instr *)PyObject_Malloc(
625 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
626 if (b->b_instr == NULL) {
627 PyErr_NoMemory();
628 return -1;
629 }
630 b->b_ialloc = DEFAULT_BLOCK_SIZE;
631 memset((char *)b->b_instr, 0,
632 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
633 }
634 else if (b->b_iused == b->b_ialloc) {
635 struct instr *tmp;
636 size_t oldsize, newsize;
637 oldsize = b->b_ialloc * sizeof(struct instr);
638 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000639
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000640 if (oldsize > (PY_SIZE_MAX >> 1)) {
641 PyErr_NoMemory();
642 return -1;
643 }
Gregory P. Smith9d534572008-06-11 07:41:16 +0000644
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000645 if (newsize == 0) {
646 PyErr_NoMemory();
647 return -1;
648 }
649 b->b_ialloc <<= 1;
650 tmp = (struct instr *)PyObject_Realloc(
651 (void *)b->b_instr, newsize);
652 if (tmp == NULL) {
653 PyErr_NoMemory();
654 return -1;
655 }
656 b->b_instr = tmp;
657 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
658 }
659 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660}
661
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000662/* Set the i_lineno member of the instruction at offset off if the
663 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000664 already been set. If it has been set, the call has no effect.
665
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000666 The line number is reset in the following cases:
667 - when entering a new scope
668 - on each statement
669 - on each expression that start a new line
670 - before the "except" clause
671 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000672*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000673
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000674static void
675compiler_set_lineno(struct compiler *c, int off)
676{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000677 basicblock *b;
678 if (c->u->u_lineno_set)
679 return;
680 c->u->u_lineno_set = true;
681 b = c->u->u_curblock;
682 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683}
684
685static int
686opcode_stack_effect(int opcode, int oparg)
687{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000688 switch (opcode) {
689 case POP_TOP:
690 return -1;
691 case ROT_TWO:
692 case ROT_THREE:
693 return 0;
694 case DUP_TOP:
695 return 1;
696 case ROT_FOUR:
697 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000698
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000699 case UNARY_POSITIVE:
700 case UNARY_NEGATIVE:
701 case UNARY_NOT:
702 case UNARY_CONVERT:
703 case UNARY_INVERT:
704 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 case SET_ADD:
707 case LIST_APPEND:
708 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000709
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 case MAP_ADD:
711 return -2;
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000712
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000713 case BINARY_POWER:
714 case BINARY_MULTIPLY:
715 case BINARY_DIVIDE:
716 case BINARY_MODULO:
717 case BINARY_ADD:
718 case BINARY_SUBTRACT:
719 case BINARY_SUBSCR:
720 case BINARY_FLOOR_DIVIDE:
721 case BINARY_TRUE_DIVIDE:
722 return -1;
723 case INPLACE_FLOOR_DIVIDE:
724 case INPLACE_TRUE_DIVIDE:
725 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000726
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000727 case SLICE+0:
728 return 0;
729 case SLICE+1:
730 return -1;
731 case SLICE+2:
732 return -1;
733 case SLICE+3:
734 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000736 case STORE_SLICE+0:
737 return -2;
738 case STORE_SLICE+1:
739 return -3;
740 case STORE_SLICE+2:
741 return -3;
742 case STORE_SLICE+3:
743 return -4;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000745 case DELETE_SLICE+0:
746 return -1;
747 case DELETE_SLICE+1:
748 return -2;
749 case DELETE_SLICE+2:
750 return -2;
751 case DELETE_SLICE+3:
752 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000754 case INPLACE_ADD:
755 case INPLACE_SUBTRACT:
756 case INPLACE_MULTIPLY:
757 case INPLACE_DIVIDE:
758 case INPLACE_MODULO:
759 return -1;
760 case STORE_SUBSCR:
761 return -3;
762 case STORE_MAP:
763 return -2;
764 case DELETE_SUBSCR:
765 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000767 case BINARY_LSHIFT:
768 case BINARY_RSHIFT:
769 case BINARY_AND:
770 case BINARY_XOR:
771 case BINARY_OR:
772 return -1;
773 case INPLACE_POWER:
774 return -1;
775 case GET_ITER:
776 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000778 case PRINT_EXPR:
779 return -1;
780 case PRINT_ITEM:
781 return -1;
782 case PRINT_NEWLINE:
783 return 0;
784 case PRINT_ITEM_TO:
785 return -2;
786 case PRINT_NEWLINE_TO:
787 return -1;
788 case INPLACE_LSHIFT:
789 case INPLACE_RSHIFT:
790 case INPLACE_AND:
791 case INPLACE_XOR:
792 case INPLACE_OR:
793 return -1;
794 case BREAK_LOOP:
795 return 0;
796 case SETUP_WITH:
797 return 4;
798 case WITH_CLEANUP:
799 return -1; /* XXX Sometimes more */
800 case LOAD_LOCALS:
801 return 1;
802 case RETURN_VALUE:
803 return -1;
804 case IMPORT_STAR:
805 return -1;
806 case EXEC_STMT:
807 return -3;
808 case YIELD_VALUE:
809 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000810
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 case POP_BLOCK:
812 return 0;
813 case END_FINALLY:
814 return -3; /* or -1 or -2 if no exception occurred or
815 return/break/continue */
816 case BUILD_CLASS:
817 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000818
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000819 case STORE_NAME:
820 return -1;
821 case DELETE_NAME:
822 return 0;
823 case UNPACK_SEQUENCE:
824 return oparg-1;
825 case FOR_ITER:
826 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000828 case STORE_ATTR:
829 return -2;
830 case DELETE_ATTR:
831 return -1;
832 case STORE_GLOBAL:
833 return -1;
834 case DELETE_GLOBAL:
835 return 0;
836 case DUP_TOPX:
837 return oparg;
838 case LOAD_CONST:
839 return 1;
840 case LOAD_NAME:
841 return 1;
842 case BUILD_TUPLE:
843 case BUILD_LIST:
844 case BUILD_SET:
845 return 1-oparg;
846 case BUILD_MAP:
847 return 1;
848 case LOAD_ATTR:
849 return 0;
850 case COMPARE_OP:
851 return -1;
852 case IMPORT_NAME:
853 return -1;
854 case IMPORT_FROM:
855 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000857 case JUMP_FORWARD:
858 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
859 case JUMP_IF_FALSE_OR_POP: /* "" */
860 case JUMP_ABSOLUTE:
861 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000862
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000863 case POP_JUMP_IF_FALSE:
864 case POP_JUMP_IF_TRUE:
865 return -1;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000866
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 case LOAD_GLOBAL:
868 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 case CONTINUE_LOOP:
871 return 0;
872 case SETUP_LOOP:
873 case SETUP_EXCEPT:
874 case SETUP_FINALLY:
875 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000876
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 case LOAD_FAST:
878 return 1;
879 case STORE_FAST:
880 return -1;
881 case DELETE_FAST:
882 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000883
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000884 case RAISE_VARARGS:
885 return -oparg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000886#define NARGS(o) (((o) % 256) + 2*((o) / 256))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000887 case CALL_FUNCTION:
888 return -NARGS(oparg);
889 case CALL_FUNCTION_VAR:
890 case CALL_FUNCTION_KW:
891 return -NARGS(oparg)-1;
892 case CALL_FUNCTION_VAR_KW:
893 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000894#undef NARGS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000895 case MAKE_FUNCTION:
896 return -oparg;
897 case BUILD_SLICE:
898 if (oparg == 3)
899 return -2;
900 else
901 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000903 case MAKE_CLOSURE:
904 return -oparg-1;
905 case LOAD_CLOSURE:
906 return 1;
907 case LOAD_DEREF:
908 return 1;
909 case STORE_DEREF:
910 return -1;
911 default:
912 fprintf(stderr, "opcode = %d\n", opcode);
913 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000915 }
916 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917}
918
919/* Add an opcode with no argument.
920 Returns 0 on failure, 1 on success.
921*/
922
923static int
924compiler_addop(struct compiler *c, int opcode)
925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000926 basicblock *b;
927 struct instr *i;
928 int off;
929 off = compiler_next_instr(c, c->u->u_curblock);
930 if (off < 0)
931 return 0;
932 b = c->u->u_curblock;
933 i = &b->b_instr[off];
934 i->i_opcode = opcode;
935 i->i_hasarg = 0;
936 if (opcode == RETURN_VALUE)
937 b->b_return = 1;
938 compiler_set_lineno(c, off);
939 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000940}
941
942static int
943compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
944{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000945 PyObject *t, *v;
946 Py_ssize_t arg;
947 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000949 /* necessary to make sure types aren't coerced (e.g., int and long) */
950 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
951 if (PyFloat_Check(o)) {
952 d = PyFloat_AS_DOUBLE(o);
953 /* all we need is to make the tuple different in either the 0.0
954 * or -0.0 case from all others, just to avoid the "coercion".
955 */
956 if (d == 0.0 && copysign(1.0, d) < 0.0)
957 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
958 else
959 t = PyTuple_Pack(2, o, o->ob_type);
960 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000961#ifndef WITHOUT_COMPLEX
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000962 else if (PyComplex_Check(o)) {
963 Py_complex z;
964 int real_negzero, imag_negzero;
965 /* For the complex case we must make complex(x, 0.)
966 different from complex(x, -0.) and complex(0., y)
967 different from complex(-0., y), for any x and y.
968 All four complex zeros must be distinguished.*/
969 z = PyComplex_AsCComplex(o);
970 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
971 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
972 if (real_negzero && imag_negzero) {
973 t = PyTuple_Pack(5, o, o->ob_type,
974 Py_None, Py_None, Py_None);
Mark Dickinson105be772008-01-31 22:17:37 +0000975 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000976 else if (imag_negzero) {
977 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
978 }
979 else if (real_negzero) {
980 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
981 }
982 else {
983 t = PyTuple_Pack(2, o, o->ob_type);
984 }
985 }
Mark Dickinson026ac7c2009-10-15 17:45:39 +0000986#endif /* WITHOUT_COMPLEX */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000987 else {
988 t = PyTuple_Pack(2, o, o->ob_type);
989 }
990 if (t == NULL)
991 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 v = PyDict_GetItem(dict, t);
994 if (!v) {
995 arg = PyDict_Size(dict);
996 v = PyInt_FromLong(arg);
997 if (!v) {
998 Py_DECREF(t);
999 return -1;
1000 }
1001 if (PyDict_SetItem(dict, t, v) < 0) {
1002 Py_DECREF(t);
1003 Py_DECREF(v);
1004 return -1;
1005 }
1006 Py_DECREF(v);
1007 }
1008 else
1009 arg = PyInt_AsLong(v);
1010 Py_DECREF(t);
1011 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001012}
1013
1014static int
1015compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001016 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017{
1018 int arg = compiler_add_o(c, dict, o);
1019 if (arg < 0)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001020 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001021 return compiler_addop_i(c, opcode, arg);
1022}
1023
1024static int
1025compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001026 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027{
1028 int arg;
1029 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1030 if (!mangled)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001031 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032 arg = compiler_add_o(c, dict, mangled);
1033 Py_DECREF(mangled);
1034 if (arg < 0)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 return compiler_addop_i(c, opcode, arg);
1037}
1038
1039/* Add an opcode with an integer argument.
1040 Returns 0 on failure, 1 on success.
1041*/
1042
1043static int
1044compiler_addop_i(struct compiler *c, int opcode, int oparg)
1045{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001046 struct instr *i;
1047 int off;
1048 off = compiler_next_instr(c, c->u->u_curblock);
1049 if (off < 0)
1050 return 0;
1051 i = &c->u->u_curblock->b_instr[off];
1052 i->i_opcode = opcode;
1053 i->i_oparg = oparg;
1054 i->i_hasarg = 1;
1055 compiler_set_lineno(c, off);
1056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057}
1058
1059static int
1060compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1061{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 struct instr *i;
1063 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001065 assert(b != NULL);
1066 off = compiler_next_instr(c, c->u->u_curblock);
1067 if (off < 0)
1068 return 0;
1069 i = &c->u->u_curblock->b_instr[off];
1070 i->i_opcode = opcode;
1071 i->i_target = b;
1072 i->i_hasarg = 1;
1073 if (absolute)
1074 i->i_jabs = 1;
1075 else
1076 i->i_jrel = 1;
1077 compiler_set_lineno(c, off);
1078 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079}
1080
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001081/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1082 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083 it as the current block. NEXT_BLOCK() also creates an implicit jump
1084 from the current block to the new block.
1085*/
1086
Neal Norwitzf733a012006-10-29 18:30:10 +00001087/* The returns inside these macros make it impossible to decref objects
1088 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089*/
1090
1091
1092#define NEW_BLOCK(C) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001093 if (compiler_use_new_block((C)) == NULL) \
1094 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095}
1096
1097#define NEXT_BLOCK(C) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001098 if (compiler_next_block((C)) == NULL) \
1099 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001100}
1101
1102#define ADDOP(C, OP) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001103 if (!compiler_addop((C), (OP))) \
1104 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105}
1106
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001107#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001108 if (!compiler_addop((C), (OP))) { \
1109 compiler_exit_scope(c); \
1110 return 0; \
1111 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001112}
1113
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001115 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1116 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117}
1118
1119#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1121 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122}
1123
1124#define ADDOP_I(C, OP, O) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001125 if (!compiler_addop_i((C), (OP), (O))) \
1126 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127}
1128
1129#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001130 if (!compiler_addop_j((C), (OP), (O), 1)) \
1131 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132}
1133
1134#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001135 if (!compiler_addop_j((C), (OP), (O), 0)) \
1136 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137}
1138
1139/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1140 the ASDL name to synthesize the name of the C type and the visit function.
1141*/
1142
1143#define VISIT(C, TYPE, V) {\
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001144 if (!compiler_visit_ ## TYPE((C), (V))) \
1145 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146}
1147
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001148#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001149 if (!compiler_visit_ ## TYPE((C), (V))) { \
1150 compiler_exit_scope(c); \
1151 return 0; \
1152 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001153}
1154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001156 if (!compiler_visit_slice((C), (V), (CTX))) \
1157 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158}
1159
1160#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001161 int _i; \
1162 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1163 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1164 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1165 if (!compiler_visit_ ## TYPE((C), elt)) \
1166 return 0; \
1167 } \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001168}
1169
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001170#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001171 int _i; \
1172 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1173 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1174 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1175 if (!compiler_visit_ ## TYPE((C), elt)) { \
1176 compiler_exit_scope(c); \
1177 return 0; \
1178 } \
1179 } \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001180}
1181
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001182static int
1183compiler_isdocstring(stmt_ty s)
1184{
1185 if (s->kind != Expr_kind)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001186 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187 return s->v.Expr.value->kind == Str_kind;
1188}
1189
1190/* Compile a sequence of statements, checking for a docstring. */
1191
1192static int
1193compiler_body(struct compiler *c, asdl_seq *stmts)
1194{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001195 int i = 0;
1196 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001198 if (!asdl_seq_LEN(stmts))
1199 return 1;
1200 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1201 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1202 /* don't generate docstrings if -OO */
1203 i = 1;
1204 VISIT(c, expr, st->v.Expr.value);
1205 if (!compiler_nameop(c, __doc__, Store))
1206 return 0;
1207 }
1208 for (; i < asdl_seq_LEN(stmts); i++)
1209 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1210 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211}
1212
1213static PyCodeObject *
1214compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001215{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001216 PyCodeObject *co;
1217 int addNone = 1;
1218 static PyObject *module;
1219 if (!module) {
1220 module = PyString_InternFromString("<module>");
1221 if (!module)
1222 return NULL;
1223 }
1224 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1225 if (!compiler_enter_scope(c, module, mod, 0))
1226 return NULL;
1227 switch (mod->kind) {
1228 case Module_kind:
1229 if (!compiler_body(c, mod->v.Module.body)) {
1230 compiler_exit_scope(c);
1231 return 0;
1232 }
1233 break;
1234 case Interactive_kind:
1235 c->c_interactive = 1;
1236 VISIT_SEQ_IN_SCOPE(c, stmt,
1237 mod->v.Interactive.body);
1238 break;
1239 case Expression_kind:
1240 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1241 addNone = 0;
1242 break;
1243 case Suite_kind:
1244 PyErr_SetString(PyExc_SystemError,
1245 "suite should not be possible");
1246 return 0;
1247 default:
1248 PyErr_Format(PyExc_SystemError,
1249 "module kind %d should not be possible",
1250 mod->kind);
1251 return 0;
1252 }
1253 co = assemble(c, addNone);
1254 compiler_exit_scope(c);
1255 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001256}
1257
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258/* The test for LOCAL must come before the test for FREE in order to
1259 handle classes where name is both local and free. The local var is
1260 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001261*/
1262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263static int
1264get_ref_type(struct compiler *c, PyObject *name)
1265{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001266 int scope = PyST_GetScope(c->u->u_ste, name);
1267 if (scope == 0) {
1268 char buf[350];
1269 PyOS_snprintf(buf, sizeof(buf),
1270 "unknown scope for %.100s in %.100s(%s) in %s\n"
1271 "symbols: %s\nlocals: %s\nglobals: %s",
1272 PyString_AS_STRING(name),
1273 PyString_AS_STRING(c->u->u_name),
Serhiy Storchakaa86c0912014-11-19 00:11:05 +02001274 PyString_AS_STRING(PyObject_Repr(c->u->u_ste->ste_id)),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001275 c->c_filename,
Serhiy Storchakaa86c0912014-11-19 00:11:05 +02001276 PyString_AS_STRING(PyObject_Repr(c->u->u_ste->ste_symbols)),
1277 PyString_AS_STRING(PyObject_Repr(c->u->u_varnames)),
1278 PyString_AS_STRING(PyObject_Repr(c->u->u_names))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001279 );
1280 Py_FatalError(buf);
1281 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001282
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001283 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001284}
1285
1286static int
1287compiler_lookup_arg(PyObject *dict, PyObject *name)
1288{
1289 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001290 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291 if (k == NULL)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001292 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001294 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295 if (v == NULL)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00001296 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297 return PyInt_AS_LONG(v);
1298}
1299
1300static int
1301compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1302{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001303 int i, free = PyCode_GetNumFree(co);
1304 if (free == 0) {
1305 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1306 ADDOP_I(c, MAKE_FUNCTION, args);
1307 return 1;
1308 }
1309 for (i = 0; i < free; ++i) {
1310 /* Bypass com_addop_varname because it will generate
1311 LOAD_DEREF but LOAD_CLOSURE is needed.
1312 */
1313 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1314 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001316 /* Special case: If a class contains a method with a
1317 free variable that has the same name as a method,
1318 the name will be considered free *and* local in the
1319 class. It should be handled by the closure, as
1320 well as by the normal name loookup logic.
1321 */
1322 reftype = get_ref_type(c, name);
1323 if (reftype == CELL)
1324 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1325 else /* (reftype == FREE) */
1326 arg = compiler_lookup_arg(c->u->u_freevars, name);
1327 if (arg == -1) {
1328 printf("lookup %s in %s %d %d\n"
1329 "freevars of %s: %s\n",
Serhiy Storchakaa86c0912014-11-19 00:11:05 +02001330 PyString_AS_STRING(PyObject_Repr(name)),
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001331 PyString_AS_STRING(c->u->u_name),
1332 reftype, arg,
1333 PyString_AS_STRING(co->co_name),
Serhiy Storchakaa86c0912014-11-19 00:11:05 +02001334 PyString_AS_STRING(PyObject_Repr(co->co_freevars)));
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001335 Py_FatalError("compiler_make_closure()");
1336 }
1337 ADDOP_I(c, LOAD_CLOSURE, arg);
1338 }
1339 ADDOP_I(c, BUILD_TUPLE, free);
1340 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1341 ADDOP_I(c, MAKE_CLOSURE, args);
1342 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343}
1344
1345static int
1346compiler_decorators(struct compiler *c, asdl_seq* decos)
1347{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001348 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001350 if (!decos)
1351 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001353 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1354 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1355 }
1356 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357}
1358
1359static int
1360compiler_arguments(struct compiler *c, arguments_ty args)
1361{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001362 int i;
1363 int n = asdl_seq_LEN(args->args);
1364 /* Correctly handle nested argument lists */
1365 for (i = 0; i < n; i++) {
1366 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
1367 if (arg->kind == Tuple_kind) {
1368 PyObject *id = PyString_FromFormat(".%d", i);
1369 if (id == NULL) {
1370 return 0;
1371 }
1372 if (!compiler_nameop(c, id, Load)) {
1373 Py_DECREF(id);
1374 return 0;
1375 }
1376 Py_DECREF(id);
1377 VISIT(c, expr, arg);
1378 }
1379 }
1380 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381}
1382
1383static int
1384compiler_function(struct compiler *c, stmt_ty s)
1385{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001386 PyCodeObject *co;
1387 PyObject *first_const = Py_None;
1388 arguments_ty args = s->v.FunctionDef.args;
1389 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1390 stmt_ty st;
1391 int i, n, docstring;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001393 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001395 if (!compiler_decorators(c, decos))
1396 return 0;
1397 if (args->defaults)
1398 VISIT_SEQ(c, expr, args->defaults);
1399 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1400 s->lineno))
1401 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001403 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1404 docstring = compiler_isdocstring(st);
1405 if (docstring && Py_OptimizeFlag < 2)
1406 first_const = st->v.Expr.value->v.Str.s;
1407 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1408 compiler_exit_scope(c);
1409 return 0;
1410 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 /* unpack nested arguments */
1413 compiler_arguments(c, args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001415 c->u->u_argcount = asdl_seq_LEN(args->args);
1416 n = asdl_seq_LEN(s->v.FunctionDef.body);
1417 /* if there was a docstring, we need to skip the first statement */
1418 for (i = docstring; i < n; i++) {
1419 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1420 VISIT_IN_SCOPE(c, stmt, st);
1421 }
1422 co = assemble(c, 1);
1423 compiler_exit_scope(c);
1424 if (co == NULL)
1425 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001427 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
1428 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001430 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1431 ADDOP_I(c, CALL_FUNCTION, 1);
1432 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001434 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435}
1436
1437static int
1438compiler_class(struct compiler *c, stmt_ty s)
1439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 int n, i;
1441 PyCodeObject *co;
1442 PyObject *str;
1443 asdl_seq* decos = s->v.ClassDef.decorator_list;
Christian Heimes5224d282008-02-23 15:01:05 +00001444
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001445 if (!compiler_decorators(c, decos))
1446 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001448 /* push class name on stack, needed by BUILD_CLASS */
1449 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1450 /* push the tuple of base classes on the stack */
1451 n = asdl_seq_LEN(s->v.ClassDef.bases);
1452 if (n > 0)
1453 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1454 ADDOP_I(c, BUILD_TUPLE, n);
1455 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1456 s->lineno))
1457 return 0;
Serhiy Storchaka5951f232015-12-24 10:35:35 +02001458 Py_INCREF(s->v.ClassDef.name);
1459 Py_SETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001460 str = PyString_InternFromString("__name__");
1461 if (!str || !compiler_nameop(c, str, Load)) {
1462 Py_XDECREF(str);
1463 compiler_exit_scope(c);
1464 return 0;
1465 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001467 Py_DECREF(str);
1468 str = PyString_InternFromString("__module__");
1469 if (!str || !compiler_nameop(c, str, Store)) {
1470 Py_XDECREF(str);
1471 compiler_exit_scope(c);
1472 return 0;
1473 }
1474 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001476 if (!compiler_body(c, s->v.ClassDef.body)) {
1477 compiler_exit_scope(c);
1478 return 0;
1479 }
Neal Norwitz4737b232005-11-19 23:58:29 +00001480
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001481 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1482 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1483 co = assemble(c, 1);
1484 compiler_exit_scope(c);
1485 if (co == NULL)
1486 return 0;
1487
1488 compiler_make_closure(c, co, 0);
1489 Py_DECREF(co);
1490
1491 ADDOP_I(c, CALL_FUNCTION, 0);
1492 ADDOP(c, BUILD_CLASS);
1493 /* apply decorators */
1494 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1495 ADDOP_I(c, CALL_FUNCTION, 1);
1496 }
1497 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1498 return 0;
1499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
1502static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001503compiler_ifexp(struct compiler *c, expr_ty e)
1504{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001505 basicblock *end, *next;
1506
1507 assert(e->kind == IfExp_kind);
1508 end = compiler_new_block(c);
1509 if (end == NULL)
1510 return 0;
1511 next = compiler_new_block(c);
1512 if (next == NULL)
1513 return 0;
1514 VISIT(c, expr, e->v.IfExp.test);
1515 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1516 VISIT(c, expr, e->v.IfExp.body);
1517 ADDOP_JREL(c, JUMP_FORWARD, end);
1518 compiler_use_next_block(c, next);
1519 VISIT(c, expr, e->v.IfExp.orelse);
1520 compiler_use_next_block(c, end);
1521 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001522}
1523
1524static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525compiler_lambda(struct compiler *c, expr_ty e)
1526{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001527 PyCodeObject *co;
1528 static identifier name;
1529 arguments_ty args = e->v.Lambda.args;
1530 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001532 if (!name) {
1533 name = PyString_InternFromString("<lambda>");
1534 if (!name)
1535 return 0;
1536 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001538 if (args->defaults)
1539 VISIT_SEQ(c, expr, args->defaults);
1540 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1541 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001542
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001543 /* unpack nested arguments */
1544 compiler_arguments(c, args);
Benjamin Peterson0dee9c12010-03-17 20:41:42 +00001545
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001546 /* Make None the first constant, so the lambda can't have a
1547 docstring. */
1548 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1549 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001551 c->u->u_argcount = asdl_seq_LEN(args->args);
1552 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1553 if (c->u->u_ste->ste_generator) {
1554 ADDOP_IN_SCOPE(c, POP_TOP);
1555 }
1556 else {
1557 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1558 }
1559 co = assemble(c, 1);
1560 compiler_exit_scope(c);
1561 if (co == NULL)
1562 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001563
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001564 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
1565 Py_DECREF(co);
1566
1567 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001568}
1569
1570static int
1571compiler_print(struct compiler *c, stmt_ty s)
1572{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001573 int i, n;
1574 bool dest;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001575
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001576 assert(s->kind == Print_kind);
1577 n = asdl_seq_LEN(s->v.Print.values);
1578 dest = false;
1579 if (s->v.Print.dest) {
1580 VISIT(c, expr, s->v.Print.dest);
1581 dest = true;
1582 }
1583 for (i = 0; i < n; i++) {
1584 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1585 if (dest) {
1586 ADDOP(c, DUP_TOP);
1587 VISIT(c, expr, e);
1588 ADDOP(c, ROT_TWO);
1589 ADDOP(c, PRINT_ITEM_TO);
1590 }
1591 else {
1592 VISIT(c, expr, e);
1593 ADDOP(c, PRINT_ITEM);
1594 }
1595 }
1596 if (s->v.Print.nl) {
1597 if (dest)
1598 ADDOP(c, PRINT_NEWLINE_TO)
1599 else
1600 ADDOP(c, PRINT_NEWLINE)
1601 }
1602 else if (dest)
1603 ADDOP(c, POP_TOP);
1604 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001605}
1606
1607static int
1608compiler_if(struct compiler *c, stmt_ty s)
1609{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001610 basicblock *end, *next;
1611 int constant;
1612 assert(s->kind == If_kind);
1613 end = compiler_new_block(c);
1614 if (end == NULL)
1615 return 0;
1616
1617 constant = expr_constant(s->v.If.test);
1618 /* constant = 0: "if 0"
1619 * constant = 1: "if 1", "if 2", ...
1620 * constant = -1: rest */
1621 if (constant == 0) {
1622 if (s->v.If.orelse)
1623 VISIT_SEQ(c, stmt, s->v.If.orelse);
1624 } else if (constant == 1) {
1625 VISIT_SEQ(c, stmt, s->v.If.body);
1626 } else {
1627 if (s->v.If.orelse) {
1628 next = compiler_new_block(c);
1629 if (next == NULL)
1630 return 0;
1631 }
1632 else
1633 next = end;
1634 VISIT(c, expr, s->v.If.test);
1635 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1636 VISIT_SEQ(c, stmt, s->v.If.body);
1637 ADDOP_JREL(c, JUMP_FORWARD, end);
1638 if (s->v.If.orelse) {
1639 compiler_use_next_block(c, next);
1640 VISIT_SEQ(c, stmt, s->v.If.orelse);
1641 }
1642 }
1643 compiler_use_next_block(c, end);
1644 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001645}
1646
1647static int
1648compiler_for(struct compiler *c, stmt_ty s)
1649{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001650 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001652 start = compiler_new_block(c);
1653 cleanup = compiler_new_block(c);
1654 end = compiler_new_block(c);
1655 if (start == NULL || end == NULL || cleanup == NULL)
1656 return 0;
1657 ADDOP_JREL(c, SETUP_LOOP, end);
1658 if (!compiler_push_fblock(c, LOOP, start))
1659 return 0;
1660 VISIT(c, expr, s->v.For.iter);
1661 ADDOP(c, GET_ITER);
1662 compiler_use_next_block(c, start);
1663 ADDOP_JREL(c, FOR_ITER, cleanup);
1664 VISIT(c, expr, s->v.For.target);
1665 VISIT_SEQ(c, stmt, s->v.For.body);
1666 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1667 compiler_use_next_block(c, cleanup);
1668 ADDOP(c, POP_BLOCK);
1669 compiler_pop_fblock(c, LOOP, start);
1670 VISIT_SEQ(c, stmt, s->v.For.orelse);
1671 compiler_use_next_block(c, end);
1672 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673}
1674
1675static int
1676compiler_while(struct compiler *c, stmt_ty s)
1677{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001678 basicblock *loop, *orelse, *end, *anchor = NULL;
1679 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001681 if (constant == 0) {
1682 if (s->v.While.orelse)
1683 VISIT_SEQ(c, stmt, s->v.While.orelse);
1684 return 1;
1685 }
1686 loop = compiler_new_block(c);
1687 end = compiler_new_block(c);
1688 if (constant == -1) {
1689 anchor = compiler_new_block(c);
1690 if (anchor == NULL)
1691 return 0;
1692 }
1693 if (loop == NULL || end == NULL)
1694 return 0;
1695 if (s->v.While.orelse) {
1696 orelse = compiler_new_block(c);
1697 if (orelse == NULL)
1698 return 0;
1699 }
1700 else
1701 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001703 ADDOP_JREL(c, SETUP_LOOP, end);
1704 compiler_use_next_block(c, loop);
1705 if (!compiler_push_fblock(c, LOOP, loop))
1706 return 0;
1707 if (constant == -1) {
1708 VISIT(c, expr, s->v.While.test);
1709 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1710 }
1711 VISIT_SEQ(c, stmt, s->v.While.body);
1712 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001714 /* XXX should the two POP instructions be in a separate block
1715 if there is no else clause ?
1716 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717
Benjamin Peterson7a6a9732014-12-13 16:06:19 -05001718 if (constant == -1)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001719 compiler_use_next_block(c, anchor);
Benjamin Peterson7a6a9732014-12-13 16:06:19 -05001720 ADDOP(c, POP_BLOCK);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001721 compiler_pop_fblock(c, LOOP, loop);
1722 if (orelse != NULL) /* what if orelse is just pass? */
1723 VISIT_SEQ(c, stmt, s->v.While.orelse);
1724 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001725
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001726 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001727}
1728
1729static int
1730compiler_continue(struct compiler *c)
1731{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001732 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1733 static const char IN_FINALLY_ERROR_MSG[] =
1734 "'continue' not supported inside 'finally' clause";
1735 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001737 if (!c->u->u_nfblocks)
1738 return compiler_error(c, LOOP_ERROR_MSG);
1739 i = c->u->u_nfblocks - 1;
1740 switch (c->u->u_fblock[i].fb_type) {
1741 case LOOP:
1742 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1743 break;
1744 case EXCEPT:
1745 case FINALLY_TRY:
1746 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1747 /* Prevent continue anywhere under a finally
1748 even if hidden in a sub-try or except. */
1749 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1750 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1751 }
1752 if (i == -1)
1753 return compiler_error(c, LOOP_ERROR_MSG);
1754 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1755 break;
1756 case FINALLY_END:
1757 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1758 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001761}
1762
1763/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001764
1765 SETUP_FINALLY L
1766 <code for body>
1767 POP_BLOCK
1768 LOAD_CONST <None>
1769 L: <code for finalbody>
1770 END_FINALLY
1771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 The special instructions use the block stack. Each block
1773 stack entry contains the instruction that created it (here
1774 SETUP_FINALLY), the level of the value stack at the time the
1775 block stack entry was created, and a label (here L).
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777 SETUP_FINALLY:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001778 Pushes the current value stack level and the label
1779 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 POP_BLOCK:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001781 Pops en entry from the block stack, and pops the value
1782 stack until its level is the same as indicated on the
1783 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 END_FINALLY:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001785 Pops a variable number of entries from the *value* stack
1786 and re-raises the exception they specify. The number of
1787 entries popped depends on the (pseudo) exception type.
1788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789 The block stack is unwound when an exception is raised:
1790 when a SETUP_FINALLY entry is found, the exception is pushed
1791 onto the value stack (and the exception condition is cleared),
1792 and the interpreter jumps to the label gotten from the block
1793 stack.
1794*/
1795
1796static int
1797compiler_try_finally(struct compiler *c, stmt_ty s)
1798{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001799 basicblock *body, *end;
1800 body = compiler_new_block(c);
1801 end = compiler_new_block(c);
1802 if (body == NULL || end == NULL)
1803 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001805 ADDOP_JREL(c, SETUP_FINALLY, end);
1806 compiler_use_next_block(c, body);
1807 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1808 return 0;
1809 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1810 ADDOP(c, POP_BLOCK);
1811 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001813 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1814 compiler_use_next_block(c, end);
1815 if (!compiler_push_fblock(c, FINALLY_END, end))
1816 return 0;
1817 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1818 ADDOP(c, END_FINALLY);
1819 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001821 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822}
1823
1824/*
1825 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1826 (The contents of the value stack is shown in [], with the top
1827 at the right; 'tb' is trace-back info, 'val' the exception's
1828 associated value, and 'exc' the exception.)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001829
1830 Value stack Label Instruction Argument
1831 [] SETUP_EXCEPT L1
1832 [] <code for S>
1833 [] POP_BLOCK
1834 [] JUMP_FORWARD L0
1835
1836 [tb, val, exc] L1: DUP )
1837 [tb, val, exc, exc] <evaluate E1> )
1838 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1839 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1840 [tb, val, exc] POP
1841 [tb, val] <assign to V1> (or POP if no V1)
1842 [tb] POP
1843 [] <code for S1>
1844 JUMP_FORWARD L0
1845
1846 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 .............................etc.......................
1848
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1850
1851 [] L0: <next statement>
1852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 Of course, parts are not generated if Vi or Ei is not present.
1854*/
1855static int
1856compiler_try_except(struct compiler *c, stmt_ty s)
1857{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001858 basicblock *body, *orelse, *except, *end;
1859 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 body = compiler_new_block(c);
1862 except = compiler_new_block(c);
1863 orelse = compiler_new_block(c);
1864 end = compiler_new_block(c);
1865 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1866 return 0;
1867 ADDOP_JREL(c, SETUP_EXCEPT, except);
1868 compiler_use_next_block(c, body);
1869 if (!compiler_push_fblock(c, EXCEPT, body))
1870 return 0;
1871 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1872 ADDOP(c, POP_BLOCK);
1873 compiler_pop_fblock(c, EXCEPT, body);
1874 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1875 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1876 compiler_use_next_block(c, except);
1877 for (i = 0; i < n; i++) {
1878 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1879 s->v.TryExcept.handlers, i);
1880 if (!handler->v.ExceptHandler.type && i < n-1)
1881 return compiler_error(c, "default 'except:' must be last");
1882 c->u->u_lineno_set = false;
1883 c->u->u_lineno = handler->lineno;
1884 except = compiler_new_block(c);
1885 if (except == NULL)
1886 return 0;
1887 if (handler->v.ExceptHandler.type) {
1888 ADDOP(c, DUP_TOP);
1889 VISIT(c, expr, handler->v.ExceptHandler.type);
1890 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1891 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
1892 }
1893 ADDOP(c, POP_TOP);
1894 if (handler->v.ExceptHandler.name) {
1895 VISIT(c, expr, handler->v.ExceptHandler.name);
1896 }
1897 else {
1898 ADDOP(c, POP_TOP);
1899 }
1900 ADDOP(c, POP_TOP);
1901 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
1902 ADDOP_JREL(c, JUMP_FORWARD, end);
1903 compiler_use_next_block(c, except);
1904 }
1905 ADDOP(c, END_FINALLY);
1906 compiler_use_next_block(c, orelse);
1907 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1908 compiler_use_next_block(c, end);
1909 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910}
1911
1912static int
1913compiler_import_as(struct compiler *c, identifier name, identifier asname)
1914{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001915 /* The IMPORT_NAME opcode was already generated. This function
1916 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001918 If there is a dot in name, we need to split it and emit a
1919 LOAD_ATTR for each name.
1920 */
1921 const char *src = PyString_AS_STRING(name);
1922 const char *dot = strchr(src, '.');
1923 if (dot) {
1924 /* Consume the base module name to get the first attribute */
1925 src = dot + 1;
1926 while (dot) {
1927 /* NB src is only defined when dot != NULL */
1928 PyObject *attr;
1929 dot = strchr(src, '.');
1930 attr = PyString_FromStringAndSize(src,
1931 dot ? dot - src : strlen(src));
1932 if (!attr)
1933 return -1;
1934 ADDOP_O(c, LOAD_ATTR, attr, names);
1935 Py_DECREF(attr);
1936 src = dot + 1;
1937 }
1938 }
1939 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940}
1941
1942static int
1943compiler_import(struct compiler *c, stmt_ty s)
1944{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001945 /* The Import node stores a module name like a.b.c as a single
1946 string. This is convenient for all cases except
1947 import a.b.c as d
1948 where we need to parse that string to extract the individual
1949 module names.
1950 XXX Perhaps change the representation to make this case simpler?
1951 */
1952 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001953
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001954 for (i = 0; i < n; i++) {
1955 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
1956 int r;
1957 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001959 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
1960 level = PyInt_FromLong(0);
1961 else
1962 level = PyInt_FromLong(-1);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001963
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001964 if (level == NULL)
1965 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001966
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001967 ADDOP_O(c, LOAD_CONST, level, consts);
1968 Py_DECREF(level);
1969 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1970 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001972 if (alias->asname) {
1973 r = compiler_import_as(c, alias->name, alias->asname);
1974 if (!r)
1975 return r;
1976 }
1977 else {
1978 identifier tmp = alias->name;
1979 const char *base = PyString_AS_STRING(alias->name);
1980 char *dot = strchr(base, '.');
Benjamin Peterson0287f2f2015-07-27 07:47:21 -07001981 if (dot) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001982 tmp = PyString_FromStringAndSize(base,
1983 dot - base);
Benjamin Peterson0287f2f2015-07-27 07:47:21 -07001984 if (tmp == NULL)
1985 return 0;
1986 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001987 r = compiler_nameop(c, tmp, Store);
1988 if (dot) {
1989 Py_DECREF(tmp);
1990 }
1991 if (!r)
1992 return r;
1993 }
1994 }
1995 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996}
1997
1998static int
1999compiler_from_import(struct compiler *c, stmt_ty s)
2000{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002001 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002003 PyObject *names = PyTuple_New(n);
2004 PyObject *level;
2005 static PyObject *empty_string;
Benjamin Petersona72be3b2009-06-13 20:23:33 +00002006
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002007 if (!empty_string) {
2008 empty_string = PyString_FromString("");
2009 if (!empty_string)
2010 return 0;
2011 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002013 if (!names)
2014 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002015
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002016 if (s->v.ImportFrom.level == 0 && c->c_flags &&
2017 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
2018 level = PyInt_FromLong(-1);
2019 else
2020 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002021
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002022 if (!level) {
2023 Py_DECREF(names);
2024 return 0;
2025 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002027 /* build up the names */
2028 for (i = 0; i < n; i++) {
2029 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2030 Py_INCREF(alias->name);
2031 PyTuple_SET_ITEM(names, i, alias->name);
2032 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002034 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2035 !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
2036 Py_DECREF(level);
2037 Py_DECREF(names);
2038 return compiler_error(c, "from __future__ imports must occur "
2039 "at the beginning of the file");
2040 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002042 ADDOP_O(c, LOAD_CONST, level, consts);
2043 Py_DECREF(level);
2044 ADDOP_O(c, LOAD_CONST, names, consts);
2045 Py_DECREF(names);
2046 if (s->v.ImportFrom.module) {
2047 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2048 }
2049 else {
2050 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2051 }
2052 for (i = 0; i < n; i++) {
2053 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2054 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002056 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2057 assert(n == 1);
2058 ADDOP(c, IMPORT_STAR);
2059 return 1;
2060 }
2061
2062 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2063 store_name = alias->name;
2064 if (alias->asname)
2065 store_name = alias->asname;
2066
2067 if (!compiler_nameop(c, store_name, Store)) {
2068 Py_DECREF(names);
2069 return 0;
2070 }
2071 }
2072 /* remove imported module */
2073 ADDOP(c, POP_TOP);
2074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075}
2076
2077static int
2078compiler_assert(struct compiler *c, stmt_ty s)
2079{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002080 static PyObject *assertion_error = NULL;
2081 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002083 if (Py_OptimizeFlag)
2084 return 1;
2085 if (assertion_error == NULL) {
2086 assertion_error = PyString_InternFromString("AssertionError");
2087 if (assertion_error == NULL)
2088 return 0;
2089 }
2090 if (s->v.Assert.test->kind == Tuple_kind &&
2091 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2092 const char* msg =
2093 "assertion is always true, perhaps remove parentheses?";
2094 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2095 c->u->u_lineno, NULL, NULL) == -1)
2096 return 0;
2097 }
2098 VISIT(c, expr, s->v.Assert.test);
2099 end = compiler_new_block(c);
2100 if (end == NULL)
2101 return 0;
2102 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2103 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2104 if (s->v.Assert.msg) {
2105 VISIT(c, expr, s->v.Assert.msg);
Benjamin Peterson0c0d7562011-10-27 08:21:59 -04002106 ADDOP_I(c, CALL_FUNCTION, 1);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002107 }
Benjamin Peterson0c0d7562011-10-27 08:21:59 -04002108 ADDOP_I(c, RAISE_VARARGS, 1);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002109 compiler_use_next_block(c, end);
2110 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111}
2112
2113static int
2114compiler_visit_stmt(struct compiler *c, stmt_ty s)
2115{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002116 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 /* Always assign a lineno to the next instruction for a stmt. */
2119 c->u->u_lineno = s->lineno;
2120 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002121
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002122 switch (s->kind) {
2123 case FunctionDef_kind:
2124 return compiler_function(c, s);
2125 case ClassDef_kind:
2126 return compiler_class(c, s);
2127 case Return_kind:
2128 if (c->u->u_ste->ste_type != FunctionBlock)
2129 return compiler_error(c, "'return' outside function");
2130 if (s->v.Return.value) {
2131 VISIT(c, expr, s->v.Return.value);
2132 }
2133 else
2134 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2135 ADDOP(c, RETURN_VALUE);
2136 break;
2137 case Delete_kind:
2138 VISIT_SEQ(c, expr, s->v.Delete.targets)
2139 break;
2140 case Assign_kind:
2141 n = asdl_seq_LEN(s->v.Assign.targets);
2142 VISIT(c, expr, s->v.Assign.value);
2143 for (i = 0; i < n; i++) {
2144 if (i < n - 1)
2145 ADDOP(c, DUP_TOP);
2146 VISIT(c, expr,
2147 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2148 }
2149 break;
2150 case AugAssign_kind:
2151 return compiler_augassign(c, s);
2152 case Print_kind:
2153 return compiler_print(c, s);
2154 case For_kind:
2155 return compiler_for(c, s);
2156 case While_kind:
2157 return compiler_while(c, s);
2158 case If_kind:
2159 return compiler_if(c, s);
2160 case Raise_kind:
2161 n = 0;
2162 if (s->v.Raise.type) {
2163 VISIT(c, expr, s->v.Raise.type);
2164 n++;
2165 if (s->v.Raise.inst) {
2166 VISIT(c, expr, s->v.Raise.inst);
2167 n++;
2168 if (s->v.Raise.tback) {
2169 VISIT(c, expr, s->v.Raise.tback);
2170 n++;
2171 }
2172 }
2173 }
2174 ADDOP_I(c, RAISE_VARARGS, n);
2175 break;
2176 case TryExcept_kind:
2177 return compiler_try_except(c, s);
2178 case TryFinally_kind:
2179 return compiler_try_finally(c, s);
2180 case Assert_kind:
2181 return compiler_assert(c, s);
2182 case Import_kind:
2183 return compiler_import(c, s);
2184 case ImportFrom_kind:
2185 return compiler_from_import(c, s);
2186 case Exec_kind:
2187 VISIT(c, expr, s->v.Exec.body);
2188 if (s->v.Exec.globals) {
2189 VISIT(c, expr, s->v.Exec.globals);
2190 if (s->v.Exec.locals) {
2191 VISIT(c, expr, s->v.Exec.locals);
2192 } else {
2193 ADDOP(c, DUP_TOP);
2194 }
2195 } else {
2196 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2197 ADDOP(c, DUP_TOP);
2198 }
2199 ADDOP(c, EXEC_STMT);
2200 break;
2201 case Global_kind:
2202 break;
2203 case Expr_kind:
2204 if (c->c_interactive && c->c_nestlevel <= 1) {
2205 VISIT(c, expr, s->v.Expr.value);
2206 ADDOP(c, PRINT_EXPR);
2207 }
2208 else if (s->v.Expr.value->kind != Str_kind &&
2209 s->v.Expr.value->kind != Num_kind) {
2210 VISIT(c, expr, s->v.Expr.value);
2211 ADDOP(c, POP_TOP);
2212 }
2213 break;
2214 case Pass_kind:
2215 break;
2216 case Break_kind:
2217 if (!compiler_in_loop(c))
2218 return compiler_error(c, "'break' outside loop");
2219 ADDOP(c, BREAK_LOOP);
2220 break;
2221 case Continue_kind:
2222 return compiler_continue(c);
2223 case With_kind:
2224 return compiler_with(c, s);
2225 }
2226 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227}
2228
2229static int
2230unaryop(unaryop_ty op)
2231{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002232 switch (op) {
2233 case Invert:
2234 return UNARY_INVERT;
2235 case Not:
2236 return UNARY_NOT;
2237 case UAdd:
2238 return UNARY_POSITIVE;
2239 case USub:
2240 return UNARY_NEGATIVE;
2241 default:
2242 PyErr_Format(PyExc_SystemError,
2243 "unary op %d should not be possible", op);
2244 return 0;
2245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246}
2247
2248static int
2249binop(struct compiler *c, operator_ty op)
2250{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002251 switch (op) {
2252 case Add:
2253 return BINARY_ADD;
2254 case Sub:
2255 return BINARY_SUBTRACT;
2256 case Mult:
2257 return BINARY_MULTIPLY;
2258 case Div:
2259 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2260 return BINARY_TRUE_DIVIDE;
2261 else
2262 return BINARY_DIVIDE;
2263 case Mod:
2264 return BINARY_MODULO;
2265 case Pow:
2266 return BINARY_POWER;
2267 case LShift:
2268 return BINARY_LSHIFT;
2269 case RShift:
2270 return BINARY_RSHIFT;
2271 case BitOr:
2272 return BINARY_OR;
2273 case BitXor:
2274 return BINARY_XOR;
2275 case BitAnd:
2276 return BINARY_AND;
2277 case FloorDiv:
2278 return BINARY_FLOOR_DIVIDE;
2279 default:
2280 PyErr_Format(PyExc_SystemError,
2281 "binary op %d should not be possible", op);
2282 return 0;
2283 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284}
2285
2286static int
2287cmpop(cmpop_ty op)
2288{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002289 switch (op) {
2290 case Eq:
2291 return PyCmp_EQ;
2292 case NotEq:
2293 return PyCmp_NE;
2294 case Lt:
2295 return PyCmp_LT;
2296 case LtE:
2297 return PyCmp_LE;
2298 case Gt:
2299 return PyCmp_GT;
2300 case GtE:
2301 return PyCmp_GE;
2302 case Is:
2303 return PyCmp_IS;
2304 case IsNot:
2305 return PyCmp_IS_NOT;
2306 case In:
2307 return PyCmp_IN;
2308 case NotIn:
2309 return PyCmp_NOT_IN;
2310 default:
2311 return PyCmp_BAD;
2312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313}
2314
2315static int
2316inplace_binop(struct compiler *c, operator_ty op)
2317{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002318 switch (op) {
2319 case Add:
2320 return INPLACE_ADD;
2321 case Sub:
2322 return INPLACE_SUBTRACT;
2323 case Mult:
2324 return INPLACE_MULTIPLY;
2325 case Div:
2326 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2327 return INPLACE_TRUE_DIVIDE;
2328 else
2329 return INPLACE_DIVIDE;
2330 case Mod:
2331 return INPLACE_MODULO;
2332 case Pow:
2333 return INPLACE_POWER;
2334 case LShift:
2335 return INPLACE_LSHIFT;
2336 case RShift:
2337 return INPLACE_RSHIFT;
2338 case BitOr:
2339 return INPLACE_OR;
2340 case BitXor:
2341 return INPLACE_XOR;
2342 case BitAnd:
2343 return INPLACE_AND;
2344 case FloorDiv:
2345 return INPLACE_FLOOR_DIVIDE;
2346 default:
2347 PyErr_Format(PyExc_SystemError,
2348 "inplace binary op %d should not be possible", op);
2349 return 0;
2350 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351}
2352
2353static int
2354compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2355{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002356 int op, scope, arg;
2357 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002359 PyObject *dict = c->u->u_names;
2360 PyObject *mangled;
2361 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002363 mangled = _Py_Mangle(c->u->u_private, name);
2364 if (!mangled)
2365 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002366
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002367 op = 0;
2368 optype = OP_NAME;
2369 scope = PyST_GetScope(c->u->u_ste, mangled);
2370 switch (scope) {
2371 case FREE:
2372 dict = c->u->u_freevars;
2373 optype = OP_DEREF;
2374 break;
2375 case CELL:
2376 dict = c->u->u_cellvars;
2377 optype = OP_DEREF;
2378 break;
2379 case LOCAL:
2380 if (c->u->u_ste->ste_type == FunctionBlock)
2381 optype = OP_FAST;
2382 break;
2383 case GLOBAL_IMPLICIT:
2384 if (c->u->u_ste->ste_type == FunctionBlock &&
2385 !c->u->u_ste->ste_unoptimized)
2386 optype = OP_GLOBAL;
2387 break;
2388 case GLOBAL_EXPLICIT:
2389 optype = OP_GLOBAL;
2390 break;
2391 default:
2392 /* scope can be 0 */
2393 break;
2394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002396 /* XXX Leave assert here, but handle __doc__ and the like better */
2397 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002398
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002399 switch (optype) {
2400 case OP_DEREF:
2401 switch (ctx) {
2402 case Load: op = LOAD_DEREF; break;
2403 case Store: op = STORE_DEREF; break;
2404 case AugLoad:
2405 case AugStore:
2406 break;
2407 case Del:
2408 PyErr_Format(PyExc_SyntaxError,
2409 "can not delete variable '%s' referenced "
2410 "in nested scope",
2411 PyString_AS_STRING(name));
2412 Py_DECREF(mangled);
2413 return 0;
2414 case Param:
2415 default:
2416 PyErr_SetString(PyExc_SystemError,
2417 "param invalid for deref variable");
2418 return 0;
2419 }
2420 break;
2421 case OP_FAST:
2422 switch (ctx) {
2423 case Load: op = LOAD_FAST; break;
2424 case Store: op = STORE_FAST; break;
2425 case Del: op = DELETE_FAST; break;
2426 case AugLoad:
2427 case AugStore:
2428 break;
2429 case Param:
2430 default:
2431 PyErr_SetString(PyExc_SystemError,
2432 "param invalid for local variable");
2433 return 0;
2434 }
2435 ADDOP_O(c, op, mangled, varnames);
2436 Py_DECREF(mangled);
2437 return 1;
2438 case OP_GLOBAL:
2439 switch (ctx) {
2440 case Load: op = LOAD_GLOBAL; break;
2441 case Store: op = STORE_GLOBAL; break;
2442 case Del: op = DELETE_GLOBAL; break;
2443 case AugLoad:
2444 case AugStore:
2445 break;
2446 case Param:
2447 default:
2448 PyErr_SetString(PyExc_SystemError,
2449 "param invalid for global variable");
2450 return 0;
2451 }
2452 break;
2453 case OP_NAME:
2454 switch (ctx) {
2455 case Load: op = LOAD_NAME; break;
2456 case Store: op = STORE_NAME; break;
2457 case Del: op = DELETE_NAME; break;
2458 case AugLoad:
2459 case AugStore:
2460 break;
2461 case Param:
2462 default:
2463 PyErr_SetString(PyExc_SystemError,
2464 "param invalid for name variable");
2465 return 0;
2466 }
2467 break;
2468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002470 assert(op);
2471 arg = compiler_add_o(c, dict, mangled);
2472 Py_DECREF(mangled);
2473 if (arg < 0)
2474 return 0;
2475 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476}
2477
2478static int
2479compiler_boolop(struct compiler *c, expr_ty e)
2480{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002481 basicblock *end;
2482 int jumpi, i, n;
2483 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002485 assert(e->kind == BoolOp_kind);
2486 if (e->v.BoolOp.op == And)
2487 jumpi = JUMP_IF_FALSE_OR_POP;
2488 else
2489 jumpi = JUMP_IF_TRUE_OR_POP;
2490 end = compiler_new_block(c);
2491 if (end == NULL)
2492 return 0;
2493 s = e->v.BoolOp.values;
2494 n = asdl_seq_LEN(s) - 1;
2495 assert(n >= 0);
2496 for (i = 0; i < n; ++i) {
2497 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2498 ADDOP_JABS(c, jumpi, end);
2499 }
2500 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2501 compiler_use_next_block(c, end);
2502 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503}
2504
2505static int
2506compiler_list(struct compiler *c, expr_ty e)
2507{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002508 int n = asdl_seq_LEN(e->v.List.elts);
2509 if (e->v.List.ctx == Store) {
2510 ADDOP_I(c, UNPACK_SEQUENCE, n);
2511 }
2512 VISIT_SEQ(c, expr, e->v.List.elts);
2513 if (e->v.List.ctx == Load) {
2514 ADDOP_I(c, BUILD_LIST, n);
2515 }
2516 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517}
2518
2519static int
2520compiler_tuple(struct compiler *c, expr_ty e)
2521{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002522 int n = asdl_seq_LEN(e->v.Tuple.elts);
2523 if (e->v.Tuple.ctx == Store) {
2524 ADDOP_I(c, UNPACK_SEQUENCE, n);
2525 }
2526 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2527 if (e->v.Tuple.ctx == Load) {
2528 ADDOP_I(c, BUILD_TUPLE, n);
2529 }
2530 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531}
2532
2533static int
2534compiler_compare(struct compiler *c, expr_ty e)
2535{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002536 int i, n;
2537 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002539 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2540 VISIT(c, expr, e->v.Compare.left);
2541 n = asdl_seq_LEN(e->v.Compare.ops);
2542 assert(n > 0);
2543 if (n > 1) {
2544 cleanup = compiler_new_block(c);
2545 if (cleanup == NULL)
2546 return 0;
2547 VISIT(c, expr,
2548 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2549 }
2550 for (i = 1; i < n; i++) {
2551 ADDOP(c, DUP_TOP);
2552 ADDOP(c, ROT_THREE);
2553 ADDOP_I(c, COMPARE_OP,
2554 cmpop((cmpop_ty)(asdl_seq_GET(
2555 e->v.Compare.ops, i - 1))));
2556 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2557 NEXT_BLOCK(c);
2558 if (i < (n - 1))
2559 VISIT(c, expr,
2560 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2561 }
2562 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2563 ADDOP_I(c, COMPARE_OP,
2564 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2565 if (n > 1) {
2566 basicblock *end = compiler_new_block(c);
2567 if (end == NULL)
2568 return 0;
2569 ADDOP_JREL(c, JUMP_FORWARD, end);
2570 compiler_use_next_block(c, cleanup);
2571 ADDOP(c, ROT_TWO);
2572 ADDOP(c, POP_TOP);
2573 compiler_use_next_block(c, end);
2574 }
2575 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576}
2577
2578static int
2579compiler_call(struct compiler *c, expr_ty e)
2580{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002581 int n, code = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002583 VISIT(c, expr, e->v.Call.func);
2584 n = asdl_seq_LEN(e->v.Call.args);
2585 VISIT_SEQ(c, expr, e->v.Call.args);
2586 if (e->v.Call.keywords) {
2587 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2588 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2589 }
2590 if (e->v.Call.starargs) {
2591 VISIT(c, expr, e->v.Call.starargs);
2592 code |= 1;
2593 }
2594 if (e->v.Call.kwargs) {
2595 VISIT(c, expr, e->v.Call.kwargs);
2596 code |= 2;
2597 }
2598 switch (code) {
2599 case 0:
2600 ADDOP_I(c, CALL_FUNCTION, n);
2601 break;
2602 case 1:
2603 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2604 break;
2605 case 2:
2606 ADDOP_I(c, CALL_FUNCTION_KW, n);
2607 break;
2608 case 3:
2609 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2610 break;
2611 }
2612 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613}
2614
2615static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002616compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002617 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002619 /* generate code for the iterator, then each of the ifs,
2620 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002622 comprehension_ty l;
2623 basicblock *start, *anchor, *skip, *if_cleanup;
2624 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002626 start = compiler_new_block(c);
2627 skip = compiler_new_block(c);
2628 if_cleanup = compiler_new_block(c);
2629 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002631 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2632 anchor == NULL)
2633 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002635 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
2636 VISIT(c, expr, l->iter);
2637 ADDOP(c, GET_ITER);
2638 compiler_use_next_block(c, start);
2639 ADDOP_JREL(c, FOR_ITER, anchor);
2640 NEXT_BLOCK(c);
2641 VISIT(c, expr, l->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002643 /* XXX this needs to be cleaned up...a lot! */
2644 n = asdl_seq_LEN(l->ifs);
2645 for (i = 0; i < n; i++) {
2646 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
2647 VISIT(c, expr, e);
2648 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2649 NEXT_BLOCK(c);
2650 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002652 if (++gen_index < asdl_seq_LEN(generators))
2653 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
2654 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002656 /* only append after the last for generator */
2657 if (gen_index >= asdl_seq_LEN(generators)) {
2658 VISIT(c, expr, elt);
2659 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002661 compiler_use_next_block(c, skip);
2662 }
2663 compiler_use_next_block(c, if_cleanup);
2664 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2665 compiler_use_next_block(c, anchor);
2666
2667 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668}
2669
2670static int
2671compiler_listcomp(struct compiler *c, expr_ty e)
2672{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002673 assert(e->kind == ListComp_kind);
2674 ADDOP_I(c, BUILD_LIST, 0);
2675 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2676 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677}
2678
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002679/* Dict and set comprehensions and generator expressions work by creating a
2680 nested function to perform the actual iteration. This means that the
2681 iteration variables don't leak into the current scope.
2682 The defined function is called immediately following its definition, with the
2683 result of that call being the result of the expression.
2684 The LC/SC version returns the populated container, while the GE version is
2685 flagged in symtable.c as a generator, so it returns the generator object
2686 when the function is called.
2687 This code *knows* that the loop cannot contain break, continue, or return,
2688 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2689
2690 Possible cleanups:
2691 - iterate over the generator sequence instead of using recursion
2692*/
2693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694static int
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002695compiler_comprehension_generator(struct compiler *c,
2696 asdl_seq *generators, int gen_index,
2697 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002699 /* generate code for the iterator, then each of the ifs,
2700 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002702 comprehension_ty gen;
2703 basicblock *start, *anchor, *skip, *if_cleanup;
2704 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002706 start = compiler_new_block(c);
2707 skip = compiler_new_block(c);
2708 if_cleanup = compiler_new_block(c);
2709 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002711 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2712 anchor == NULL)
2713 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002715 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002717 if (gen_index == 0) {
2718 /* Receive outermost iter as an implicit argument */
2719 c->u->u_argcount = 1;
2720 ADDOP_I(c, LOAD_FAST, 0);
2721 }
2722 else {
2723 /* Sub-iter - calculate on the fly */
2724 VISIT(c, expr, gen->iter);
2725 ADDOP(c, GET_ITER);
2726 }
2727 compiler_use_next_block(c, start);
2728 ADDOP_JREL(c, FOR_ITER, anchor);
2729 NEXT_BLOCK(c);
2730 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002732 /* XXX this needs to be cleaned up...a lot! */
2733 n = asdl_seq_LEN(gen->ifs);
2734 for (i = 0; i < n; i++) {
2735 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2736 VISIT(c, expr, e);
2737 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2738 NEXT_BLOCK(c);
2739 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002741 if (++gen_index < asdl_seq_LEN(generators))
2742 if (!compiler_comprehension_generator(c,
2743 generators, gen_index,
2744 elt, val, type))
2745 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002747 /* only append after the last for generator */
2748 if (gen_index >= asdl_seq_LEN(generators)) {
2749 /* comprehension specific code */
2750 switch (type) {
2751 case COMP_GENEXP:
2752 VISIT(c, expr, elt);
2753 ADDOP(c, YIELD_VALUE);
2754 ADDOP(c, POP_TOP);
2755 break;
2756 case COMP_SETCOMP:
2757 VISIT(c, expr, elt);
2758 ADDOP_I(c, SET_ADD, gen_index + 1);
2759 break;
2760 case COMP_DICTCOMP:
2761 /* With 'd[k] = v', v is evaluated before k, so we do
2762 the same. */
2763 VISIT(c, expr, val);
2764 VISIT(c, expr, elt);
2765 ADDOP_I(c, MAP_ADD, gen_index + 1);
2766 break;
2767 default:
2768 return 0;
2769 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002771 compiler_use_next_block(c, skip);
2772 }
2773 compiler_use_next_block(c, if_cleanup);
2774 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2775 compiler_use_next_block(c, anchor);
2776
2777 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778}
2779
2780static int
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002781compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002782 asdl_seq *generators, expr_ty elt, expr_ty val)
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002783{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002784 PyCodeObject *co = NULL;
2785 expr_ty outermost_iter;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002786
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002787 outermost_iter = ((comprehension_ty)
2788 asdl_seq_GET(generators, 0))->iter;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002789
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002790 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2791 goto error;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002792
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002793 if (type != COMP_GENEXP) {
2794 int op;
2795 switch (type) {
2796 case COMP_SETCOMP:
2797 op = BUILD_SET;
2798 break;
2799 case COMP_DICTCOMP:
2800 op = BUILD_MAP;
2801 break;
2802 default:
2803 PyErr_Format(PyExc_SystemError,
2804 "unknown comprehension type %d", type);
2805 goto error_in_scope;
2806 }
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002807
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002808 ADDOP_I(c, op, 0);
2809 }
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002810
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002811 if (!compiler_comprehension_generator(c, generators, 0, elt,
2812 val, type))
2813 goto error_in_scope;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002814
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002815 if (type != COMP_GENEXP) {
2816 ADDOP(c, RETURN_VALUE);
2817 }
2818
2819 co = assemble(c, 1);
2820 compiler_exit_scope(c);
2821 if (co == NULL)
2822 goto error;
2823
2824 if (!compiler_make_closure(c, co, 0))
2825 goto error;
2826 Py_DECREF(co);
2827
2828 VISIT(c, expr, outermost_iter);
2829 ADDOP(c, GET_ITER);
2830 ADDOP_I(c, CALL_FUNCTION, 1);
2831 return 1;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002832error_in_scope:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002833 compiler_exit_scope(c);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002834error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002835 Py_XDECREF(co);
2836 return 0;
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002837}
2838
2839static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840compiler_genexp(struct compiler *c, expr_ty e)
2841{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002842 static identifier name;
2843 if (!name) {
2844 name = PyString_FromString("<genexpr>");
2845 if (!name)
2846 return 0;
2847 }
2848 assert(e->kind == GeneratorExp_kind);
2849 return compiler_comprehension(c, e, COMP_GENEXP, name,
2850 e->v.GeneratorExp.generators,
2851 e->v.GeneratorExp.elt, NULL);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002852}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002854static int
2855compiler_setcomp(struct compiler *c, expr_ty e)
2856{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002857 static identifier name;
2858 if (!name) {
2859 name = PyString_FromString("<setcomp>");
2860 if (!name)
2861 return 0;
2862 }
2863 assert(e->kind == SetComp_kind);
2864 return compiler_comprehension(c, e, COMP_SETCOMP, name,
2865 e->v.SetComp.generators,
2866 e->v.SetComp.elt, NULL);
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002867}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868
Alexandre Vassalottib6465472010-01-11 22:36:12 +00002869static int
2870compiler_dictcomp(struct compiler *c, expr_ty e)
2871{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002872 static identifier name;
2873 if (!name) {
2874 name = PyString_FromString("<dictcomp>");
2875 if (!name)
2876 return 0;
2877 }
2878 assert(e->kind == DictComp_kind);
2879 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
2880 e->v.DictComp.generators,
2881 e->v.DictComp.key, e->v.DictComp.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882}
2883
2884static int
2885compiler_visit_keyword(struct compiler *c, keyword_ty k)
2886{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002887 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2888 VISIT(c, expr, k->value);
2889 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890}
2891
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002892/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893 whether they are true or false.
2894
2895 Return values: 1 for true, 0 for false, -1 for non-constant.
2896 */
2897
2898static int
2899expr_constant(expr_ty e)
2900{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002901 switch (e->kind) {
2902 case Num_kind:
2903 return PyObject_IsTrue(e->v.Num.n);
2904 case Str_kind:
2905 return PyObject_IsTrue(e->v.Str.s);
2906 case Name_kind:
2907 /* __debug__ is not assignable, so we can optimize
2908 * it away in if and while statements */
2909 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2910 "__debug__") == 0)
2911 return ! Py_OptimizeFlag;
2912 /* fall through */
2913 default:
2914 return -1;
2915 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916}
2917
Guido van Rossumc2e20742006-02-27 22:32:47 +00002918/*
2919 Implements the with statement from PEP 343.
2920
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002921 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00002922
2923 with EXPR as VAR:
2924 BLOCK
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925
Guido van Rossumc2e20742006-02-27 22:32:47 +00002926 It is implemented roughly as:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002927
Guido van Rossumda5b7012006-05-02 19:47:52 +00002928 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002929 exit = context.__exit__ # not calling it
2930 value = context.__enter__()
2931 try:
2932 VAR = value # if VAR present in the syntax
2933 BLOCK
2934 finally:
2935 if an exception was raised:
Serhiy Storchakaf0aa88f2015-06-11 00:06:27 +03002936 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002937 else:
Serhiy Storchakaf0aa88f2015-06-11 00:06:27 +03002938 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002939 exit(*exc)
2940 */
2941static int
2942compiler_with(struct compiler *c, stmt_ty s)
2943{
Guido van Rossumc2e20742006-02-27 22:32:47 +00002944 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002945
2946 assert(s->kind == With_kind);
2947
Guido van Rossumc2e20742006-02-27 22:32:47 +00002948 block = compiler_new_block(c);
2949 finally = compiler_new_block(c);
2950 if (!block || !finally)
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002951 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002952
Guido van Rossumda5b7012006-05-02 19:47:52 +00002953 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002954 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002955 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002956
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002957 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002958 compiler_use_next_block(c, block);
Benjamin Peterson565d7852010-02-05 02:12:14 +00002959 /* Note that the block is actually called SETUP_WITH in ceval.c, but
2960 functions the same as SETUP_FINALLY except that exceptions are
2961 normalized. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002962 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002963 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002964 }
2965
2966 if (s->v.With.optional_vars) {
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002967 VISIT(c, expr, s->v.With.optional_vars);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002968 }
2969 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002970 /* Discard result from context.__enter__() */
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002971 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002972 }
2973
2974 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002975 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002976
2977 /* End of try block; start the finally block */
2978 ADDOP(c, POP_BLOCK);
2979 compiler_pop_fblock(c, FINALLY_TRY, block);
2980
2981 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2982 compiler_use_next_block(c, finally);
2983 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitroua4d36a92010-06-22 21:42:05 +00002984 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002985
Nick Coghlan7af53be2008-03-07 14:13:28 +00002986 /* Finally block starts; context.__exit__ is on the stack under
2987 the exception or return information. Just issue our magic
2988 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002989 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002990
2991 /* Finally block ends. */
2992 ADDOP(c, END_FINALLY);
2993 compiler_pop_fblock(c, FINALLY_END, finally);
2994 return 1;
2995}
2996
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997static int
2998compiler_visit_expr(struct compiler *c, expr_ty e)
2999{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003000 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003002 /* If expr e has a different line number than the last expr/stmt,
3003 set a new line number for the next instruction.
3004 */
3005 if (e->lineno > c->u->u_lineno) {
3006 c->u->u_lineno = e->lineno;
3007 c->u->u_lineno_set = false;
3008 }
3009 switch (e->kind) {
3010 case BoolOp_kind:
3011 return compiler_boolop(c, e);
3012 case BinOp_kind:
3013 VISIT(c, expr, e->v.BinOp.left);
3014 VISIT(c, expr, e->v.BinOp.right);
3015 ADDOP(c, binop(c, e->v.BinOp.op));
3016 break;
3017 case UnaryOp_kind:
3018 VISIT(c, expr, e->v.UnaryOp.operand);
3019 ADDOP(c, unaryop(e->v.UnaryOp.op));
3020 break;
3021 case Lambda_kind:
3022 return compiler_lambda(c, e);
3023 case IfExp_kind:
3024 return compiler_ifexp(c, e);
3025 case Dict_kind:
3026 n = asdl_seq_LEN(e->v.Dict.values);
3027 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3028 for (i = 0; i < n; i++) {
3029 VISIT(c, expr,
3030 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3031 VISIT(c, expr,
3032 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3033 ADDOP(c, STORE_MAP);
3034 }
3035 break;
3036 case Set_kind:
3037 n = asdl_seq_LEN(e->v.Set.elts);
3038 VISIT_SEQ(c, expr, e->v.Set.elts);
3039 ADDOP_I(c, BUILD_SET, n);
3040 break;
3041 case ListComp_kind:
3042 return compiler_listcomp(c, e);
3043 case SetComp_kind:
3044 return compiler_setcomp(c, e);
3045 case DictComp_kind:
3046 return compiler_dictcomp(c, e);
3047 case GeneratorExp_kind:
3048 return compiler_genexp(c, e);
3049 case Yield_kind:
3050 if (c->u->u_ste->ste_type != FunctionBlock)
3051 return compiler_error(c, "'yield' outside function");
3052 if (e->v.Yield.value) {
3053 VISIT(c, expr, e->v.Yield.value);
3054 }
3055 else {
3056 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3057 }
3058 ADDOP(c, YIELD_VALUE);
3059 break;
3060 case Compare_kind:
3061 return compiler_compare(c, e);
3062 case Call_kind:
3063 return compiler_call(c, e);
3064 case Repr_kind:
3065 VISIT(c, expr, e->v.Repr.value);
3066 ADDOP(c, UNARY_CONVERT);
3067 break;
3068 case Num_kind:
3069 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3070 break;
3071 case Str_kind:
3072 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3073 break;
3074 /* The following exprs can be assignment targets. */
3075 case Attribute_kind:
3076 if (e->v.Attribute.ctx != AugStore)
3077 VISIT(c, expr, e->v.Attribute.value);
3078 switch (e->v.Attribute.ctx) {
3079 case AugLoad:
3080 ADDOP(c, DUP_TOP);
3081 /* Fall through to load */
3082 case Load:
3083 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3084 break;
3085 case AugStore:
3086 ADDOP(c, ROT_TWO);
3087 /* Fall through to save */
3088 case Store:
3089 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3090 break;
3091 case Del:
3092 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3093 break;
3094 case Param:
3095 default:
3096 PyErr_SetString(PyExc_SystemError,
3097 "param invalid in attribute expression");
3098 return 0;
3099 }
3100 break;
3101 case Subscript_kind:
3102 switch (e->v.Subscript.ctx) {
3103 case AugLoad:
3104 VISIT(c, expr, e->v.Subscript.value);
3105 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3106 break;
3107 case Load:
3108 VISIT(c, expr, e->v.Subscript.value);
3109 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3110 break;
3111 case AugStore:
3112 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3113 break;
3114 case Store:
3115 VISIT(c, expr, e->v.Subscript.value);
3116 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3117 break;
3118 case Del:
3119 VISIT(c, expr, e->v.Subscript.value);
3120 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3121 break;
3122 case Param:
3123 default:
3124 PyErr_SetString(PyExc_SystemError,
3125 "param invalid in subscript expression");
3126 return 0;
3127 }
3128 break;
3129 case Name_kind:
3130 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3131 /* child nodes of List and Tuple will have expr_context set */
3132 case List_kind:
3133 return compiler_list(c, e);
3134 case Tuple_kind:
3135 return compiler_tuple(c, e);
3136 }
3137 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138}
3139
3140static int
3141compiler_augassign(struct compiler *c, stmt_ty s)
3142{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003143 expr_ty e = s->v.AugAssign.target;
3144 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003146 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003148 switch (e->kind) {
3149 case Attribute_kind:
3150 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3151 AugLoad, e->lineno, e->col_offset, c->c_arena);
3152 if (auge == NULL)
3153 return 0;
3154 VISIT(c, expr, auge);
3155 VISIT(c, expr, s->v.AugAssign.value);
3156 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3157 auge->v.Attribute.ctx = AugStore;
3158 VISIT(c, expr, auge);
3159 break;
3160 case Subscript_kind:
3161 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3162 AugLoad, e->lineno, e->col_offset, c->c_arena);
3163 if (auge == NULL)
3164 return 0;
3165 VISIT(c, expr, auge);
3166 VISIT(c, expr, s->v.AugAssign.value);
3167 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3168 auge->v.Subscript.ctx = AugStore;
3169 VISIT(c, expr, auge);
3170 break;
3171 case Name_kind:
3172 if (!compiler_nameop(c, e->v.Name.id, Load))
3173 return 0;
3174 VISIT(c, expr, s->v.AugAssign.value);
3175 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3176 return compiler_nameop(c, e->v.Name.id, Store);
3177 default:
3178 PyErr_Format(PyExc_SystemError,
3179 "invalid node type (%d) for augmented assignment",
3180 e->kind);
3181 return 0;
3182 }
3183 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184}
3185
3186static int
3187compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3188{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003189 struct fblockinfo *f;
3190 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3191 PyErr_SetString(PyExc_SystemError,
3192 "too many statically nested blocks");
3193 return 0;
3194 }
3195 f = &c->u->u_fblock[c->u->u_nfblocks++];
3196 f->fb_type = t;
3197 f->fb_block = b;
3198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199}
3200
3201static void
3202compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3203{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003204 struct compiler_unit *u = c->u;
3205 assert(u->u_nfblocks > 0);
3206 u->u_nfblocks--;
3207 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3208 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209}
3210
Jeremy Hylton82271f12006-10-04 02:24:52 +00003211static int
3212compiler_in_loop(struct compiler *c) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003213 int i;
3214 struct compiler_unit *u = c->u;
3215 for (i = 0; i < u->u_nfblocks; ++i) {
3216 if (u->u_fblock[i].fb_type == LOOP)
3217 return 1;
3218 }
3219 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003220}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221/* Raises a SyntaxError and returns 0.
3222 If something goes wrong, a different exception may be raised.
3223*/
3224
3225static int
3226compiler_error(struct compiler *c, const char *errstr)
3227{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003228 PyObject *loc;
3229 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003231 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3232 if (!loc) {
3233 Py_INCREF(Py_None);
3234 loc = Py_None;
3235 }
3236 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3237 Py_None, loc);
3238 if (!u)
3239 goto exit;
3240 v = Py_BuildValue("(zO)", errstr, u);
3241 if (!v)
3242 goto exit;
3243 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244 exit:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003245 Py_DECREF(loc);
3246 Py_XDECREF(u);
3247 Py_XDECREF(v);
3248 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249}
3250
3251static int
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003252compiler_handle_subscr(struct compiler *c, const char *kind,
3253 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003255 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003257 /* XXX this code is duplicated */
3258 switch (ctx) {
3259 case AugLoad: /* fall through to Load */
3260 case Load: op = BINARY_SUBSCR; break;
3261 case AugStore:/* fall through to Store */
3262 case Store: op = STORE_SUBSCR; break;
3263 case Del: op = DELETE_SUBSCR; break;
3264 case Param:
3265 PyErr_Format(PyExc_SystemError,
3266 "invalid %s kind %d in subscript\n",
3267 kind, ctx);
3268 return 0;
3269 }
3270 if (ctx == AugLoad) {
3271 ADDOP_I(c, DUP_TOPX, 2);
3272 }
3273 else if (ctx == AugStore) {
3274 ADDOP(c, ROT_THREE);
3275 }
3276 ADDOP(c, op);
3277 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278}
3279
3280static int
3281compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3282{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003283 int n = 2;
3284 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003286 /* only handles the cases where BUILD_SLICE is emitted */
3287 if (s->v.Slice.lower) {
3288 VISIT(c, expr, s->v.Slice.lower);
3289 }
3290 else {
3291 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3292 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003294 if (s->v.Slice.upper) {
3295 VISIT(c, expr, s->v.Slice.upper);
3296 }
3297 else {
3298 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3299 }
3300
3301 if (s->v.Slice.step) {
3302 n++;
3303 VISIT(c, expr, s->v.Slice.step);
3304 }
3305 ADDOP_I(c, BUILD_SLICE, n);
3306 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307}
3308
3309static int
3310compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3311{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003312 int op = 0, slice_offset = 0, stack_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003314 assert(s->v.Slice.step == NULL);
3315 if (s->v.Slice.lower) {
3316 slice_offset++;
3317 stack_count++;
3318 if (ctx != AugStore)
3319 VISIT(c, expr, s->v.Slice.lower);
3320 }
3321 if (s->v.Slice.upper) {
3322 slice_offset += 2;
3323 stack_count++;
3324 if (ctx != AugStore)
3325 VISIT(c, expr, s->v.Slice.upper);
3326 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003328 if (ctx == AugLoad) {
3329 switch (stack_count) {
3330 case 0: ADDOP(c, DUP_TOP); break;
3331 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3332 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3333 }
3334 }
3335 else if (ctx == AugStore) {
3336 switch (stack_count) {
3337 case 0: ADDOP(c, ROT_TWO); break;
3338 case 1: ADDOP(c, ROT_THREE); break;
3339 case 2: ADDOP(c, ROT_FOUR); break;
3340 }
3341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003343 switch (ctx) {
3344 case AugLoad: /* fall through to Load */
3345 case Load: op = SLICE; break;
3346 case AugStore:/* fall through to Store */
3347 case Store: op = STORE_SLICE; break;
3348 case Del: op = DELETE_SLICE; break;
3349 case Param:
3350 default:
3351 PyErr_SetString(PyExc_SystemError,
3352 "param invalid in simple slice");
3353 return 0;
3354 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003356 ADDOP(c, op + slice_offset);
3357 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358}
3359
3360static int
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003361compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3362 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003364 switch (s->kind) {
3365 case Ellipsis_kind:
3366 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3367 break;
3368 case Slice_kind:
3369 return compiler_slice(c, s, ctx);
3370 case Index_kind:
3371 VISIT(c, expr, s->v.Index.value);
3372 break;
3373 case ExtSlice_kind:
3374 default:
3375 PyErr_SetString(PyExc_SystemError,
3376 "extended slice invalid in nested slice");
3377 return 0;
3378 }
3379 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380}
3381
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382static int
3383compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3384{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003385 char * kindname = NULL;
3386 switch (s->kind) {
3387 case Index_kind:
3388 kindname = "index";
3389 if (ctx != AugStore) {
3390 VISIT(c, expr, s->v.Index.value);
3391 }
3392 break;
3393 case Ellipsis_kind:
3394 kindname = "ellipsis";
3395 if (ctx != AugStore) {
3396 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3397 }
3398 break;
3399 case Slice_kind:
3400 kindname = "slice";
3401 if (!s->v.Slice.step)
3402 return compiler_simple_slice(c, s, ctx);
3403 if (ctx != AugStore) {
3404 if (!compiler_slice(c, s, ctx))
3405 return 0;
3406 }
3407 break;
3408 case ExtSlice_kind:
3409 kindname = "extended slice";
3410 if (ctx != AugStore) {
3411 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3412 for (i = 0; i < n; i++) {
3413 slice_ty sub = (slice_ty)asdl_seq_GET(
3414 s->v.ExtSlice.dims, i);
3415 if (!compiler_visit_nested_slice(c, sub, ctx))
3416 return 0;
3417 }
3418 ADDOP_I(c, BUILD_TUPLE, n);
3419 }
3420 break;
3421 default:
3422 PyErr_Format(PyExc_SystemError,
3423 "invalid subscript kind %d", s->kind);
3424 return 0;
3425 }
3426 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427}
3428
Neal Norwitzf733a012006-10-29 18:30:10 +00003429
3430/* End of the compiler section, beginning of the assembler section */
3431
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432/* do depth-first search of basic block graph, starting with block.
3433 post records the block indices in post-order.
3434
3435 XXX must handle implicit jumps from one block to next
3436*/
3437
Neal Norwitzf733a012006-10-29 18:30:10 +00003438struct assembler {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003439 PyObject *a_bytecode; /* string containing bytecode */
3440 int a_offset; /* offset into bytecode */
3441 int a_nblocks; /* number of reachable blocks */
3442 basicblock **a_postorder; /* list of blocks in dfs postorder */
3443 PyObject *a_lnotab; /* string containing lnotab */
3444 int a_lnotab_off; /* offset into lnotab */
3445 int a_lineno; /* last lineno of emitted instruction */
3446 int a_lineno_off; /* bytecode offset of last lineno */
Neal Norwitzf733a012006-10-29 18:30:10 +00003447};
3448
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003449static void
3450dfs(struct compiler *c, basicblock *b, struct assembler *a)
3451{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003452 int i;
3453 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003455 if (b->b_seen)
3456 return;
3457 b->b_seen = 1;
3458 if (b->b_next != NULL)
3459 dfs(c, b->b_next, a);
3460 for (i = 0; i < b->b_iused; i++) {
3461 instr = &b->b_instr[i];
3462 if (instr->i_jrel || instr->i_jabs)
3463 dfs(c, instr->i_target, a);
3464 }
3465 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466}
3467
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003468static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3470{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003471 int i, target_depth;
3472 struct instr *instr;
3473 if (b->b_seen || b->b_startdepth >= depth)
3474 return maxdepth;
3475 b->b_seen = 1;
3476 b->b_startdepth = depth;
3477 for (i = 0; i < b->b_iused; i++) {
3478 instr = &b->b_instr[i];
3479 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3480 if (depth > maxdepth)
3481 maxdepth = depth;
3482 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3483 if (instr->i_jrel || instr->i_jabs) {
3484 target_depth = depth;
3485 if (instr->i_opcode == FOR_ITER) {
3486 target_depth = depth-2;
Antoine Pitrouab4a6912014-05-23 11:46:03 +02003487 }
3488 else if (instr->i_opcode == SETUP_FINALLY ||
3489 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003490 target_depth = depth+3;
3491 if (target_depth > maxdepth)
3492 maxdepth = target_depth;
3493 }
Antoine Pitrouab4a6912014-05-23 11:46:03 +02003494 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
3495 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
3496 depth = depth - 1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003497 maxdepth = stackdepth_walk(c, instr->i_target,
3498 target_depth, maxdepth);
3499 if (instr->i_opcode == JUMP_ABSOLUTE ||
3500 instr->i_opcode == JUMP_FORWARD) {
3501 goto out; /* remaining code is dead */
3502 }
3503 }
3504 }
3505 if (b->b_next)
3506 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507out:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003508 b->b_seen = 0;
3509 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510}
3511
3512/* Find the flow path that needs the largest stack. We assume that
3513 * cycles in the flow graph have no net effect on the stack depth.
3514 */
3515static int
3516stackdepth(struct compiler *c)
3517{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003518 basicblock *b, *entryblock;
3519 entryblock = NULL;
3520 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3521 b->b_seen = 0;
3522 b->b_startdepth = INT_MIN;
3523 entryblock = b;
3524 }
3525 if (!entryblock)
3526 return 0;
3527 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528}
3529
3530static int
3531assemble_init(struct assembler *a, int nblocks, int firstlineno)
3532{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003533 memset(a, 0, sizeof(struct assembler));
3534 a->a_lineno = firstlineno;
3535 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3536 if (!a->a_bytecode)
3537 return 0;
3538 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3539 if (!a->a_lnotab)
3540 return 0;
3541 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3542 PyErr_NoMemory();
3543 return 0;
3544 }
3545 a->a_postorder = (basicblock **)PyObject_Malloc(
3546 sizeof(basicblock *) * nblocks);
3547 if (!a->a_postorder) {
3548 PyErr_NoMemory();
3549 return 0;
3550 }
3551 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552}
3553
3554static void
3555assemble_free(struct assembler *a)
3556{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003557 Py_XDECREF(a->a_bytecode);
3558 Py_XDECREF(a->a_lnotab);
3559 if (a->a_postorder)
3560 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561}
3562
3563/* Return the size of a basic block in bytes. */
3564
3565static int
3566instrsize(struct instr *instr)
3567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003568 if (!instr->i_hasarg)
3569 return 1; /* 1 byte for the opcode*/
3570 if (instr->i_oparg > 0xffff)
3571 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3572 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573}
3574
3575static int
3576blocksize(basicblock *b)
3577{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003578 int i;
3579 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003581 for (i = 0; i < b->b_iused; i++)
3582 size += instrsize(&b->b_instr[i]);
3583 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584}
3585
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003586/* Appends a pair to the end of the line number table, a_lnotab, representing
3587 the instruction's bytecode offset and line number. See
3588 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003589
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003590static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003592{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003593 int d_bytecode, d_lineno;
3594 int len;
3595 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003597 d_bytecode = a->a_offset - a->a_lineno_off;
3598 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003600 assert(d_bytecode >= 0);
3601 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003603 if(d_bytecode == 0 && d_lineno == 0)
3604 return 1;
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003605
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003606 if (d_bytecode > 255) {
3607 int j, nbytes, ncodes = d_bytecode / 255;
3608 nbytes = a->a_lnotab_off + 2 * ncodes;
3609 len = PyString_GET_SIZE(a->a_lnotab);
3610 if (nbytes >= len) {
3611 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3612 len = nbytes;
3613 else if (len <= INT_MAX / 2)
3614 len *= 2;
3615 else {
3616 PyErr_NoMemory();
3617 return 0;
3618 }
3619 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3620 return 0;
3621 }
3622 lnotab = (unsigned char *)
3623 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3624 for (j = 0; j < ncodes; j++) {
3625 *lnotab++ = 255;
3626 *lnotab++ = 0;
3627 }
3628 d_bytecode -= ncodes * 255;
3629 a->a_lnotab_off += ncodes * 2;
3630 }
3631 assert(d_bytecode <= 255);
3632 if (d_lineno > 255) {
3633 int j, nbytes, ncodes = d_lineno / 255;
3634 nbytes = a->a_lnotab_off + 2 * ncodes;
3635 len = PyString_GET_SIZE(a->a_lnotab);
3636 if (nbytes >= len) {
3637 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3638 len = nbytes;
3639 else if (len <= INT_MAX / 2)
3640 len *= 2;
3641 else {
3642 PyErr_NoMemory();
3643 return 0;
3644 }
3645 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3646 return 0;
3647 }
3648 lnotab = (unsigned char *)
3649 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3650 *lnotab++ = d_bytecode;
3651 *lnotab++ = 255;
3652 d_bytecode = 0;
3653 for (j = 1; j < ncodes; j++) {
3654 *lnotab++ = 0;
3655 *lnotab++ = 255;
3656 }
3657 d_lineno -= ncodes * 255;
3658 a->a_lnotab_off += ncodes * 2;
3659 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003660
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003661 len = PyString_GET_SIZE(a->a_lnotab);
3662 if (a->a_lnotab_off + 2 >= len) {
3663 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
3664 return 0;
3665 }
3666 lnotab = (unsigned char *)
3667 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003668
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003669 a->a_lnotab_off += 2;
3670 if (d_bytecode) {
3671 *lnotab++ = d_bytecode;
3672 *lnotab++ = d_lineno;
3673 }
3674 else { /* First line of a block; def stmt, etc. */
3675 *lnotab++ = 0;
3676 *lnotab++ = d_lineno;
3677 }
3678 a->a_lineno = i->i_lineno;
3679 a->a_lineno_off = a->a_offset;
3680 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003681}
3682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683/* assemble_emit()
3684 Extend the bytecode with a new instruction.
3685 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003686*/
3687
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003688static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003690{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003691 int size, arg = 0, ext = 0;
3692 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
3693 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003695 size = instrsize(i);
3696 if (i->i_hasarg) {
3697 arg = i->i_oparg;
3698 ext = arg >> 16;
3699 }
3700 if (i->i_lineno && !assemble_lnotab(a, i))
3701 return 0;
3702 if (a->a_offset + size >= len) {
3703 if (len > PY_SSIZE_T_MAX / 2)
3704 return 0;
3705 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
3706 return 0;
3707 }
3708 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3709 a->a_offset += size;
3710 if (size == 6) {
3711 assert(i->i_hasarg);
3712 *code++ = (char)EXTENDED_ARG;
3713 *code++ = ext & 0xff;
3714 *code++ = ext >> 8;
3715 arg &= 0xffff;
3716 }
3717 *code++ = i->i_opcode;
3718 if (i->i_hasarg) {
3719 assert(size == 3 || size == 6);
3720 *code++ = arg & 0xff;
3721 *code++ = arg >> 8;
3722 }
3723 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003724}
3725
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003726static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003728{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003729 basicblock *b;
3730 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3731 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003732
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003733 /* Compute the size of each block and fixup jump args.
3734 Replace block pointer with position in bytecode. */
3735 do {
3736 totsize = 0;
3737 for (i = a->a_nblocks - 1; i >= 0; i--) {
3738 b = a->a_postorder[i];
3739 bsize = blocksize(b);
3740 b->b_offset = totsize;
3741 totsize += bsize;
3742 }
3743 last_extended_arg_count = extended_arg_count;
3744 extended_arg_count = 0;
3745 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3746 bsize = b->b_offset;
3747 for (i = 0; i < b->b_iused; i++) {
3748 struct instr *instr = &b->b_instr[i];
3749 /* Relative jumps are computed relative to
3750 the instruction pointer after fetching
3751 the jump instruction.
3752 */
3753 bsize += instrsize(instr);
3754 if (instr->i_jabs)
3755 instr->i_oparg = instr->i_target->b_offset;
3756 else if (instr->i_jrel) {
3757 int delta = instr->i_target->b_offset - bsize;
3758 instr->i_oparg = delta;
3759 }
3760 else
3761 continue;
3762 if (instr->i_oparg > 0xffff)
3763 extended_arg_count++;
3764 }
3765 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003766
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003767 /* XXX: This is an awful hack that could hurt performance, but
3768 on the bright side it should work until we come up
3769 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003770
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003771 The issue is that in the first loop blocksize() is called
3772 which calls instrsize() which requires i_oparg be set
3773 appropriately. There is a bootstrap problem because
3774 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003775
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003776 So we loop until we stop seeing new EXTENDED_ARGs.
3777 The only EXTENDED_ARGs that could be popping up are
3778 ones in jump instructions. So this should converge
3779 fairly quickly.
3780 */
3781 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003782}
3783
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003784static PyObject *
3785dict_keys_inorder(PyObject *dict, int offset)
3786{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003787 PyObject *tuple, *k, *v;
3788 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003789
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003790 tuple = PyTuple_New(size);
3791 if (tuple == NULL)
3792 return NULL;
3793 while (PyDict_Next(dict, &pos, &k, &v)) {
3794 i = PyInt_AS_LONG(v);
3795 /* The keys of the dictionary are tuples. (see compiler_add_o)
3796 The object we want is always first, though. */
3797 k = PyTuple_GET_ITEM(k, 0);
3798 Py_INCREF(k);
3799 assert((i - offset) < size);
3800 assert((i - offset) >= 0);
3801 PyTuple_SET_ITEM(tuple, i - offset, k);
3802 }
3803 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003804}
3805
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003806static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003808{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003809 PySTEntryObject *ste = c->u->u_ste;
3810 int flags = 0, n;
3811 if (ste->ste_type != ModuleBlock)
3812 flags |= CO_NEWLOCALS;
3813 if (ste->ste_type == FunctionBlock) {
3814 if (!ste->ste_unoptimized)
3815 flags |= CO_OPTIMIZED;
3816 if (ste->ste_nested)
3817 flags |= CO_NESTED;
3818 if (ste->ste_generator)
3819 flags |= CO_GENERATOR;
3820 if (ste->ste_varargs)
3821 flags |= CO_VARARGS;
3822 if (ste->ste_varkeywords)
3823 flags |= CO_VARKEYWORDS;
3824 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003825
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003826 /* (Only) inherit compilerflags in PyCF_MASK */
3827 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003828
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003829 n = PyDict_Size(c->u->u_freevars);
3830 if (n < 0)
3831 return -1;
3832 if (n == 0) {
3833 n = PyDict_Size(c->u->u_cellvars);
3834 if (n < 0)
3835 return -1;
3836 if (n == 0) {
3837 flags |= CO_NOFREE;
3838 }
3839 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003840
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003841 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003842}
3843
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003844static PyCodeObject *
3845makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003846{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003847 PyObject *tmp;
3848 PyCodeObject *co = NULL;
3849 PyObject *consts = NULL;
3850 PyObject *names = NULL;
3851 PyObject *varnames = NULL;
3852 PyObject *filename = NULL;
3853 PyObject *name = NULL;
3854 PyObject *freevars = NULL;
3855 PyObject *cellvars = NULL;
3856 PyObject *bytecode = NULL;
3857 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003858
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003859 tmp = dict_keys_inorder(c->u->u_consts, 0);
3860 if (!tmp)
3861 goto error;
3862 consts = PySequence_List(tmp); /* optimize_code requires a list */
3863 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003865 names = dict_keys_inorder(c->u->u_names, 0);
3866 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3867 if (!consts || !names || !varnames)
3868 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003869
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003870 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3871 if (!cellvars)
3872 goto error;
3873 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3874 if (!freevars)
3875 goto error;
3876 filename = PyString_FromString(c->c_filename);
3877 if (!filename)
3878 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003879
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003880 nlocals = PyDict_Size(c->u->u_varnames);
3881 flags = compute_code_flags(c);
3882 if (flags < 0)
3883 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003885 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3886 if (!bytecode)
3887 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003889 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3890 if (!tmp)
3891 goto error;
3892 Py_DECREF(consts);
3893 consts = tmp;
3894
3895 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3896 bytecode, consts, names, varnames,
3897 freevars, cellvars,
3898 filename, c->u->u_name,
3899 c->u->u_firstlineno,
3900 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003902 Py_XDECREF(consts);
3903 Py_XDECREF(names);
3904 Py_XDECREF(varnames);
3905 Py_XDECREF(filename);
3906 Py_XDECREF(name);
3907 Py_XDECREF(freevars);
3908 Py_XDECREF(cellvars);
3909 Py_XDECREF(bytecode);
3910 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003911}
3912
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003913
3914/* For debugging purposes only */
3915#if 0
3916static void
3917dump_instr(const struct instr *i)
3918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003919 const char *jrel = i->i_jrel ? "jrel " : "";
3920 const char *jabs = i->i_jabs ? "jabs " : "";
3921 char arg[128];
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003922
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003923 *arg = '\0';
3924 if (i->i_hasarg)
3925 sprintf(arg, "arg: %d ", i->i_oparg);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003926
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003927 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3928 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003929}
3930
3931static void
3932dump_basicblock(const basicblock *b)
3933{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003934 const char *seen = b->b_seen ? "seen " : "";
3935 const char *b_return = b->b_return ? "return " : "";
3936 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3937 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3938 if (b->b_instr) {
3939 int i;
3940 for (i = 0; i < b->b_iused; i++) {
3941 fprintf(stderr, " [%02d] ", i);
3942 dump_instr(b->b_instr + i);
3943 }
3944 }
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003945}
3946#endif
3947
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003948static PyCodeObject *
3949assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003950{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003951 basicblock *b, *entryblock;
3952 struct assembler a;
3953 int i, j, nblocks;
3954 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003955
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003956 /* Make sure every block that falls off the end returns None.
3957 XXX NEXT_BLOCK() isn't quite right, because if the last
3958 block ends with a jump or return b_next shouldn't set.
3959 */
3960 if (!c->u->u_curblock->b_return) {
3961 NEXT_BLOCK(c);
3962 if (addNone)
3963 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3964 ADDOP(c, RETURN_VALUE);
3965 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003966
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003967 nblocks = 0;
3968 entryblock = NULL;
3969 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3970 nblocks++;
3971 entryblock = b;
3972 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003973
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003974 /* Set firstlineno if it wasn't explicitly set. */
3975 if (!c->u->u_firstlineno) {
3976 if (entryblock && entryblock->b_instr)
3977 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3978 else
3979 c->u->u_firstlineno = 1;
3980 }
3981 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3982 goto error;
3983 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003984
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003985 /* Can't modify the bytecode after computing jump offsets. */
3986 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003987
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003988 /* Emit code in reverse postorder from dfs. */
3989 for (i = a.a_nblocks - 1; i >= 0; i--) {
3990 b = a.a_postorder[i];
3991 for (j = 0; j < b->b_iused; j++)
3992 if (!assemble_emit(&a, &b->b_instr[j]))
3993 goto error;
3994 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003995
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003996 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3997 goto error;
3998 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3999 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004000
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004001 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004002 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00004003 assemble_free(&a);
4004 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004005}