blob: d6f640fabb2c1a72882d0852f351111fa5a25b27 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned i_jabs : 1;
47 unsigned i_jrel : 1;
48 unsigned i_hasarg : 1;
49 unsigned char i_opcode;
50 int i_oparg;
51 struct basicblock_ *i_target; /* target block (if jump instruction) */
52 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000053};
54
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000055typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056 /* Each basicblock in a compilation unit is linked via b_list in the
57 reverse order that the block are allocated. b_list points to the next
58 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 struct basicblock_ *b_list;
60 /* number of instructions used */
61 int b_iused;
62 /* length of instruction array (b_instr) */
63 int b_ialloc;
64 /* pointer to an array of instructions, initially NULL */
65 struct instr *b_instr;
66 /* If b_next is non-NULL, it is a pointer to the next
67 block reached by normal control flow. */
68 struct basicblock_ *b_next;
69 /* b_seen is used to perform a DFS of basicblocks. */
70 unsigned b_seen : 1;
71 /* b_return is true if a RETURN_VALUE opcode is inserted. */
72 unsigned b_return : 1;
73 /* depth of stack upon entry of block, computed by stackdepth() */
74 int b_startdepth;
75 /* instruction offset for block, computed by assemble_jump_offsets() */
76 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077} basicblock;
78
79/* fblockinfo tracks the current frame block.
80
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081A frame block is used to handle loops, try/except, and try/finally.
82It's called a frame block to distinguish it from a basic block in the
83compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084*/
85
86enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
87
88struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 enum fblocktype fb_type;
90 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091};
92
93/* The following items change on entry and exit of code blocks.
94 They must be saved and restored when returning to a block.
95*/
96struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 PyObject *u_name;
100 /* The following fields are dicts that map objects to
101 the index of them in co_XXX. The index is used as
102 the argument for opcodes that refer to those collections.
103 */
104 PyObject *u_consts; /* all constants */
105 PyObject *u_names; /* all names */
106 PyObject *u_varnames; /* local variables */
107 PyObject *u_cellvars; /* cell variables */
108 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 int u_argcount; /* number of arguments for block */
113 int u_kwonlyargcount; /* number of keyword only 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 Pitrouf95a1b32010-05-09 15:52:27 +0000119 int u_nfblocks;
120 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 int u_firstlineno; /* the first lineno of the block */
123 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000124 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 int u_lineno_set; /* boolean to indicate whether instr
126 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127};
128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000131The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000133managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134*/
135
136struct compiler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 const char *c_filename;
138 struct symtable *c_st;
139 PyFutureFeatures *c_future; /* pointer to module's __future__ */
140 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Georg Brandl8334fd92010-12-04 10:26:46 +0000142 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 int c_interactive; /* true if in interactive mode */
144 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 struct compiler_unit *u; /* compiler state for current block */
147 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
148 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149};
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151static int compiler_enter_scope(struct compiler *, identifier, void *, int);
152static void compiler_free(struct compiler *);
153static basicblock *compiler_new_block(struct compiler *);
154static int compiler_next_instr(struct compiler *, basicblock *);
155static int compiler_addop(struct compiler *, int);
156static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
157static int compiler_addop_i(struct compiler *, int, int);
158static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159static basicblock *compiler_use_new_block(struct compiler *);
160static int compiler_error(struct compiler *, const char *);
161static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
162
163static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
164static int compiler_visit_stmt(struct compiler *, stmt_ty);
165static int compiler_visit_keyword(struct compiler *, keyword_ty);
166static int compiler_visit_expr(struct compiler *, expr_ty);
167static int compiler_augassign(struct compiler *, stmt_ty);
168static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170
171static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175/* Returns true if there is a loop on the fblock stack. */
176static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177
178static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000179static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180
Guido van Rossumc2e20742006-02-27 22:32:47 +0000181static int compiler_with(struct compiler *, stmt_ty);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000182static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 asdl_seq *args,
184 asdl_seq *keywords,
185 expr_ty starargs,
186 expr_ty kwargs);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static PyCodeObject *assemble(struct compiler *, int addNone);
189static PyObject *__doc__;
190
Benjamin Petersonb173f782009-05-05 22:31:58 +0000191#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Name mangling: __private becomes _classname__private.
197 This is independent from how the name is used. */
198 const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident);
199 Py_UNICODE *buffer;
200 size_t nlen, plen;
201 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
202 name == NULL || name[0] != '_' || name[1] != '_') {
203 Py_INCREF(ident);
204 return ident;
205 }
206 p = PyUnicode_AS_UNICODE(privateobj);
207 nlen = Py_UNICODE_strlen(name);
208 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 The only time a name with a dot can occur is when
211 we are compiling an import statement that has a
212 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 TODO(jhylton): Decide whether we want to support
215 mangling of the module name, e.g. __M.X.
216 */
217 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
218 || Py_UNICODE_strchr(name, '.')) {
219 Py_INCREF(ident);
220 return ident; /* Don't mangle __whatever__ */
221 }
222 /* Strip leading underscores from class name */
223 while (*p == '_')
224 p++;
225 if (*p == 0) {
226 Py_INCREF(ident);
227 return ident; /* Don't mangle if class is just underscores */
228 }
229 plen = Py_UNICODE_strlen(p);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 assert(1 <= PY_SSIZE_T_MAX - nlen);
232 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen);
235 if (!ident)
236 return 0;
237 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
238 buffer = PyUnicode_AS_UNICODE(ident);
239 buffer[0] = '_';
240 Py_UNICODE_strncpy(buffer+1, p, plen);
241 Py_UNICODE_strcpy(buffer+1+plen, name);
242 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000243}
244
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245static int
246compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 c->c_stack = PyList_New(0);
251 if (!c->c_stack)
252 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255}
256
257PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +0000258PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
259 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 struct compiler c;
262 PyCodeObject *co = NULL;
263 PyCompilerFlags local_flags;
264 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (!__doc__) {
267 __doc__ = PyUnicode_InternFromString("__doc__");
268 if (!__doc__)
269 return NULL;
270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (!compiler_init(&c))
273 return NULL;
274 c.c_filename = filename;
275 c.c_arena = arena;
276 c.c_future = PyFuture_FromAST(mod, filename);
277 if (c.c_future == NULL)
278 goto finally;
279 if (!flags) {
280 local_flags.cf_flags = 0;
281 flags = &local_flags;
282 }
283 merged = c.c_future->ff_features | flags->cf_flags;
284 c.c_future->ff_features = merged;
285 flags->cf_flags = merged;
286 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000287 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 c.c_st = PySymtable_Build(mod, filename, c.c_future);
291 if (c.c_st == NULL) {
292 if (!PyErr_Occurred())
293 PyErr_SetString(PyExc_SystemError, "no symtable");
294 goto finally;
295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298
Thomas Wouters1175c432006-02-27 22:49:54 +0000299 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 compiler_free(&c);
301 assert(co || PyErr_Occurred());
302 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303}
304
305PyCodeObject *
306PyNode_Compile(struct _node *n, const char *filename)
307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 PyCodeObject *co = NULL;
309 mod_ty mod;
310 PyArena *arena = PyArena_New();
311 if (!arena)
312 return NULL;
313 mod = PyAST_FromNode(n, NULL, filename, arena);
314 if (mod)
315 co = PyAST_Compile(mod, filename, NULL, arena);
316 PyArena_Free(arena);
317 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000318}
319
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (c->c_st)
324 PySymtable_Free(c->c_st);
325 if (c->c_future)
326 PyObject_Free(c->c_future);
327 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000328}
329
Guido van Rossum79f25d91997-04-29 20:08:16 +0000330static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 Py_ssize_t i, n;
334 PyObject *v, *k;
335 PyObject *dict = PyDict_New();
336 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 n = PyList_Size(list);
339 for (i = 0; i < n; i++) {
340 v = PyLong_FromLong(i);
341 if (!v) {
342 Py_DECREF(dict);
343 return NULL;
344 }
345 k = PyList_GET_ITEM(list, i);
346 k = PyTuple_Pack(2, k, k->ob_type);
347 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
348 Py_XDECREF(k);
349 Py_DECREF(v);
350 Py_DECREF(dict);
351 return NULL;
352 }
353 Py_DECREF(k);
354 Py_DECREF(v);
355 }
356 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357}
358
359/* Return new dict containing names from src that match scope(s).
360
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000361src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000363values are integers, starting at offset and increasing by one for
364each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365*/
366
367static PyObject *
368dictbytype(PyObject *src, int scope_type, int flag, int offset)
369{
Meador Inge996ae042012-07-18 17:57:46 -0500370 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500372 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 assert(offset >= 0);
375 if (dest == NULL)
376 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377
Meador Inge2ca63152012-07-18 14:20:11 -0500378 /* Sort the keys so that we have a deterministic order on the indexes
379 saved in the returned dictionary. These indexes are used as indexes
380 into the free and cell var storage. Therefore if they aren't
381 deterministic, then the generated bytecode is not deterministic.
382 */
383 sorted_keys = PyDict_Keys(src);
384 if (sorted_keys == NULL)
385 return NULL;
386 if (PyList_Sort(sorted_keys) != 0) {
387 Py_DECREF(sorted_keys);
388 return NULL;
389 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500390 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500391
392 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* XXX this should probably be a macro in symtable.h */
394 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500395 k = PyList_GET_ITEM(sorted_keys, key_i);
396 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 assert(PyLong_Check(v));
398 vi = PyLong_AS_LONG(v);
399 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (scope == scope_type || vi & flag) {
402 PyObject *tuple, *item = PyLong_FromLong(i);
403 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500404 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 Py_DECREF(dest);
406 return NULL;
407 }
408 i++;
409 tuple = PyTuple_Pack(2, k, k->ob_type);
410 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500411 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 Py_DECREF(item);
413 Py_DECREF(dest);
414 Py_XDECREF(tuple);
415 return NULL;
416 }
417 Py_DECREF(item);
418 Py_DECREF(tuple);
419 }
420 }
Meador Inge2ca63152012-07-18 14:20:11 -0500421 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000423}
424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425static void
426compiler_unit_check(struct compiler_unit *u)
427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 basicblock *block;
429 for (block = u->u_blocks; block != NULL; block = block->b_list) {
430 assert((void *)block != (void *)0xcbcbcbcb);
431 assert((void *)block != (void *)0xfbfbfbfb);
432 assert((void *)block != (void *)0xdbdbdbdb);
433 if (block->b_instr != NULL) {
434 assert(block->b_ialloc > 0);
435 assert(block->b_iused > 0);
436 assert(block->b_ialloc >= block->b_iused);
437 }
438 else {
439 assert (block->b_iused == 0);
440 assert (block->b_ialloc == 0);
441 }
442 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443}
444
445static void
446compiler_unit_free(struct compiler_unit *u)
447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 compiler_unit_check(u);
451 b = u->u_blocks;
452 while (b != NULL) {
453 if (b->b_instr)
454 PyObject_Free((void *)b->b_instr);
455 next = b->b_list;
456 PyObject_Free((void *)b);
457 b = next;
458 }
459 Py_CLEAR(u->u_ste);
460 Py_CLEAR(u->u_name);
461 Py_CLEAR(u->u_consts);
462 Py_CLEAR(u->u_names);
463 Py_CLEAR(u->u_varnames);
464 Py_CLEAR(u->u_freevars);
465 Py_CLEAR(u->u_cellvars);
466 Py_CLEAR(u->u_private);
467 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468}
469
470static int
471compiler_enter_scope(struct compiler *c, identifier name, void *key,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
477 struct compiler_unit));
478 if (!u) {
479 PyErr_NoMemory();
480 return 0;
481 }
482 memset(u, 0, sizeof(struct compiler_unit));
483 u->u_argcount = 0;
484 u->u_kwonlyargcount = 0;
485 u->u_ste = PySymtable_Lookup(c->c_st, key);
486 if (!u->u_ste) {
487 compiler_unit_free(u);
488 return 0;
489 }
490 Py_INCREF(name);
491 u->u_name = name;
492 u->u_varnames = list2dict(u->u_ste->ste_varnames);
493 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
494 if (!u->u_varnames || !u->u_cellvars) {
495 compiler_unit_free(u);
496 return 0;
497 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
500 PyDict_Size(u->u_cellvars));
501 if (!u->u_freevars) {
502 compiler_unit_free(u);
503 return 0;
504 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 u->u_blocks = NULL;
507 u->u_nfblocks = 0;
508 u->u_firstlineno = lineno;
509 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000510 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 u->u_lineno_set = 0;
512 u->u_consts = PyDict_New();
513 if (!u->u_consts) {
514 compiler_unit_free(u);
515 return 0;
516 }
517 u->u_names = PyDict_New();
518 if (!u->u_names) {
519 compiler_unit_free(u);
520 return 0;
521 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Push the old compiler_unit on the stack. */
526 if (c->u) {
527 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
528 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
529 Py_XDECREF(capsule);
530 compiler_unit_free(u);
531 return 0;
532 }
533 Py_DECREF(capsule);
534 u->u_private = c->u->u_private;
535 Py_XINCREF(u->u_private);
536 }
537 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 c->c_nestlevel++;
540 if (compiler_use_new_block(c) == NULL)
541 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544}
545
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000546static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547compiler_exit_scope(struct compiler *c)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 int n;
550 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 c->c_nestlevel--;
553 compiler_unit_free(c->u);
554 /* Restore c->u to the parent unit. */
555 n = PyList_GET_SIZE(c->c_stack) - 1;
556 if (n >= 0) {
557 capsule = PyList_GET_ITEM(c->c_stack, n);
558 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
559 assert(c->u);
560 /* we are deleting from a list so this really shouldn't fail */
561 if (PySequence_DelItem(c->c_stack, n) < 0)
562 Py_FatalError("compiler_exit_scope()");
563 compiler_unit_check(c->u);
564 }
565 else
566 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000568}
569
570/* Allocate a new block and return a pointer to it.
571 Returns NULL on error.
572*/
573
574static basicblock *
575compiler_new_block(struct compiler *c)
576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 basicblock *b;
578 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 u = c->u;
581 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
582 if (b == NULL) {
583 PyErr_NoMemory();
584 return NULL;
585 }
586 memset((void *)b, 0, sizeof(basicblock));
587 /* Extend the singly linked list of blocks with new block. */
588 b->b_list = u->u_blocks;
589 u->u_blocks = b;
590 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000591}
592
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593static basicblock *
594compiler_use_new_block(struct compiler *c)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 basicblock *block = compiler_new_block(c);
597 if (block == NULL)
598 return NULL;
599 c->u->u_curblock = block;
600 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000601}
602
603static basicblock *
604compiler_next_block(struct compiler *c)
605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 basicblock *block = compiler_new_block(c);
607 if (block == NULL)
608 return 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
614static basicblock *
615compiler_use_next_block(struct compiler *c, basicblock *block)
616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 assert(block != NULL);
618 c->u->u_curblock->b_next = block;
619 c->u->u_curblock = block;
620 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621}
622
623/* Returns the offset of the next instruction in the current block's
624 b_instr array. Resizes the b_instr as necessary.
625 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000626*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000627
628static int
629compiler_next_instr(struct compiler *c, basicblock *b)
630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 assert(b != NULL);
632 if (b->b_instr == NULL) {
633 b->b_instr = (struct instr *)PyObject_Malloc(
634 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
635 if (b->b_instr == NULL) {
636 PyErr_NoMemory();
637 return -1;
638 }
639 b->b_ialloc = DEFAULT_BLOCK_SIZE;
640 memset((char *)b->b_instr, 0,
641 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
642 }
643 else if (b->b_iused == b->b_ialloc) {
644 struct instr *tmp;
645 size_t oldsize, newsize;
646 oldsize = b->b_ialloc * sizeof(struct instr);
647 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (oldsize > (PY_SIZE_MAX >> 1)) {
650 PyErr_NoMemory();
651 return -1;
652 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (newsize == 0) {
655 PyErr_NoMemory();
656 return -1;
657 }
658 b->b_ialloc <<= 1;
659 tmp = (struct instr *)PyObject_Realloc(
660 (void *)b->b_instr, newsize);
661 if (tmp == NULL) {
662 PyErr_NoMemory();
663 return -1;
664 }
665 b->b_instr = tmp;
666 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
667 }
668 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669}
670
Christian Heimes2202f872008-02-06 14:31:34 +0000671/* Set the i_lineno member of the instruction at offset off if the
672 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000673 already been set. If it has been set, the call has no effect.
674
Christian Heimes2202f872008-02-06 14:31:34 +0000675 The line number is reset in the following cases:
676 - when entering a new scope
677 - on each statement
678 - on each expression that start a new line
679 - before the "except" clause
680 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000681*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683static void
684compiler_set_lineno(struct compiler *c, int off)
685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 basicblock *b;
687 if (c->u->u_lineno_set)
688 return;
689 c->u->u_lineno_set = 1;
690 b = c->u->u_curblock;
691 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000692}
693
694static int
695opcode_stack_effect(int opcode, int oparg)
696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 switch (opcode) {
698 case POP_TOP:
699 return -1;
700 case ROT_TWO:
701 case ROT_THREE:
702 return 0;
703 case DUP_TOP:
704 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000705 case DUP_TOP_TWO:
706 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 case UNARY_POSITIVE:
709 case UNARY_NEGATIVE:
710 case UNARY_NOT:
711 case UNARY_INVERT:
712 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 case SET_ADD:
715 case LIST_APPEND:
716 return -1;
717 case MAP_ADD:
718 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 case BINARY_POWER:
721 case BINARY_MULTIPLY:
722 case BINARY_MODULO:
723 case BINARY_ADD:
724 case BINARY_SUBTRACT:
725 case BINARY_SUBSCR:
726 case BINARY_FLOOR_DIVIDE:
727 case BINARY_TRUE_DIVIDE:
728 return -1;
729 case INPLACE_FLOOR_DIVIDE:
730 case INPLACE_TRUE_DIVIDE:
731 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 case INPLACE_ADD:
734 case INPLACE_SUBTRACT:
735 case INPLACE_MULTIPLY:
736 case INPLACE_MODULO:
737 return -1;
738 case STORE_SUBSCR:
739 return -3;
740 case STORE_MAP:
741 return -2;
742 case DELETE_SUBSCR:
743 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 case BINARY_LSHIFT:
746 case BINARY_RSHIFT:
747 case BINARY_AND:
748 case BINARY_XOR:
749 case BINARY_OR:
750 return -1;
751 case INPLACE_POWER:
752 return -1;
753 case GET_ITER:
754 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 case PRINT_EXPR:
757 return -1;
758 case LOAD_BUILD_CLASS:
759 return 1;
760 case INPLACE_LSHIFT:
761 case INPLACE_RSHIFT:
762 case INPLACE_AND:
763 case INPLACE_XOR:
764 case INPLACE_OR:
765 return -1;
766 case BREAK_LOOP:
767 return 0;
768 case SETUP_WITH:
769 return 7;
770 case WITH_CLEANUP:
771 return -1; /* XXX Sometimes more */
772 case STORE_LOCALS:
773 return -1;
774 case RETURN_VALUE:
775 return -1;
776 case IMPORT_STAR:
777 return -1;
778 case YIELD_VALUE:
779 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 case POP_BLOCK:
782 return 0;
783 case POP_EXCEPT:
784 return 0; /* -3 except if bad bytecode */
785 case END_FINALLY:
786 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 case STORE_NAME:
789 return -1;
790 case DELETE_NAME:
791 return 0;
792 case UNPACK_SEQUENCE:
793 return oparg-1;
794 case UNPACK_EX:
795 return (oparg&0xFF) + (oparg>>8);
796 case FOR_ITER:
797 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 case STORE_ATTR:
800 return -2;
801 case DELETE_ATTR:
802 return -1;
803 case STORE_GLOBAL:
804 return -1;
805 case DELETE_GLOBAL:
806 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 case LOAD_CONST:
808 return 1;
809 case LOAD_NAME:
810 return 1;
811 case BUILD_TUPLE:
812 case BUILD_LIST:
813 case BUILD_SET:
814 return 1-oparg;
815 case BUILD_MAP:
816 return 1;
817 case LOAD_ATTR:
818 return 0;
819 case COMPARE_OP:
820 return -1;
821 case IMPORT_NAME:
822 return -1;
823 case IMPORT_FROM:
824 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 case JUMP_FORWARD:
827 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
828 case JUMP_IF_FALSE_OR_POP: /* "" */
829 case JUMP_ABSOLUTE:
830 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 case POP_JUMP_IF_FALSE:
833 case POP_JUMP_IF_TRUE:
834 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 case LOAD_GLOBAL:
837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 case CONTINUE_LOOP:
840 return 0;
841 case SETUP_LOOP:
842 return 0;
843 case SETUP_EXCEPT:
844 case SETUP_FINALLY:
845 return 6; /* can push 3 values for the new exception
846 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 case LOAD_FAST:
849 return 1;
850 case STORE_FAST:
851 return -1;
852 case DELETE_FAST:
853 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 case RAISE_VARARGS:
856 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000857#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 case CALL_FUNCTION:
859 return -NARGS(oparg);
860 case CALL_FUNCTION_VAR:
861 case CALL_FUNCTION_KW:
862 return -NARGS(oparg)-1;
863 case CALL_FUNCTION_VAR_KW:
864 return -NARGS(oparg)-2;
865 case MAKE_FUNCTION:
866 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
867 case MAKE_CLOSURE:
868 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000869#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case BUILD_SLICE:
871 if (oparg == 3)
872 return -2;
873 else
874 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case LOAD_CLOSURE:
877 return 1;
878 case LOAD_DEREF:
879 return 1;
880 case STORE_DEREF:
881 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000882 case DELETE_DEREF:
883 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 default:
885 fprintf(stderr, "opcode = %d\n", opcode);
886 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 }
889 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000890}
891
892/* Add an opcode with no argument.
893 Returns 0 on failure, 1 on success.
894*/
895
896static int
897compiler_addop(struct compiler *c, int opcode)
898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 basicblock *b;
900 struct instr *i;
901 int off;
902 off = compiler_next_instr(c, c->u->u_curblock);
903 if (off < 0)
904 return 0;
905 b = c->u->u_curblock;
906 i = &b->b_instr[off];
907 i->i_opcode = opcode;
908 i->i_hasarg = 0;
909 if (opcode == RETURN_VALUE)
910 b->b_return = 1;
911 compiler_set_lineno(c, off);
912 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913}
914
915static int
916compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyObject *t, *v;
919 Py_ssize_t arg;
920 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* necessary to make sure types aren't coerced (e.g., int and long) */
923 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
924 if (PyFloat_Check(o)) {
925 d = PyFloat_AS_DOUBLE(o);
926 /* all we need is to make the tuple different in either the 0.0
927 * or -0.0 case from all others, just to avoid the "coercion".
928 */
929 if (d == 0.0 && copysign(1.0, d) < 0.0)
930 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
931 else
932 t = PyTuple_Pack(2, o, o->ob_type);
933 }
934 else if (PyComplex_Check(o)) {
935 Py_complex z;
936 int real_negzero, imag_negzero;
937 /* For the complex case we must make complex(x, 0.)
938 different from complex(x, -0.) and complex(0., y)
939 different from complex(-0., y), for any x and y.
940 All four complex zeros must be distinguished.*/
941 z = PyComplex_AsCComplex(o);
942 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
943 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
944 if (real_negzero && imag_negzero) {
945 t = PyTuple_Pack(5, o, o->ob_type,
946 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +0000947 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 else if (imag_negzero) {
949 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +0000950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 else if (real_negzero) {
952 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
953 }
954 else {
955 t = PyTuple_Pack(2, o, o->ob_type);
956 }
957 }
958 else {
959 t = PyTuple_Pack(2, o, o->ob_type);
960 }
961 if (t == NULL)
962 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 v = PyDict_GetItem(dict, t);
965 if (!v) {
966 if (PyErr_Occurred())
967 return -1;
968 arg = PyDict_Size(dict);
969 v = PyLong_FromLong(arg);
970 if (!v) {
971 Py_DECREF(t);
972 return -1;
973 }
974 if (PyDict_SetItem(dict, t, v) < 0) {
975 Py_DECREF(t);
976 Py_DECREF(v);
977 return -1;
978 }
979 Py_DECREF(v);
980 }
981 else
982 arg = PyLong_AsLong(v);
983 Py_DECREF(t);
984 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985}
986
987static int
988compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990{
991 int arg = compiler_add_o(c, dict, o);
992 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +0000993 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994 return compiler_addop_i(c, opcode, arg);
995}
996
997static int
998compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000{
1001 int arg;
1002 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1003 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005 arg = compiler_add_o(c, dict, mangled);
1006 Py_DECREF(mangled);
1007 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001008 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009 return compiler_addop_i(c, opcode, arg);
1010}
1011
1012/* Add an opcode with an integer argument.
1013 Returns 0 on failure, 1 on success.
1014*/
1015
1016static int
1017compiler_addop_i(struct compiler *c, int opcode, int oparg)
1018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 struct instr *i;
1020 int off;
1021 off = compiler_next_instr(c, c->u->u_curblock);
1022 if (off < 0)
1023 return 0;
1024 i = &c->u->u_curblock->b_instr[off];
1025 i->i_opcode = opcode;
1026 i->i_oparg = oparg;
1027 i->i_hasarg = 1;
1028 compiler_set_lineno(c, off);
1029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030}
1031
1032static int
1033compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 struct instr *i;
1036 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 assert(b != NULL);
1039 off = compiler_next_instr(c, c->u->u_curblock);
1040 if (off < 0)
1041 return 0;
1042 i = &c->u->u_curblock->b_instr[off];
1043 i->i_opcode = opcode;
1044 i->i_target = b;
1045 i->i_hasarg = 1;
1046 if (absolute)
1047 i->i_jabs = 1;
1048 else
1049 i->i_jrel = 1;
1050 compiler_set_lineno(c, off);
1051 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052}
1053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1055 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056 it as the current block. NEXT_BLOCK() also creates an implicit jump
1057 from the current block to the new block.
1058*/
1059
Thomas Wouters89f507f2006-12-13 04:49:30 +00001060/* The returns inside these macros make it impossible to decref objects
1061 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062*/
1063
1064
1065#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (compiler_use_new_block((C)) == NULL) \
1067 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068}
1069
1070#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (compiler_next_block((C)) == NULL) \
1072 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073}
1074
1075#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (!compiler_addop((C), (OP))) \
1077 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078}
1079
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001080#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (!compiler_addop((C), (OP))) { \
1082 compiler_exit_scope(c); \
1083 return 0; \
1084 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001085}
1086
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1089 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001090}
1091
1092#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1094 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095}
1096
1097#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (!compiler_addop_i((C), (OP), (O))) \
1099 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001100}
1101
1102#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (!compiler_addop_j((C), (OP), (O), 1)) \
1104 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105}
1106
1107#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 if (!compiler_addop_j((C), (OP), (O), 0)) \
1109 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001110}
1111
1112/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1113 the ASDL name to synthesize the name of the C type and the visit function.
1114*/
1115
1116#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (!compiler_visit_ ## TYPE((C), (V))) \
1118 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119}
1120
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001121#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (!compiler_visit_ ## TYPE((C), (V))) { \
1123 compiler_exit_scope(c); \
1124 return 0; \
1125 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001126}
1127
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (!compiler_visit_slice((C), (V), (CTX))) \
1130 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131}
1132
1133#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 int _i; \
1135 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1136 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1137 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1138 if (!compiler_visit_ ## TYPE((C), elt)) \
1139 return 0; \
1140 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141}
1142
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001143#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 int _i; \
1145 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1146 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1147 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1148 if (!compiler_visit_ ## TYPE((C), elt)) { \
1149 compiler_exit_scope(c); \
1150 return 0; \
1151 } \
1152 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001153}
1154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155static int
1156compiler_isdocstring(stmt_ty s)
1157{
1158 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001159 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160 return s->v.Expr.value->kind == Str_kind;
1161}
1162
1163/* Compile a sequence of statements, checking for a docstring. */
1164
1165static int
1166compiler_body(struct compiler *c, asdl_seq *stmts)
1167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 int i = 0;
1169 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (!asdl_seq_LEN(stmts))
1172 return 1;
1173 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001174 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 /* don't generate docstrings if -OO */
1176 i = 1;
1177 VISIT(c, expr, st->v.Expr.value);
1178 if (!compiler_nameop(c, __doc__, Store))
1179 return 0;
1180 }
1181 for (; i < asdl_seq_LEN(stmts); i++)
1182 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1183 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184}
1185
1186static PyCodeObject *
1187compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyCodeObject *co;
1190 int addNone = 1;
1191 static PyObject *module;
1192 if (!module) {
1193 module = PyUnicode_InternFromString("<module>");
1194 if (!module)
1195 return NULL;
1196 }
1197 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1198 if (!compiler_enter_scope(c, module, mod, 0))
1199 return NULL;
1200 switch (mod->kind) {
1201 case Module_kind:
1202 if (!compiler_body(c, mod->v.Module.body)) {
1203 compiler_exit_scope(c);
1204 return 0;
1205 }
1206 break;
1207 case Interactive_kind:
1208 c->c_interactive = 1;
1209 VISIT_SEQ_IN_SCOPE(c, stmt,
1210 mod->v.Interactive.body);
1211 break;
1212 case Expression_kind:
1213 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1214 addNone = 0;
1215 break;
1216 case Suite_kind:
1217 PyErr_SetString(PyExc_SystemError,
1218 "suite should not be possible");
1219 return 0;
1220 default:
1221 PyErr_Format(PyExc_SystemError,
1222 "module kind %d should not be possible",
1223 mod->kind);
1224 return 0;
1225 }
1226 co = assemble(c, addNone);
1227 compiler_exit_scope(c);
1228 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001229}
1230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231/* The test for LOCAL must come before the test for FREE in order to
1232 handle classes where name is both local and free. The local var is
1233 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001234*/
1235
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236static int
1237get_ref_type(struct compiler *c, PyObject *name)
1238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 int scope = PyST_GetScope(c->u->u_ste, name);
1240 if (scope == 0) {
1241 char buf[350];
1242 PyOS_snprintf(buf, sizeof(buf),
1243 "unknown scope for %.100s in %.100s(%s) in %s\n"
1244 "symbols: %s\nlocals: %s\nglobals: %s",
1245 PyBytes_AS_STRING(name),
1246 PyBytes_AS_STRING(c->u->u_name),
1247 PyObject_REPR(c->u->u_ste->ste_id),
1248 c->c_filename,
1249 PyObject_REPR(c->u->u_ste->ste_symbols),
1250 PyObject_REPR(c->u->u_varnames),
1251 PyObject_REPR(c->u->u_names)
1252 );
1253 Py_FatalError(buf);
1254 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259static int
1260compiler_lookup_arg(PyObject *dict, PyObject *name)
1261{
1262 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001265 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001267 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001269 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001270 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271}
1272
1273static int
1274compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 int i, free = PyCode_GetNumFree(co);
1277 if (free == 0) {
1278 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1279 ADDOP_I(c, MAKE_FUNCTION, args);
1280 return 1;
1281 }
1282 for (i = 0; i < free; ++i) {
1283 /* Bypass com_addop_varname because it will generate
1284 LOAD_DEREF but LOAD_CLOSURE is needed.
1285 */
1286 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1287 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 /* Special case: If a class contains a method with a
1290 free variable that has the same name as a method,
1291 the name will be considered free *and* local in the
1292 class. It should be handled by the closure, as
1293 well as by the normal name loookup logic.
1294 */
1295 reftype = get_ref_type(c, name);
1296 if (reftype == CELL)
1297 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1298 else /* (reftype == FREE) */
1299 arg = compiler_lookup_arg(c->u->u_freevars, name);
1300 if (arg == -1) {
1301 fprintf(stderr,
1302 "lookup %s in %s %d %d\n"
1303 "freevars of %s: %s\n",
1304 PyObject_REPR(name),
1305 PyBytes_AS_STRING(c->u->u_name),
1306 reftype, arg,
1307 _PyUnicode_AsString(co->co_name),
1308 PyObject_REPR(co->co_freevars));
1309 Py_FatalError("compiler_make_closure()");
1310 }
1311 ADDOP_I(c, LOAD_CLOSURE, arg);
1312 }
1313 ADDOP_I(c, BUILD_TUPLE, free);
1314 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1315 ADDOP_I(c, MAKE_CLOSURE, args);
1316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317}
1318
1319static int
1320compiler_decorators(struct compiler *c, asdl_seq* decos)
1321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (!decos)
1325 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1328 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1329 }
1330 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331}
1332
1333static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001334compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 int i, default_count = 0;
1338 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1339 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1340 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1341 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001342 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1343 if (!mangled)
1344 return -1;
1345 ADDOP_O(c, LOAD_CONST, mangled, consts);
1346 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (!compiler_visit_expr(c, default_)) {
1348 return -1;
1349 }
1350 default_count++;
1351 }
1352 }
1353 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001354}
1355
1356static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001357compiler_visit_argannotation(struct compiler *c, identifier id,
1358 expr_ty annotation, PyObject *names)
1359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (annotation) {
1361 VISIT(c, expr, annotation);
1362 if (PyList_Append(names, id))
1363 return -1;
1364 }
1365 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001366}
1367
1368static int
1369compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1370 PyObject *names)
1371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 int i, error;
1373 for (i = 0; i < asdl_seq_LEN(args); i++) {
1374 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1375 error = compiler_visit_argannotation(
1376 c,
1377 arg->arg,
1378 arg->annotation,
1379 names);
1380 if (error)
1381 return error;
1382 }
1383 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001384}
1385
1386static int
1387compiler_visit_annotations(struct compiler *c, arguments_ty args,
1388 expr_ty returns)
1389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 /* Push arg annotations and a list of the argument names. Return the #
1391 of items pushed. The expressions are evaluated out-of-order wrt the
1392 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1395 */
1396 static identifier return_str;
1397 PyObject *names;
1398 int len;
1399 names = PyList_New(0);
1400 if (!names)
1401 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (compiler_visit_argannotations(c, args->args, names))
1404 goto error;
1405 if (args->varargannotation &&
1406 compiler_visit_argannotation(c, args->vararg,
1407 args->varargannotation, names))
1408 goto error;
1409 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1410 goto error;
1411 if (args->kwargannotation &&
1412 compiler_visit_argannotation(c, args->kwarg,
1413 args->kwargannotation, names))
1414 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (!return_str) {
1417 return_str = PyUnicode_InternFromString("return");
1418 if (!return_str)
1419 goto error;
1420 }
1421 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1422 goto error;
1423 }
1424
1425 len = PyList_GET_SIZE(names);
1426 if (len > 65534) {
1427 /* len must fit in 16 bits, and len is incremented below */
1428 PyErr_SetString(PyExc_SyntaxError,
1429 "too many annotations");
1430 goto error;
1431 }
1432 if (len) {
1433 /* convert names to a tuple and place on stack */
1434 PyObject *elt;
1435 int i;
1436 PyObject *s = PyTuple_New(len);
1437 if (!s)
1438 goto error;
1439 for (i = 0; i < len; i++) {
1440 elt = PyList_GET_ITEM(names, i);
1441 Py_INCREF(elt);
1442 PyTuple_SET_ITEM(s, i, elt);
1443 }
1444 ADDOP_O(c, LOAD_CONST, s, consts);
1445 Py_DECREF(s);
1446 len++; /* include the just-pushed tuple */
1447 }
1448 Py_DECREF(names);
1449 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001450
1451error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_DECREF(names);
1453 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001454}
1455
1456static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457compiler_function(struct compiler *c, stmt_ty s)
1458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyCodeObject *co;
1460 PyObject *first_const = Py_None;
1461 arguments_ty args = s->v.FunctionDef.args;
1462 expr_ty returns = s->v.FunctionDef.returns;
1463 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1464 stmt_ty st;
1465 int i, n, docstring, kw_default_count = 0, arglength;
1466 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (!compiler_decorators(c, decos))
1471 return 0;
1472 if (args->kwonlyargs) {
1473 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1474 args->kw_defaults);
1475 if (res < 0)
1476 return 0;
1477 kw_default_count = res;
1478 }
1479 if (args->defaults)
1480 VISIT_SEQ(c, expr, args->defaults);
1481 num_annotations = compiler_visit_annotations(c, args, returns);
1482 if (num_annotations < 0)
1483 return 0;
1484 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1487 s->lineno))
1488 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1491 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001492 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 first_const = st->v.Expr.value->v.Str.s;
1494 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1495 compiler_exit_scope(c);
1496 return 0;
1497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 c->u->u_argcount = asdl_seq_LEN(args->args);
1500 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1501 n = asdl_seq_LEN(s->v.FunctionDef.body);
1502 /* if there was a docstring, we need to skip the first statement */
1503 for (i = docstring; i < n; i++) {
1504 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1505 VISIT_IN_SCOPE(c, stmt, st);
1506 }
1507 co = assemble(c, 1);
1508 compiler_exit_scope(c);
1509 if (co == NULL)
1510 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 arglength = asdl_seq_LEN(args->defaults);
1513 arglength |= kw_default_count << 8;
1514 arglength |= num_annotations << 16;
1515 compiler_make_closure(c, co, arglength);
1516 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 /* decorators */
1519 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1520 ADDOP_I(c, CALL_FUNCTION, 1);
1521 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
1526static int
1527compiler_class(struct compiler *c, stmt_ty s)
1528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 PyCodeObject *co;
1530 PyObject *str;
1531 int i;
1532 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (!compiler_decorators(c, decos))
1535 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 /* ultimately generate code for:
1538 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1539 where:
1540 <func> is a function/closure created from the class body;
1541 it has a single argument (__locals__) where the dict
1542 (or MutableSequence) representing the locals is passed
1543 <name> is the class name
1544 <bases> is the positional arguments and *varargs argument
1545 <keywords> is the keyword arguments and **kwds argument
1546 This borrows from compiler_call.
1547 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 /* 1. compile the class body into a code object */
1550 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno))
1551 return 0;
1552 /* this block represents what we do in the new scope */
1553 {
1554 /* use the class name for name mangling */
1555 Py_INCREF(s->v.ClassDef.name);
1556 Py_XDECREF(c->u->u_private);
1557 c->u->u_private = s->v.ClassDef.name;
1558 /* force it to have one mandatory argument */
1559 c->u->u_argcount = 1;
1560 /* load the first argument (__locals__) ... */
1561 ADDOP_I(c, LOAD_FAST, 0);
1562 /* ... and store it into f_locals */
1563 ADDOP_IN_SCOPE(c, STORE_LOCALS);
1564 /* load (global) __name__ ... */
1565 str = PyUnicode_InternFromString("__name__");
1566 if (!str || !compiler_nameop(c, str, Load)) {
1567 Py_XDECREF(str);
1568 compiler_exit_scope(c);
1569 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 Py_DECREF(str);
1572 /* ... and store it as __module__ */
1573 str = PyUnicode_InternFromString("__module__");
1574 if (!str || !compiler_nameop(c, str, Store)) {
1575 Py_XDECREF(str);
1576 compiler_exit_scope(c);
1577 return 0;
1578 }
1579 Py_DECREF(str);
1580 /* compile the body proper */
1581 if (!compiler_body(c, s->v.ClassDef.body)) {
1582 compiler_exit_scope(c);
1583 return 0;
1584 }
1585 /* return the (empty) __class__ cell */
1586 str = PyUnicode_InternFromString("__class__");
1587 if (str == NULL) {
1588 compiler_exit_scope(c);
1589 return 0;
1590 }
1591 i = compiler_lookup_arg(c->u->u_cellvars, str);
1592 Py_DECREF(str);
1593 if (i == -1) {
1594 /* This happens when nobody references the cell */
1595 PyErr_Clear();
1596 /* Return None */
1597 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1598 }
1599 else {
1600 /* Return the cell where to store __class__ */
1601 ADDOP_I(c, LOAD_CLOSURE, i);
1602 }
1603 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1604 /* create the code object */
1605 co = assemble(c, 1);
1606 }
1607 /* leave the new scope */
1608 compiler_exit_scope(c);
1609 if (co == NULL)
1610 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 /* 2. load the 'build_class' function */
1613 ADDOP(c, LOAD_BUILD_CLASS);
1614
1615 /* 3. load a function (or closure) made from the code object */
1616 compiler_make_closure(c, co, 0);
1617 Py_DECREF(co);
1618
1619 /* 4. load class name */
1620 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1621
1622 /* 5. generate the rest of the code for the call */
1623 if (!compiler_call_helper(c, 2,
1624 s->v.ClassDef.bases,
1625 s->v.ClassDef.keywords,
1626 s->v.ClassDef.starargs,
1627 s->v.ClassDef.kwargs))
1628 return 0;
1629
1630 /* 6. apply decorators */
1631 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1632 ADDOP_I(c, CALL_FUNCTION, 1);
1633 }
1634
1635 /* 7. store into <name> */
1636 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1637 return 0;
1638 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639}
1640
1641static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001642compiler_ifexp(struct compiler *c, expr_ty e)
1643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 basicblock *end, *next;
1645
1646 assert(e->kind == IfExp_kind);
1647 end = compiler_new_block(c);
1648 if (end == NULL)
1649 return 0;
1650 next = compiler_new_block(c);
1651 if (next == NULL)
1652 return 0;
1653 VISIT(c, expr, e->v.IfExp.test);
1654 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1655 VISIT(c, expr, e->v.IfExp.body);
1656 ADDOP_JREL(c, JUMP_FORWARD, end);
1657 compiler_use_next_block(c, next);
1658 VISIT(c, expr, e->v.IfExp.orelse);
1659 compiler_use_next_block(c, end);
1660 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001661}
1662
1663static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001664compiler_lambda(struct compiler *c, expr_ty e)
1665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 PyCodeObject *co;
1667 static identifier name;
1668 int kw_default_count = 0, arglength;
1669 arguments_ty args = e->v.Lambda.args;
1670 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 if (!name) {
1673 name = PyUnicode_InternFromString("<lambda>");
1674 if (!name)
1675 return 0;
1676 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 if (args->kwonlyargs) {
1679 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1680 args->kw_defaults);
1681 if (res < 0) return 0;
1682 kw_default_count = res;
1683 }
1684 if (args->defaults)
1685 VISIT_SEQ(c, expr, args->defaults);
1686 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1687 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 /* Make None the first constant, so the lambda can't have a
1690 docstring. */
1691 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1692 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 c->u->u_argcount = asdl_seq_LEN(args->args);
1695 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1696 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1697 if (c->u->u_ste->ste_generator) {
1698 ADDOP_IN_SCOPE(c, POP_TOP);
1699 }
1700 else {
1701 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1702 }
1703 co = assemble(c, 1);
1704 compiler_exit_scope(c);
1705 if (co == NULL)
1706 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 arglength = asdl_seq_LEN(args->defaults);
1709 arglength |= kw_default_count << 8;
1710 compiler_make_closure(c, co, arglength);
1711 Py_DECREF(co);
1712
1713 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714}
1715
1716static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717compiler_if(struct compiler *c, stmt_ty s)
1718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 basicblock *end, *next;
1720 int constant;
1721 assert(s->kind == If_kind);
1722 end = compiler_new_block(c);
1723 if (end == NULL)
1724 return 0;
1725
Georg Brandl8334fd92010-12-04 10:26:46 +00001726 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* constant = 0: "if 0"
1728 * constant = 1: "if 1", "if 2", ...
1729 * constant = -1: rest */
1730 if (constant == 0) {
1731 if (s->v.If.orelse)
1732 VISIT_SEQ(c, stmt, s->v.If.orelse);
1733 } else if (constant == 1) {
1734 VISIT_SEQ(c, stmt, s->v.If.body);
1735 } else {
1736 if (s->v.If.orelse) {
1737 next = compiler_new_block(c);
1738 if (next == NULL)
1739 return 0;
1740 }
1741 else
1742 next = end;
1743 VISIT(c, expr, s->v.If.test);
1744 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1745 VISIT_SEQ(c, stmt, s->v.If.body);
1746 ADDOP_JREL(c, JUMP_FORWARD, end);
1747 if (s->v.If.orelse) {
1748 compiler_use_next_block(c, next);
1749 VISIT_SEQ(c, stmt, s->v.If.orelse);
1750 }
1751 }
1752 compiler_use_next_block(c, end);
1753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001754}
1755
1756static int
1757compiler_for(struct compiler *c, stmt_ty s)
1758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 start = compiler_new_block(c);
1762 cleanup = compiler_new_block(c);
1763 end = compiler_new_block(c);
1764 if (start == NULL || end == NULL || cleanup == NULL)
1765 return 0;
1766 ADDOP_JREL(c, SETUP_LOOP, end);
1767 if (!compiler_push_fblock(c, LOOP, start))
1768 return 0;
1769 VISIT(c, expr, s->v.For.iter);
1770 ADDOP(c, GET_ITER);
1771 compiler_use_next_block(c, start);
1772 ADDOP_JREL(c, FOR_ITER, cleanup);
1773 VISIT(c, expr, s->v.For.target);
1774 VISIT_SEQ(c, stmt, s->v.For.body);
1775 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1776 compiler_use_next_block(c, cleanup);
1777 ADDOP(c, POP_BLOCK);
1778 compiler_pop_fblock(c, LOOP, start);
1779 VISIT_SEQ(c, stmt, s->v.For.orelse);
1780 compiler_use_next_block(c, end);
1781 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782}
1783
1784static int
1785compiler_while(struct compiler *c, stmt_ty s)
1786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001788 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (constant == 0) {
1791 if (s->v.While.orelse)
1792 VISIT_SEQ(c, stmt, s->v.While.orelse);
1793 return 1;
1794 }
1795 loop = compiler_new_block(c);
1796 end = compiler_new_block(c);
1797 if (constant == -1) {
1798 anchor = compiler_new_block(c);
1799 if (anchor == NULL)
1800 return 0;
1801 }
1802 if (loop == NULL || end == NULL)
1803 return 0;
1804 if (s->v.While.orelse) {
1805 orelse = compiler_new_block(c);
1806 if (orelse == NULL)
1807 return 0;
1808 }
1809 else
1810 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 ADDOP_JREL(c, SETUP_LOOP, end);
1813 compiler_use_next_block(c, loop);
1814 if (!compiler_push_fblock(c, LOOP, loop))
1815 return 0;
1816 if (constant == -1) {
1817 VISIT(c, expr, s->v.While.test);
1818 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1819 }
1820 VISIT_SEQ(c, stmt, s->v.While.body);
1821 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 /* XXX should the two POP instructions be in a separate block
1824 if there is no else clause ?
1825 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (constant == -1) {
1828 compiler_use_next_block(c, anchor);
1829 ADDOP(c, POP_BLOCK);
1830 }
1831 compiler_pop_fblock(c, LOOP, loop);
1832 if (orelse != NULL) /* what if orelse is just pass? */
1833 VISIT_SEQ(c, stmt, s->v.While.orelse);
1834 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837}
1838
1839static int
1840compiler_continue(struct compiler *c)
1841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1843 static const char IN_FINALLY_ERROR_MSG[] =
1844 "'continue' not supported inside 'finally' clause";
1845 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (!c->u->u_nfblocks)
1848 return compiler_error(c, LOOP_ERROR_MSG);
1849 i = c->u->u_nfblocks - 1;
1850 switch (c->u->u_fblock[i].fb_type) {
1851 case LOOP:
1852 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1853 break;
1854 case EXCEPT:
1855 case FINALLY_TRY:
1856 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1857 /* Prevent continue anywhere under a finally
1858 even if hidden in a sub-try or except. */
1859 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1860 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1861 }
1862 if (i == -1)
1863 return compiler_error(c, LOOP_ERROR_MSG);
1864 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1865 break;
1866 case FINALLY_END:
1867 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1868 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871}
1872
1873/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874
1875 SETUP_FINALLY L
1876 <code for body>
1877 POP_BLOCK
1878 LOAD_CONST <None>
1879 L: <code for finalbody>
1880 END_FINALLY
1881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 The special instructions use the block stack. Each block
1883 stack entry contains the instruction that created it (here
1884 SETUP_FINALLY), the level of the value stack at the time the
1885 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 Pushes the current value stack level and the label
1889 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 Pops en entry from the block stack, and pops the value
1892 stack until its level is the same as indicated on the
1893 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 Pops a variable number of entries from the *value* stack
1896 and re-raises the exception they specify. The number of
1897 entries popped depends on the (pseudo) exception type.
1898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899 The block stack is unwound when an exception is raised:
1900 when a SETUP_FINALLY entry is found, the exception is pushed
1901 onto the value stack (and the exception condition is cleared),
1902 and the interpreter jumps to the label gotten from the block
1903 stack.
1904*/
1905
1906static int
1907compiler_try_finally(struct compiler *c, stmt_ty s)
1908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 basicblock *body, *end;
1910 body = compiler_new_block(c);
1911 end = compiler_new_block(c);
1912 if (body == NULL || end == NULL)
1913 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 ADDOP_JREL(c, SETUP_FINALLY, end);
1916 compiler_use_next_block(c, body);
1917 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1918 return 0;
1919 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1920 ADDOP(c, POP_BLOCK);
1921 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1924 compiler_use_next_block(c, end);
1925 if (!compiler_push_fblock(c, FINALLY_END, end))
1926 return 0;
1927 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1928 ADDOP(c, END_FINALLY);
1929 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932}
1933
1934/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001935 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936 (The contents of the value stack is shown in [], with the top
1937 at the right; 'tb' is trace-back info, 'val' the exception's
1938 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939
1940 Value stack Label Instruction Argument
1941 [] SETUP_EXCEPT L1
1942 [] <code for S>
1943 [] POP_BLOCK
1944 [] JUMP_FORWARD L0
1945
1946 [tb, val, exc] L1: DUP )
1947 [tb, val, exc, exc] <evaluate E1> )
1948 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1949 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
1950 [tb, val, exc] POP
1951 [tb, val] <assign to V1> (or POP if no V1)
1952 [tb] POP
1953 [] <code for S1>
1954 JUMP_FORWARD L0
1955
1956 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957 .............................etc.......................
1958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
1960
1961 [] L0: <next statement>
1962
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963 Of course, parts are not generated if Vi or Ei is not present.
1964*/
1965static int
1966compiler_try_except(struct compiler *c, stmt_ty s)
1967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 basicblock *body, *orelse, *except, *end;
1969 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 body = compiler_new_block(c);
1972 except = compiler_new_block(c);
1973 orelse = compiler_new_block(c);
1974 end = compiler_new_block(c);
1975 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1976 return 0;
1977 ADDOP_JREL(c, SETUP_EXCEPT, except);
1978 compiler_use_next_block(c, body);
1979 if (!compiler_push_fblock(c, EXCEPT, body))
1980 return 0;
1981 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1982 ADDOP(c, POP_BLOCK);
1983 compiler_pop_fblock(c, EXCEPT, body);
1984 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1985 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1986 compiler_use_next_block(c, except);
1987 for (i = 0; i < n; i++) {
1988 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson74897ba2011-05-27 14:10:24 -05001989 s->v.TryExcept.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (!handler->v.ExceptHandler.type && i < n-1)
1991 return compiler_error(c, "default 'except:' must be last");
1992 c->u->u_lineno_set = 0;
1993 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00001994 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 except = compiler_new_block(c);
1996 if (except == NULL)
1997 return 0;
1998 if (handler->v.ExceptHandler.type) {
1999 ADDOP(c, DUP_TOP);
2000 VISIT(c, expr, handler->v.ExceptHandler.type);
2001 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2002 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2003 }
2004 ADDOP(c, POP_TOP);
2005 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002006 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002007
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002008 cleanup_end = compiler_new_block(c);
2009 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002010 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002011 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002012
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002013 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2014 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002016 /*
2017 try:
2018 # body
2019 except type as name:
2020 try:
2021 # body
2022 finally:
2023 name = None
2024 del name
2025 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002027 /* second try: */
2028 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2029 compiler_use_next_block(c, cleanup_body);
2030 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2031 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002033 /* second # body */
2034 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2035 ADDOP(c, POP_BLOCK);
2036 ADDOP(c, POP_EXCEPT);
2037 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002039 /* finally: */
2040 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2041 compiler_use_next_block(c, cleanup_end);
2042 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2043 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002045 /* name = None */
2046 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2047 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002049 /* del name */
2050 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002052 ADDOP(c, END_FINALLY);
2053 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 }
2055 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002056 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002058 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002059 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002060 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061
Guido van Rossumb940e112007-01-10 16:19:56 +00002062 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002063 ADDOP(c, POP_TOP);
2064 compiler_use_next_block(c, cleanup_body);
2065 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2066 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002068 ADDOP(c, POP_EXCEPT);
2069 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 }
2071 ADDOP_JREL(c, JUMP_FORWARD, end);
2072 compiler_use_next_block(c, except);
2073 }
2074 ADDOP(c, END_FINALLY);
2075 compiler_use_next_block(c, orelse);
2076 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2077 compiler_use_next_block(c, end);
2078 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079}
2080
2081static int
2082compiler_import_as(struct compiler *c, identifier name, identifier asname)
2083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* The IMPORT_NAME opcode was already generated. This function
2085 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 If there is a dot in name, we need to split it and emit a
2088 LOAD_ATTR for each name.
2089 */
2090 const Py_UNICODE *src = PyUnicode_AS_UNICODE(name);
2091 const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.');
2092 if (dot) {
2093 /* Consume the base module name to get the first attribute */
2094 src = dot + 1;
2095 while (dot) {
2096 /* NB src is only defined when dot != NULL */
2097 PyObject *attr;
2098 dot = Py_UNICODE_strchr(src, '.');
2099 attr = PyUnicode_FromUnicode(src,
2100 dot ? dot - src : Py_UNICODE_strlen(src));
2101 if (!attr)
2102 return -1;
2103 ADDOP_O(c, LOAD_ATTR, attr, names);
2104 Py_DECREF(attr);
2105 src = dot + 1;
2106 }
2107 }
2108 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002109}
2110
2111static int
2112compiler_import(struct compiler *c, stmt_ty s)
2113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* The Import node stores a module name like a.b.c as a single
2115 string. This is convenient for all cases except
2116 import a.b.c as d
2117 where we need to parse that string to extract the individual
2118 module names.
2119 XXX Perhaps change the representation to make this case simpler?
2120 */
2121 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 for (i = 0; i < n; i++) {
2124 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2125 int r;
2126 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 level = PyLong_FromLong(0);
2129 if (level == NULL)
2130 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 ADDOP_O(c, LOAD_CONST, level, consts);
2133 Py_DECREF(level);
2134 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2135 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (alias->asname) {
2138 r = compiler_import_as(c, alias->name, alias->asname);
2139 if (!r)
2140 return r;
2141 }
2142 else {
2143 identifier tmp = alias->name;
2144 const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name);
2145 Py_UNICODE *dot = Py_UNICODE_strchr(base, '.');
2146 if (dot)
2147 tmp = PyUnicode_FromUnicode(base,
2148 dot - base);
2149 r = compiler_nameop(c, tmp, Store);
2150 if (dot) {
2151 Py_DECREF(tmp);
2152 }
2153 if (!r)
2154 return r;
2155 }
2156 }
2157 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158}
2159
2160static int
2161compiler_from_import(struct compiler *c, stmt_ty s)
2162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 PyObject *names = PyTuple_New(n);
2166 PyObject *level;
2167 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (!empty_string) {
2170 empty_string = PyUnicode_FromString("");
2171 if (!empty_string)
2172 return 0;
2173 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 if (!names)
2176 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 level = PyLong_FromLong(s->v.ImportFrom.level);
2179 if (!level) {
2180 Py_DECREF(names);
2181 return 0;
2182 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 /* build up the names */
2185 for (i = 0; i < n; i++) {
2186 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2187 Py_INCREF(alias->name);
2188 PyTuple_SET_ITEM(names, i, alias->name);
2189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2192 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2193 Py_DECREF(level);
2194 Py_DECREF(names);
2195 return compiler_error(c, "from __future__ imports must occur "
2196 "at the beginning of the file");
2197 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 ADDOP_O(c, LOAD_CONST, level, consts);
2200 Py_DECREF(level);
2201 ADDOP_O(c, LOAD_CONST, names, consts);
2202 Py_DECREF(names);
2203 if (s->v.ImportFrom.module) {
2204 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2205 }
2206 else {
2207 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2208 }
2209 for (i = 0; i < n; i++) {
2210 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2211 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') {
2214 assert(n == 1);
2215 ADDOP(c, IMPORT_STAR);
2216 return 1;
2217 }
2218
2219 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2220 store_name = alias->name;
2221 if (alias->asname)
2222 store_name = alias->asname;
2223
2224 if (!compiler_nameop(c, store_name, Store)) {
2225 Py_DECREF(names);
2226 return 0;
2227 }
2228 }
2229 /* remove imported module */
2230 ADDOP(c, POP_TOP);
2231 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002232}
2233
2234static int
2235compiler_assert(struct compiler *c, stmt_ty s)
2236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 static PyObject *assertion_error = NULL;
2238 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Georg Brandl8334fd92010-12-04 10:26:46 +00002240 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 return 1;
2242 if (assertion_error == NULL) {
2243 assertion_error = PyUnicode_InternFromString("AssertionError");
2244 if (assertion_error == NULL)
2245 return 0;
2246 }
2247 if (s->v.Assert.test->kind == Tuple_kind &&
2248 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2249 const char* msg =
2250 "assertion is always true, perhaps remove parentheses?";
2251 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2252 c->u->u_lineno, NULL, NULL) == -1)
2253 return 0;
2254 }
2255 VISIT(c, expr, s->v.Assert.test);
2256 end = compiler_new_block(c);
2257 if (end == NULL)
2258 return 0;
2259 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2260 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2261 if (s->v.Assert.msg) {
2262 VISIT(c, expr, s->v.Assert.msg);
2263 ADDOP_I(c, CALL_FUNCTION, 1);
2264 }
2265 ADDOP_I(c, RAISE_VARARGS, 1);
2266 compiler_use_next_block(c, end);
2267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268}
2269
2270static int
2271compiler_visit_stmt(struct compiler *c, stmt_ty s)
2272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 /* Always assign a lineno to the next instruction for a stmt. */
2276 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002277 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 switch (s->kind) {
2281 case FunctionDef_kind:
2282 return compiler_function(c, s);
2283 case ClassDef_kind:
2284 return compiler_class(c, s);
2285 case Return_kind:
2286 if (c->u->u_ste->ste_type != FunctionBlock)
2287 return compiler_error(c, "'return' outside function");
2288 if (s->v.Return.value) {
2289 VISIT(c, expr, s->v.Return.value);
2290 }
2291 else
2292 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2293 ADDOP(c, RETURN_VALUE);
2294 break;
2295 case Delete_kind:
2296 VISIT_SEQ(c, expr, s->v.Delete.targets)
2297 break;
2298 case Assign_kind:
2299 n = asdl_seq_LEN(s->v.Assign.targets);
2300 VISIT(c, expr, s->v.Assign.value);
2301 for (i = 0; i < n; i++) {
2302 if (i < n - 1)
2303 ADDOP(c, DUP_TOP);
2304 VISIT(c, expr,
2305 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2306 }
2307 break;
2308 case AugAssign_kind:
2309 return compiler_augassign(c, s);
2310 case For_kind:
2311 return compiler_for(c, s);
2312 case While_kind:
2313 return compiler_while(c, s);
2314 case If_kind:
2315 return compiler_if(c, s);
2316 case Raise_kind:
2317 n = 0;
2318 if (s->v.Raise.exc) {
2319 VISIT(c, expr, s->v.Raise.exc);
2320 n++;
2321 if (s->v.Raise.cause) {
2322 VISIT(c, expr, s->v.Raise.cause);
2323 n++;
2324 }
2325 }
2326 ADDOP_I(c, RAISE_VARARGS, n);
2327 break;
2328 case TryExcept_kind:
2329 return compiler_try_except(c, s);
2330 case TryFinally_kind:
2331 return compiler_try_finally(c, s);
2332 case Assert_kind:
2333 return compiler_assert(c, s);
2334 case Import_kind:
2335 return compiler_import(c, s);
2336 case ImportFrom_kind:
2337 return compiler_from_import(c, s);
2338 case Global_kind:
2339 case Nonlocal_kind:
2340 break;
2341 case Expr_kind:
2342 if (c->c_interactive && c->c_nestlevel <= 1) {
2343 VISIT(c, expr, s->v.Expr.value);
2344 ADDOP(c, PRINT_EXPR);
2345 }
2346 else if (s->v.Expr.value->kind != Str_kind &&
2347 s->v.Expr.value->kind != Num_kind) {
2348 VISIT(c, expr, s->v.Expr.value);
2349 ADDOP(c, POP_TOP);
2350 }
2351 break;
2352 case Pass_kind:
2353 break;
2354 case Break_kind:
2355 if (!compiler_in_loop(c))
2356 return compiler_error(c, "'break' outside loop");
2357 ADDOP(c, BREAK_LOOP);
2358 break;
2359 case Continue_kind:
2360 return compiler_continue(c);
2361 case With_kind:
2362 return compiler_with(c, s);
2363 }
2364 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365}
2366
2367static int
2368unaryop(unaryop_ty op)
2369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 switch (op) {
2371 case Invert:
2372 return UNARY_INVERT;
2373 case Not:
2374 return UNARY_NOT;
2375 case UAdd:
2376 return UNARY_POSITIVE;
2377 case USub:
2378 return UNARY_NEGATIVE;
2379 default:
2380 PyErr_Format(PyExc_SystemError,
2381 "unary op %d should not be possible", op);
2382 return 0;
2383 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384}
2385
2386static int
2387binop(struct compiler *c, operator_ty op)
2388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 switch (op) {
2390 case Add:
2391 return BINARY_ADD;
2392 case Sub:
2393 return BINARY_SUBTRACT;
2394 case Mult:
2395 return BINARY_MULTIPLY;
2396 case Div:
2397 return BINARY_TRUE_DIVIDE;
2398 case Mod:
2399 return BINARY_MODULO;
2400 case Pow:
2401 return BINARY_POWER;
2402 case LShift:
2403 return BINARY_LSHIFT;
2404 case RShift:
2405 return BINARY_RSHIFT;
2406 case BitOr:
2407 return BINARY_OR;
2408 case BitXor:
2409 return BINARY_XOR;
2410 case BitAnd:
2411 return BINARY_AND;
2412 case FloorDiv:
2413 return BINARY_FLOOR_DIVIDE;
2414 default:
2415 PyErr_Format(PyExc_SystemError,
2416 "binary op %d should not be possible", op);
2417 return 0;
2418 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419}
2420
2421static int
2422cmpop(cmpop_ty op)
2423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 switch (op) {
2425 case Eq:
2426 return PyCmp_EQ;
2427 case NotEq:
2428 return PyCmp_NE;
2429 case Lt:
2430 return PyCmp_LT;
2431 case LtE:
2432 return PyCmp_LE;
2433 case Gt:
2434 return PyCmp_GT;
2435 case GtE:
2436 return PyCmp_GE;
2437 case Is:
2438 return PyCmp_IS;
2439 case IsNot:
2440 return PyCmp_IS_NOT;
2441 case In:
2442 return PyCmp_IN;
2443 case NotIn:
2444 return PyCmp_NOT_IN;
2445 default:
2446 return PyCmp_BAD;
2447 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448}
2449
2450static int
2451inplace_binop(struct compiler *c, operator_ty op)
2452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 switch (op) {
2454 case Add:
2455 return INPLACE_ADD;
2456 case Sub:
2457 return INPLACE_SUBTRACT;
2458 case Mult:
2459 return INPLACE_MULTIPLY;
2460 case Div:
2461 return INPLACE_TRUE_DIVIDE;
2462 case Mod:
2463 return INPLACE_MODULO;
2464 case Pow:
2465 return INPLACE_POWER;
2466 case LShift:
2467 return INPLACE_LSHIFT;
2468 case RShift:
2469 return INPLACE_RSHIFT;
2470 case BitOr:
2471 return INPLACE_OR;
2472 case BitXor:
2473 return INPLACE_XOR;
2474 case BitAnd:
2475 return INPLACE_AND;
2476 case FloorDiv:
2477 return INPLACE_FLOOR_DIVIDE;
2478 default:
2479 PyErr_Format(PyExc_SystemError,
2480 "inplace binary op %d should not be possible", op);
2481 return 0;
2482 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483}
2484
2485static int
2486compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 int op, scope, arg;
2489 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 PyObject *dict = c->u->u_names;
2492 PyObject *mangled;
2493 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 mangled = _Py_Mangle(c->u->u_private, name);
2496 if (!mangled)
2497 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 op = 0;
2500 optype = OP_NAME;
2501 scope = PyST_GetScope(c->u->u_ste, mangled);
2502 switch (scope) {
2503 case FREE:
2504 dict = c->u->u_freevars;
2505 optype = OP_DEREF;
2506 break;
2507 case CELL:
2508 dict = c->u->u_cellvars;
2509 optype = OP_DEREF;
2510 break;
2511 case LOCAL:
2512 if (c->u->u_ste->ste_type == FunctionBlock)
2513 optype = OP_FAST;
2514 break;
2515 case GLOBAL_IMPLICIT:
2516 if (c->u->u_ste->ste_type == FunctionBlock &&
2517 !c->u->u_ste->ste_unoptimized)
2518 optype = OP_GLOBAL;
2519 break;
2520 case GLOBAL_EXPLICIT:
2521 optype = OP_GLOBAL;
2522 break;
2523 default:
2524 /* scope can be 0 */
2525 break;
2526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 /* XXX Leave assert here, but handle __doc__ and the like better */
2529 assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 switch (optype) {
2532 case OP_DEREF:
2533 switch (ctx) {
2534 case Load: op = LOAD_DEREF; break;
2535 case Store: op = STORE_DEREF; break;
2536 case AugLoad:
2537 case AugStore:
2538 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002539 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 case Param:
2541 default:
2542 PyErr_SetString(PyExc_SystemError,
2543 "param invalid for deref variable");
2544 return 0;
2545 }
2546 break;
2547 case OP_FAST:
2548 switch (ctx) {
2549 case Load: op = LOAD_FAST; break;
2550 case Store: op = STORE_FAST; break;
2551 case Del: op = DELETE_FAST; break;
2552 case AugLoad:
2553 case AugStore:
2554 break;
2555 case Param:
2556 default:
2557 PyErr_SetString(PyExc_SystemError,
2558 "param invalid for local variable");
2559 return 0;
2560 }
2561 ADDOP_O(c, op, mangled, varnames);
2562 Py_DECREF(mangled);
2563 return 1;
2564 case OP_GLOBAL:
2565 switch (ctx) {
2566 case Load: op = LOAD_GLOBAL; break;
2567 case Store: op = STORE_GLOBAL; break;
2568 case Del: op = DELETE_GLOBAL; break;
2569 case AugLoad:
2570 case AugStore:
2571 break;
2572 case Param:
2573 default:
2574 PyErr_SetString(PyExc_SystemError,
2575 "param invalid for global variable");
2576 return 0;
2577 }
2578 break;
2579 case OP_NAME:
2580 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002581 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 case Store: op = STORE_NAME; break;
2583 case Del: op = DELETE_NAME; break;
2584 case AugLoad:
2585 case AugStore:
2586 break;
2587 case Param:
2588 default:
2589 PyErr_SetString(PyExc_SystemError,
2590 "param invalid for name variable");
2591 return 0;
2592 }
2593 break;
2594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 assert(op);
2597 arg = compiler_add_o(c, dict, mangled);
2598 Py_DECREF(mangled);
2599 if (arg < 0)
2600 return 0;
2601 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602}
2603
2604static int
2605compiler_boolop(struct compiler *c, expr_ty e)
2606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 basicblock *end;
2608 int jumpi, i, n;
2609 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 assert(e->kind == BoolOp_kind);
2612 if (e->v.BoolOp.op == And)
2613 jumpi = JUMP_IF_FALSE_OR_POP;
2614 else
2615 jumpi = JUMP_IF_TRUE_OR_POP;
2616 end = compiler_new_block(c);
2617 if (end == NULL)
2618 return 0;
2619 s = e->v.BoolOp.values;
2620 n = asdl_seq_LEN(s) - 1;
2621 assert(n >= 0);
2622 for (i = 0; i < n; ++i) {
2623 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2624 ADDOP_JABS(c, jumpi, end);
2625 }
2626 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2627 compiler_use_next_block(c, end);
2628 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629}
2630
2631static int
2632compiler_list(struct compiler *c, expr_ty e)
2633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 int n = asdl_seq_LEN(e->v.List.elts);
2635 if (e->v.List.ctx == Store) {
2636 int i, seen_star = 0;
2637 for (i = 0; i < n; i++) {
2638 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2639 if (elt->kind == Starred_kind && !seen_star) {
2640 if ((i >= (1 << 8)) ||
2641 (n-i-1 >= (INT_MAX >> 8)))
2642 return compiler_error(c,
2643 "too many expressions in "
2644 "star-unpacking assignment");
2645 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2646 seen_star = 1;
2647 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2648 } else if (elt->kind == Starred_kind) {
2649 return compiler_error(c,
2650 "two starred expressions in assignment");
2651 }
2652 }
2653 if (!seen_star) {
2654 ADDOP_I(c, UNPACK_SEQUENCE, n);
2655 }
2656 }
2657 VISIT_SEQ(c, expr, e->v.List.elts);
2658 if (e->v.List.ctx == Load) {
2659 ADDOP_I(c, BUILD_LIST, n);
2660 }
2661 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662}
2663
2664static int
2665compiler_tuple(struct compiler *c, expr_ty e)
2666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 int n = asdl_seq_LEN(e->v.Tuple.elts);
2668 if (e->v.Tuple.ctx == Store) {
2669 int i, seen_star = 0;
2670 for (i = 0; i < n; i++) {
2671 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2672 if (elt->kind == Starred_kind && !seen_star) {
2673 if ((i >= (1 << 8)) ||
2674 (n-i-1 >= (INT_MAX >> 8)))
2675 return compiler_error(c,
2676 "too many expressions in "
2677 "star-unpacking assignment");
2678 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2679 seen_star = 1;
2680 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2681 } else if (elt->kind == Starred_kind) {
2682 return compiler_error(c,
2683 "two starred expressions in assignment");
2684 }
2685 }
2686 if (!seen_star) {
2687 ADDOP_I(c, UNPACK_SEQUENCE, n);
2688 }
2689 }
2690 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2691 if (e->v.Tuple.ctx == Load) {
2692 ADDOP_I(c, BUILD_TUPLE, n);
2693 }
2694 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695}
2696
2697static int
2698compiler_compare(struct compiler *c, expr_ty e)
2699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 int i, n;
2701 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2704 VISIT(c, expr, e->v.Compare.left);
2705 n = asdl_seq_LEN(e->v.Compare.ops);
2706 assert(n > 0);
2707 if (n > 1) {
2708 cleanup = compiler_new_block(c);
2709 if (cleanup == NULL)
2710 return 0;
2711 VISIT(c, expr,
2712 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2713 }
2714 for (i = 1; i < n; i++) {
2715 ADDOP(c, DUP_TOP);
2716 ADDOP(c, ROT_THREE);
2717 ADDOP_I(c, COMPARE_OP,
2718 cmpop((cmpop_ty)(asdl_seq_GET(
2719 e->v.Compare.ops, i - 1))));
2720 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2721 NEXT_BLOCK(c);
2722 if (i < (n - 1))
2723 VISIT(c, expr,
2724 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2725 }
2726 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2727 ADDOP_I(c, COMPARE_OP,
2728 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2729 if (n > 1) {
2730 basicblock *end = compiler_new_block(c);
2731 if (end == NULL)
2732 return 0;
2733 ADDOP_JREL(c, JUMP_FORWARD, end);
2734 compiler_use_next_block(c, cleanup);
2735 ADDOP(c, ROT_TWO);
2736 ADDOP(c, POP_TOP);
2737 compiler_use_next_block(c, end);
2738 }
2739 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740}
2741
2742static int
2743compiler_call(struct compiler *c, expr_ty e)
2744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 VISIT(c, expr, e->v.Call.func);
2746 return compiler_call_helper(c, 0,
2747 e->v.Call.args,
2748 e->v.Call.keywords,
2749 e->v.Call.starargs,
2750 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002751}
2752
2753/* shared code between compiler_call and compiler_class */
2754static int
2755compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 int n, /* Args already pushed */
2757 asdl_seq *args,
2758 asdl_seq *keywords,
2759 expr_ty starargs,
2760 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 n += asdl_seq_LEN(args);
2765 VISIT_SEQ(c, expr, args);
2766 if (keywords) {
2767 VISIT_SEQ(c, keyword, keywords);
2768 n |= asdl_seq_LEN(keywords) << 8;
2769 }
2770 if (starargs) {
2771 VISIT(c, expr, starargs);
2772 code |= 1;
2773 }
2774 if (kwargs) {
2775 VISIT(c, expr, kwargs);
2776 code |= 2;
2777 }
2778 switch (code) {
2779 case 0:
2780 ADDOP_I(c, CALL_FUNCTION, n);
2781 break;
2782 case 1:
2783 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2784 break;
2785 case 2:
2786 ADDOP_I(c, CALL_FUNCTION_KW, n);
2787 break;
2788 case 3:
2789 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2790 break;
2791 }
2792 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002793}
2794
Nick Coghlan650f0d02007-04-15 12:05:43 +00002795
2796/* List and set comprehensions and generator expressions work by creating a
2797 nested function to perform the actual iteration. This means that the
2798 iteration variables don't leak into the current scope.
2799 The defined function is called immediately following its definition, with the
2800 result of that call being the result of the expression.
2801 The LC/SC version returns the populated container, while the GE version is
2802 flagged in symtable.c as a generator, so it returns the generator object
2803 when the function is called.
2804 This code *knows* that the loop cannot contain break, continue, or return,
2805 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
2806
2807 Possible cleanups:
2808 - iterate over the generator sequence instead of using recursion
2809*/
2810
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812compiler_comprehension_generator(struct compiler *c,
2813 asdl_seq *generators, int gen_index,
2814 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 /* generate code for the iterator, then each of the ifs,
2817 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 comprehension_ty gen;
2820 basicblock *start, *anchor, *skip, *if_cleanup;
2821 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 start = compiler_new_block(c);
2824 skip = compiler_new_block(c);
2825 if_cleanup = compiler_new_block(c);
2826 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2829 anchor == NULL)
2830 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 if (gen_index == 0) {
2835 /* Receive outermost iter as an implicit argument */
2836 c->u->u_argcount = 1;
2837 ADDOP_I(c, LOAD_FAST, 0);
2838 }
2839 else {
2840 /* Sub-iter - calculate on the fly */
2841 VISIT(c, expr, gen->iter);
2842 ADDOP(c, GET_ITER);
2843 }
2844 compiler_use_next_block(c, start);
2845 ADDOP_JREL(c, FOR_ITER, anchor);
2846 NEXT_BLOCK(c);
2847 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 /* XXX this needs to be cleaned up...a lot! */
2850 n = asdl_seq_LEN(gen->ifs);
2851 for (i = 0; i < n; i++) {
2852 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
2853 VISIT(c, expr, e);
2854 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
2855 NEXT_BLOCK(c);
2856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 if (++gen_index < asdl_seq_LEN(generators))
2859 if (!compiler_comprehension_generator(c,
2860 generators, gen_index,
2861 elt, val, type))
2862 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 /* only append after the last for generator */
2865 if (gen_index >= asdl_seq_LEN(generators)) {
2866 /* comprehension specific code */
2867 switch (type) {
2868 case COMP_GENEXP:
2869 VISIT(c, expr, elt);
2870 ADDOP(c, YIELD_VALUE);
2871 ADDOP(c, POP_TOP);
2872 break;
2873 case COMP_LISTCOMP:
2874 VISIT(c, expr, elt);
2875 ADDOP_I(c, LIST_APPEND, gen_index + 1);
2876 break;
2877 case COMP_SETCOMP:
2878 VISIT(c, expr, elt);
2879 ADDOP_I(c, SET_ADD, gen_index + 1);
2880 break;
2881 case COMP_DICTCOMP:
2882 /* With 'd[k] = v', v is evaluated before k, so we do
2883 the same. */
2884 VISIT(c, expr, val);
2885 VISIT(c, expr, elt);
2886 ADDOP_I(c, MAP_ADD, gen_index + 1);
2887 break;
2888 default:
2889 return 0;
2890 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 compiler_use_next_block(c, skip);
2893 }
2894 compiler_use_next_block(c, if_cleanup);
2895 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2896 compiler_use_next_block(c, anchor);
2897
2898 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899}
2900
2901static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002902compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00002904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 PyCodeObject *co = NULL;
2906 expr_ty outermost_iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 outermost_iter = ((comprehension_ty)
2909 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2912 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 if (type != COMP_GENEXP) {
2915 int op;
2916 switch (type) {
2917 case COMP_LISTCOMP:
2918 op = BUILD_LIST;
2919 break;
2920 case COMP_SETCOMP:
2921 op = BUILD_SET;
2922 break;
2923 case COMP_DICTCOMP:
2924 op = BUILD_MAP;
2925 break;
2926 default:
2927 PyErr_Format(PyExc_SystemError,
2928 "unknown comprehension type %d", type);
2929 goto error_in_scope;
2930 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 ADDOP_I(c, op, 0);
2933 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 if (!compiler_comprehension_generator(c, generators, 0, elt,
2936 val, type))
2937 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 if (type != COMP_GENEXP) {
2940 ADDOP(c, RETURN_VALUE);
2941 }
2942
2943 co = assemble(c, 1);
2944 compiler_exit_scope(c);
2945 if (co == NULL)
2946 goto error;
2947
2948 if (!compiler_make_closure(c, co, 0))
2949 goto error;
2950 Py_DECREF(co);
2951
2952 VISIT(c, expr, outermost_iter);
2953 ADDOP(c, GET_ITER);
2954 ADDOP_I(c, CALL_FUNCTION, 1);
2955 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002956error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002958error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 Py_XDECREF(co);
2960 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00002961}
2962
2963static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964compiler_genexp(struct compiler *c, expr_ty e)
2965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 static identifier name;
2967 if (!name) {
2968 name = PyUnicode_FromString("<genexpr>");
2969 if (!name)
2970 return 0;
2971 }
2972 assert(e->kind == GeneratorExp_kind);
2973 return compiler_comprehension(c, e, COMP_GENEXP, name,
2974 e->v.GeneratorExp.generators,
2975 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976}
2977
2978static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00002979compiler_listcomp(struct compiler *c, expr_ty e)
2980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 static identifier name;
2982 if (!name) {
2983 name = PyUnicode_FromString("<listcomp>");
2984 if (!name)
2985 return 0;
2986 }
2987 assert(e->kind == ListComp_kind);
2988 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
2989 e->v.ListComp.generators,
2990 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00002991}
2992
2993static int
2994compiler_setcomp(struct compiler *c, expr_ty e)
2995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 static identifier name;
2997 if (!name) {
2998 name = PyUnicode_FromString("<setcomp>");
2999 if (!name)
3000 return 0;
3001 }
3002 assert(e->kind == SetComp_kind);
3003 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3004 e->v.SetComp.generators,
3005 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003006}
3007
3008
3009static int
3010compiler_dictcomp(struct compiler *c, expr_ty e)
3011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 static identifier name;
3013 if (!name) {
3014 name = PyUnicode_FromString("<dictcomp>");
3015 if (!name)
3016 return 0;
3017 }
3018 assert(e->kind == DictComp_kind);
3019 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3020 e->v.DictComp.generators,
3021 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003022}
3023
3024
3025static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003026compiler_visit_keyword(struct compiler *c, keyword_ty k)
3027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3029 VISIT(c, expr, k->value);
3030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031}
3032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034 whether they are true or false.
3035
3036 Return values: 1 for true, 0 for false, -1 for non-constant.
3037 */
3038
3039static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003040expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 char *id;
3043 switch (e->kind) {
3044 case Ellipsis_kind:
3045 return 1;
3046 case Num_kind:
3047 return PyObject_IsTrue(e->v.Num.n);
3048 case Str_kind:
3049 return PyObject_IsTrue(e->v.Str.s);
3050 case Name_kind:
3051 /* optimize away names that can't be reassigned */
3052 id = PyBytes_AS_STRING(
3053 _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL));
3054 if (strcmp(id, "True") == 0) return 1;
3055 if (strcmp(id, "False") == 0) return 0;
3056 if (strcmp(id, "None") == 0) return 0;
3057 if (strcmp(id, "__debug__") == 0)
Georg Brandl8334fd92010-12-04 10:26:46 +00003058 return ! c->c_optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 /* fall through */
3060 default:
3061 return -1;
3062 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063}
3064
Guido van Rossumc2e20742006-02-27 22:32:47 +00003065/*
3066 Implements the with statement from PEP 343.
3067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003069
3070 with EXPR as VAR:
3071 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072
Guido van Rossumc2e20742006-02-27 22:32:47 +00003073 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074
Thomas Wouters477c8d52006-05-27 19:21:47 +00003075 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003076 exit = context.__exit__ # not calling it
3077 value = context.__enter__()
3078 try:
3079 VAR = value # if VAR present in the syntax
3080 BLOCK
3081 finally:
3082 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003084 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003086 exit(*exc)
3087 */
3088static int
3089compiler_with(struct compiler *c, stmt_ty s)
3090{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003091 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003092
3093 assert(s->kind == With_kind);
3094
Guido van Rossumc2e20742006-02-27 22:32:47 +00003095 block = compiler_new_block(c);
3096 finally = compiler_new_block(c);
3097 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003098 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003099
Thomas Wouters477c8d52006-05-27 19:21:47 +00003100 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003101 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003102 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003103
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003104 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003105 compiler_use_next_block(c, block);
3106 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003107 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003108 }
3109
3110 if (s->v.With.optional_vars) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003111 VISIT(c, expr, s->v.With.optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003112 }
3113 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003115 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003116 }
3117
3118 /* BLOCK code */
3119 VISIT_SEQ(c, stmt, s->v.With.body);
3120
3121 /* End of try block; start the finally block */
3122 ADDOP(c, POP_BLOCK);
3123 compiler_pop_fblock(c, FINALLY_TRY, block);
3124
3125 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3126 compiler_use_next_block(c, finally);
3127 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003128 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003129
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003130 /* Finally block starts; context.__exit__ is on the stack under
3131 the exception or return information. Just issue our magic
3132 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003133 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003134
3135 /* Finally block ends. */
3136 ADDOP(c, END_FINALLY);
3137 compiler_pop_fblock(c, FINALLY_END, finally);
3138 return 1;
3139}
3140
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141static int
3142compiler_visit_expr(struct compiler *c, expr_ty e)
3143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 /* If expr e has a different line number than the last expr/stmt,
3147 set a new line number for the next instruction.
3148 */
3149 if (e->lineno > c->u->u_lineno) {
3150 c->u->u_lineno = e->lineno;
3151 c->u->u_lineno_set = 0;
3152 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003153 /* Updating the column offset is always harmless. */
3154 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 switch (e->kind) {
3156 case BoolOp_kind:
3157 return compiler_boolop(c, e);
3158 case BinOp_kind:
3159 VISIT(c, expr, e->v.BinOp.left);
3160 VISIT(c, expr, e->v.BinOp.right);
3161 ADDOP(c, binop(c, e->v.BinOp.op));
3162 break;
3163 case UnaryOp_kind:
3164 VISIT(c, expr, e->v.UnaryOp.operand);
3165 ADDOP(c, unaryop(e->v.UnaryOp.op));
3166 break;
3167 case Lambda_kind:
3168 return compiler_lambda(c, e);
3169 case IfExp_kind:
3170 return compiler_ifexp(c, e);
3171 case Dict_kind:
3172 n = asdl_seq_LEN(e->v.Dict.values);
3173 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3174 for (i = 0; i < n; i++) {
3175 VISIT(c, expr,
3176 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3177 VISIT(c, expr,
3178 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3179 ADDOP(c, STORE_MAP);
3180 }
3181 break;
3182 case Set_kind:
3183 n = asdl_seq_LEN(e->v.Set.elts);
3184 VISIT_SEQ(c, expr, e->v.Set.elts);
3185 ADDOP_I(c, BUILD_SET, n);
3186 break;
3187 case GeneratorExp_kind:
3188 return compiler_genexp(c, e);
3189 case ListComp_kind:
3190 return compiler_listcomp(c, e);
3191 case SetComp_kind:
3192 return compiler_setcomp(c, e);
3193 case DictComp_kind:
3194 return compiler_dictcomp(c, e);
3195 case Yield_kind:
3196 if (c->u->u_ste->ste_type != FunctionBlock)
3197 return compiler_error(c, "'yield' outside function");
3198 if (e->v.Yield.value) {
3199 VISIT(c, expr, e->v.Yield.value);
3200 }
3201 else {
3202 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3203 }
3204 ADDOP(c, YIELD_VALUE);
3205 break;
3206 case Compare_kind:
3207 return compiler_compare(c, e);
3208 case Call_kind:
3209 return compiler_call(c, e);
3210 case Num_kind:
3211 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3212 break;
3213 case Str_kind:
3214 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3215 break;
3216 case Bytes_kind:
3217 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3218 break;
3219 case Ellipsis_kind:
3220 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3221 break;
3222 /* The following exprs can be assignment targets. */
3223 case Attribute_kind:
3224 if (e->v.Attribute.ctx != AugStore)
3225 VISIT(c, expr, e->v.Attribute.value);
3226 switch (e->v.Attribute.ctx) {
3227 case AugLoad:
3228 ADDOP(c, DUP_TOP);
3229 /* Fall through to load */
3230 case Load:
3231 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3232 break;
3233 case AugStore:
3234 ADDOP(c, ROT_TWO);
3235 /* Fall through to save */
3236 case Store:
3237 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3238 break;
3239 case Del:
3240 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3241 break;
3242 case Param:
3243 default:
3244 PyErr_SetString(PyExc_SystemError,
3245 "param invalid in attribute expression");
3246 return 0;
3247 }
3248 break;
3249 case Subscript_kind:
3250 switch (e->v.Subscript.ctx) {
3251 case AugLoad:
3252 VISIT(c, expr, e->v.Subscript.value);
3253 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3254 break;
3255 case Load:
3256 VISIT(c, expr, e->v.Subscript.value);
3257 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3258 break;
3259 case AugStore:
3260 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3261 break;
3262 case Store:
3263 VISIT(c, expr, e->v.Subscript.value);
3264 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3265 break;
3266 case Del:
3267 VISIT(c, expr, e->v.Subscript.value);
3268 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3269 break;
3270 case Param:
3271 default:
3272 PyErr_SetString(PyExc_SystemError,
3273 "param invalid in subscript expression");
3274 return 0;
3275 }
3276 break;
3277 case Starred_kind:
3278 switch (e->v.Starred.ctx) {
3279 case Store:
3280 /* In all legitimate cases, the Starred node was already replaced
3281 * by compiler_list/compiler_tuple. XXX: is that okay? */
3282 return compiler_error(c,
3283 "starred assignment target must be in a list or tuple");
3284 default:
3285 return compiler_error(c,
3286 "can use starred expression only as assignment target");
3287 }
3288 break;
3289 case Name_kind:
3290 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3291 /* child nodes of List and Tuple will have expr_context set */
3292 case List_kind:
3293 return compiler_list(c, e);
3294 case Tuple_kind:
3295 return compiler_tuple(c, e);
3296 }
3297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298}
3299
3300static int
3301compiler_augassign(struct compiler *c, stmt_ty s)
3302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 expr_ty e = s->v.AugAssign.target;
3304 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 switch (e->kind) {
3309 case Attribute_kind:
3310 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3311 AugLoad, e->lineno, e->col_offset, c->c_arena);
3312 if (auge == NULL)
3313 return 0;
3314 VISIT(c, expr, auge);
3315 VISIT(c, expr, s->v.AugAssign.value);
3316 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3317 auge->v.Attribute.ctx = AugStore;
3318 VISIT(c, expr, auge);
3319 break;
3320 case Subscript_kind:
3321 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3322 AugLoad, e->lineno, e->col_offset, c->c_arena);
3323 if (auge == NULL)
3324 return 0;
3325 VISIT(c, expr, auge);
3326 VISIT(c, expr, s->v.AugAssign.value);
3327 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3328 auge->v.Subscript.ctx = AugStore;
3329 VISIT(c, expr, auge);
3330 break;
3331 case Name_kind:
3332 if (!compiler_nameop(c, e->v.Name.id, Load))
3333 return 0;
3334 VISIT(c, expr, s->v.AugAssign.value);
3335 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3336 return compiler_nameop(c, e->v.Name.id, Store);
3337 default:
3338 PyErr_Format(PyExc_SystemError,
3339 "invalid node type (%d) for augmented assignment",
3340 e->kind);
3341 return 0;
3342 }
3343 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344}
3345
3346static int
3347compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 struct fblockinfo *f;
3350 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3351 PyErr_SetString(PyExc_SystemError,
3352 "too many statically nested blocks");
3353 return 0;
3354 }
3355 f = &c->u->u_fblock[c->u->u_nfblocks++];
3356 f->fb_type = t;
3357 f->fb_block = b;
3358 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359}
3360
3361static void
3362compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 struct compiler_unit *u = c->u;
3365 assert(u->u_nfblocks > 0);
3366 u->u_nfblocks--;
3367 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3368 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369}
3370
Thomas Wouters89f507f2006-12-13 04:49:30 +00003371static int
3372compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 int i;
3374 struct compiler_unit *u = c->u;
3375 for (i = 0; i < u->u_nfblocks; ++i) {
3376 if (u->u_fblock[i].fb_type == LOOP)
3377 return 1;
3378 }
3379 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003380}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381/* Raises a SyntaxError and returns 0.
3382 If something goes wrong, a different exception may be raised.
3383*/
3384
3385static int
3386compiler_error(struct compiler *c, const char *errstr)
3387{
Victor Stinnerc0499822010-10-17 19:16:33 +00003388 PyObject *loc, *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3392 if (!loc) {
3393 Py_INCREF(Py_None);
3394 loc = Py_None;
3395 }
Victor Stinnerc0499822010-10-17 19:16:33 +00003396 if (c->c_filename != NULL) {
3397 filename = PyUnicode_DecodeFSDefault(c->c_filename);
3398 if (!filename)
3399 goto exit;
3400 }
3401 else {
3402 Py_INCREF(Py_None);
3403 filename = Py_None;
3404 }
3405 u = Py_BuildValue("(NiiO)", filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003406 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 if (!u)
3408 goto exit;
3409 v = Py_BuildValue("(zO)", errstr, u);
3410 if (!v)
3411 goto exit;
3412 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 Py_DECREF(loc);
3415 Py_XDECREF(u);
3416 Py_XDECREF(v);
3417 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003418}
3419
3420static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421compiler_handle_subscr(struct compiler *c, const char *kind,
3422 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 /* XXX this code is duplicated */
3427 switch (ctx) {
3428 case AugLoad: /* fall through to Load */
3429 case Load: op = BINARY_SUBSCR; break;
3430 case AugStore:/* fall through to Store */
3431 case Store: op = STORE_SUBSCR; break;
3432 case Del: op = DELETE_SUBSCR; break;
3433 case Param:
3434 PyErr_Format(PyExc_SystemError,
3435 "invalid %s kind %d in subscript\n",
3436 kind, ctx);
3437 return 0;
3438 }
3439 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003440 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 }
3442 else if (ctx == AugStore) {
3443 ADDOP(c, ROT_THREE);
3444 }
3445 ADDOP(c, op);
3446 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447}
3448
3449static int
3450compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 int n = 2;
3453 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 /* only handles the cases where BUILD_SLICE is emitted */
3456 if (s->v.Slice.lower) {
3457 VISIT(c, expr, s->v.Slice.lower);
3458 }
3459 else {
3460 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3461 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 if (s->v.Slice.upper) {
3464 VISIT(c, expr, s->v.Slice.upper);
3465 }
3466 else {
3467 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3468 }
3469
3470 if (s->v.Slice.step) {
3471 n++;
3472 VISIT(c, expr, s->v.Slice.step);
3473 }
3474 ADDOP_I(c, BUILD_SLICE, n);
3475 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003476}
3477
3478static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3480 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 switch (s->kind) {
3483 case Slice_kind:
3484 return compiler_slice(c, s, ctx);
3485 case Index_kind:
3486 VISIT(c, expr, s->v.Index.value);
3487 break;
3488 case ExtSlice_kind:
3489 default:
3490 PyErr_SetString(PyExc_SystemError,
3491 "extended slice invalid in nested slice");
3492 return 0;
3493 }
3494 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495}
3496
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497static int
3498compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 char * kindname = NULL;
3501 switch (s->kind) {
3502 case Index_kind:
3503 kindname = "index";
3504 if (ctx != AugStore) {
3505 VISIT(c, expr, s->v.Index.value);
3506 }
3507 break;
3508 case Slice_kind:
3509 kindname = "slice";
3510 if (ctx != AugStore) {
3511 if (!compiler_slice(c, s, ctx))
3512 return 0;
3513 }
3514 break;
3515 case ExtSlice_kind:
3516 kindname = "extended slice";
3517 if (ctx != AugStore) {
3518 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3519 for (i = 0; i < n; i++) {
3520 slice_ty sub = (slice_ty)asdl_seq_GET(
3521 s->v.ExtSlice.dims, i);
3522 if (!compiler_visit_nested_slice(c, sub, ctx))
3523 return 0;
3524 }
3525 ADDOP_I(c, BUILD_TUPLE, n);
3526 }
3527 break;
3528 default:
3529 PyErr_Format(PyExc_SystemError,
3530 "invalid subscript kind %d", s->kind);
3531 return 0;
3532 }
3533 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534}
3535
Thomas Wouters89f507f2006-12-13 04:49:30 +00003536/* End of the compiler section, beginning of the assembler section */
3537
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538/* do depth-first search of basic block graph, starting with block.
3539 post records the block indices in post-order.
3540
3541 XXX must handle implicit jumps from one block to next
3542*/
3543
Thomas Wouters89f507f2006-12-13 04:49:30 +00003544struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 PyObject *a_bytecode; /* string containing bytecode */
3546 int a_offset; /* offset into bytecode */
3547 int a_nblocks; /* number of reachable blocks */
3548 basicblock **a_postorder; /* list of blocks in dfs postorder */
3549 PyObject *a_lnotab; /* string containing lnotab */
3550 int a_lnotab_off; /* offset into lnotab */
3551 int a_lineno; /* last lineno of emitted instruction */
3552 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003553};
3554
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555static void
3556dfs(struct compiler *c, basicblock *b, struct assembler *a)
3557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 int i;
3559 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 if (b->b_seen)
3562 return;
3563 b->b_seen = 1;
3564 if (b->b_next != NULL)
3565 dfs(c, b->b_next, a);
3566 for (i = 0; i < b->b_iused; i++) {
3567 instr = &b->b_instr[i];
3568 if (instr->i_jrel || instr->i_jabs)
3569 dfs(c, instr->i_target, a);
3570 }
3571 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572}
3573
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003574static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 int i, target_depth;
3578 struct instr *instr;
3579 if (b->b_seen || b->b_startdepth >= depth)
3580 return maxdepth;
3581 b->b_seen = 1;
3582 b->b_startdepth = depth;
3583 for (i = 0; i < b->b_iused; i++) {
3584 instr = &b->b_instr[i];
3585 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3586 if (depth > maxdepth)
3587 maxdepth = depth;
3588 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3589 if (instr->i_jrel || instr->i_jabs) {
3590 target_depth = depth;
3591 if (instr->i_opcode == FOR_ITER) {
3592 target_depth = depth-2;
3593 } else if (instr->i_opcode == SETUP_FINALLY ||
3594 instr->i_opcode == SETUP_EXCEPT) {
3595 target_depth = depth+3;
3596 if (target_depth > maxdepth)
3597 maxdepth = target_depth;
3598 }
3599 maxdepth = stackdepth_walk(c, instr->i_target,
3600 target_depth, maxdepth);
3601 if (instr->i_opcode == JUMP_ABSOLUTE ||
3602 instr->i_opcode == JUMP_FORWARD) {
3603 goto out; /* remaining code is dead */
3604 }
3605 }
3606 }
3607 if (b->b_next)
3608 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 b->b_seen = 0;
3611 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612}
3613
3614/* Find the flow path that needs the largest stack. We assume that
3615 * cycles in the flow graph have no net effect on the stack depth.
3616 */
3617static int
3618stackdepth(struct compiler *c)
3619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 basicblock *b, *entryblock;
3621 entryblock = NULL;
3622 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3623 b->b_seen = 0;
3624 b->b_startdepth = INT_MIN;
3625 entryblock = b;
3626 }
3627 if (!entryblock)
3628 return 0;
3629 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
3632static int
3633assemble_init(struct assembler *a, int nblocks, int firstlineno)
3634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 memset(a, 0, sizeof(struct assembler));
3636 a->a_lineno = firstlineno;
3637 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3638 if (!a->a_bytecode)
3639 return 0;
3640 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3641 if (!a->a_lnotab)
3642 return 0;
3643 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3644 PyErr_NoMemory();
3645 return 0;
3646 }
3647 a->a_postorder = (basicblock **)PyObject_Malloc(
3648 sizeof(basicblock *) * nblocks);
3649 if (!a->a_postorder) {
3650 PyErr_NoMemory();
3651 return 0;
3652 }
3653 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654}
3655
3656static void
3657assemble_free(struct assembler *a)
3658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 Py_XDECREF(a->a_bytecode);
3660 Py_XDECREF(a->a_lnotab);
3661 if (a->a_postorder)
3662 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663}
3664
3665/* Return the size of a basic block in bytes. */
3666
3667static int
3668instrsize(struct instr *instr)
3669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 if (!instr->i_hasarg)
3671 return 1; /* 1 byte for the opcode*/
3672 if (instr->i_oparg > 0xffff)
3673 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3674 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675}
3676
3677static int
3678blocksize(basicblock *b)
3679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 int i;
3681 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 for (i = 0; i < b->b_iused; i++)
3684 size += instrsize(&b->b_instr[i]);
3685 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003686}
3687
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003688/* Appends a pair to the end of the line number table, a_lnotab, representing
3689 the instruction's bytecode offset and line number. See
3690 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003691
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003692static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003693assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 int d_bytecode, d_lineno;
3696 int len;
3697 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 d_bytecode = a->a_offset - a->a_lineno_off;
3700 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 assert(d_bytecode >= 0);
3703 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 if(d_bytecode == 0 && d_lineno == 0)
3706 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 if (d_bytecode > 255) {
3709 int j, nbytes, ncodes = d_bytecode / 255;
3710 nbytes = a->a_lnotab_off + 2 * ncodes;
3711 len = PyBytes_GET_SIZE(a->a_lnotab);
3712 if (nbytes >= len) {
3713 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3714 len = nbytes;
3715 else if (len <= INT_MAX / 2)
3716 len *= 2;
3717 else {
3718 PyErr_NoMemory();
3719 return 0;
3720 }
3721 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3722 return 0;
3723 }
3724 lnotab = (unsigned char *)
3725 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3726 for (j = 0; j < ncodes; j++) {
3727 *lnotab++ = 255;
3728 *lnotab++ = 0;
3729 }
3730 d_bytecode -= ncodes * 255;
3731 a->a_lnotab_off += ncodes * 2;
3732 }
3733 assert(d_bytecode <= 255);
3734 if (d_lineno > 255) {
3735 int j, nbytes, ncodes = d_lineno / 255;
3736 nbytes = a->a_lnotab_off + 2 * ncodes;
3737 len = PyBytes_GET_SIZE(a->a_lnotab);
3738 if (nbytes >= len) {
3739 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3740 len = nbytes;
3741 else if (len <= INT_MAX / 2)
3742 len *= 2;
3743 else {
3744 PyErr_NoMemory();
3745 return 0;
3746 }
3747 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3748 return 0;
3749 }
3750 lnotab = (unsigned char *)
3751 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3752 *lnotab++ = d_bytecode;
3753 *lnotab++ = 255;
3754 d_bytecode = 0;
3755 for (j = 1; j < ncodes; j++) {
3756 *lnotab++ = 0;
3757 *lnotab++ = 255;
3758 }
3759 d_lineno -= ncodes * 255;
3760 a->a_lnotab_off += ncodes * 2;
3761 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 len = PyBytes_GET_SIZE(a->a_lnotab);
3764 if (a->a_lnotab_off + 2 >= len) {
3765 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3766 return 0;
3767 }
3768 lnotab = (unsigned char *)
3769 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 a->a_lnotab_off += 2;
3772 if (d_bytecode) {
3773 *lnotab++ = d_bytecode;
3774 *lnotab++ = d_lineno;
3775 }
3776 else { /* First line of a block; def stmt, etc. */
3777 *lnotab++ = 0;
3778 *lnotab++ = d_lineno;
3779 }
3780 a->a_lineno = i->i_lineno;
3781 a->a_lineno_off = a->a_offset;
3782 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003783}
3784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785/* assemble_emit()
3786 Extend the bytecode with a new instruction.
3787 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003788*/
3789
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003790static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 int size, arg = 0, ext = 0;
3794 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
3795 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 size = instrsize(i);
3798 if (i->i_hasarg) {
3799 arg = i->i_oparg;
3800 ext = arg >> 16;
3801 }
3802 if (i->i_lineno && !assemble_lnotab(a, i))
3803 return 0;
3804 if (a->a_offset + size >= len) {
3805 if (len > PY_SSIZE_T_MAX / 2)
3806 return 0;
3807 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
3808 return 0;
3809 }
3810 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
3811 a->a_offset += size;
3812 if (size == 6) {
3813 assert(i->i_hasarg);
3814 *code++ = (char)EXTENDED_ARG;
3815 *code++ = ext & 0xff;
3816 *code++ = ext >> 8;
3817 arg &= 0xffff;
3818 }
3819 *code++ = i->i_opcode;
3820 if (i->i_hasarg) {
3821 assert(size == 3 || size == 6);
3822 *code++ = arg & 0xff;
3823 *code++ = arg >> 8;
3824 }
3825 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003826}
3827
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003828static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 basicblock *b;
3832 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
3833 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 /* Compute the size of each block and fixup jump args.
3836 Replace block pointer with position in bytecode. */
3837 do {
3838 totsize = 0;
3839 for (i = a->a_nblocks - 1; i >= 0; i--) {
3840 b = a->a_postorder[i];
3841 bsize = blocksize(b);
3842 b->b_offset = totsize;
3843 totsize += bsize;
3844 }
3845 last_extended_arg_count = extended_arg_count;
3846 extended_arg_count = 0;
3847 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3848 bsize = b->b_offset;
3849 for (i = 0; i < b->b_iused; i++) {
3850 struct instr *instr = &b->b_instr[i];
3851 /* Relative jumps are computed relative to
3852 the instruction pointer after fetching
3853 the jump instruction.
3854 */
3855 bsize += instrsize(instr);
3856 if (instr->i_jabs)
3857 instr->i_oparg = instr->i_target->b_offset;
3858 else if (instr->i_jrel) {
3859 int delta = instr->i_target->b_offset - bsize;
3860 instr->i_oparg = delta;
3861 }
3862 else
3863 continue;
3864 if (instr->i_oparg > 0xffff)
3865 extended_arg_count++;
3866 }
3867 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 /* XXX: This is an awful hack that could hurt performance, but
3870 on the bright side it should work until we come up
3871 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 The issue is that in the first loop blocksize() is called
3874 which calls instrsize() which requires i_oparg be set
3875 appropriately. There is a bootstrap problem because
3876 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 So we loop until we stop seeing new EXTENDED_ARGs.
3879 The only EXTENDED_ARGs that could be popping up are
3880 ones in jump instructions. So this should converge
3881 fairly quickly.
3882 */
3883 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003884}
3885
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003886static PyObject *
3887dict_keys_inorder(PyObject *dict, int offset)
3888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 PyObject *tuple, *k, *v;
3890 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 tuple = PyTuple_New(size);
3893 if (tuple == NULL)
3894 return NULL;
3895 while (PyDict_Next(dict, &pos, &k, &v)) {
3896 i = PyLong_AS_LONG(v);
3897 /* The keys of the dictionary are tuples. (see compiler_add_o)
3898 The object we want is always first, though. */
3899 k = PyTuple_GET_ITEM(k, 0);
3900 Py_INCREF(k);
3901 assert((i - offset) < size);
3902 assert((i - offset) >= 0);
3903 PyTuple_SET_ITEM(tuple, i - offset, k);
3904 }
3905 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003906}
3907
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003908static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 PySTEntryObject *ste = c->u->u_ste;
3912 int flags = 0, n;
3913 if (ste->ste_type != ModuleBlock)
3914 flags |= CO_NEWLOCALS;
3915 if (ste->ste_type == FunctionBlock) {
3916 if (!ste->ste_unoptimized)
3917 flags |= CO_OPTIMIZED;
3918 if (ste->ste_nested)
3919 flags |= CO_NESTED;
3920 if (ste->ste_generator)
3921 flags |= CO_GENERATOR;
3922 if (ste->ste_varargs)
3923 flags |= CO_VARARGS;
3924 if (ste->ste_varkeywords)
3925 flags |= CO_VARKEYWORDS;
3926 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 /* (Only) inherit compilerflags in PyCF_MASK */
3929 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 n = PyDict_Size(c->u->u_freevars);
3932 if (n < 0)
3933 return -1;
3934 if (n == 0) {
3935 n = PyDict_Size(c->u->u_cellvars);
3936 if (n < 0)
3937 return -1;
3938 if (n == 0) {
3939 flags |= CO_NOFREE;
3940 }
3941 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003944}
3945
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946static PyCodeObject *
3947makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 PyObject *tmp;
3950 PyCodeObject *co = NULL;
3951 PyObject *consts = NULL;
3952 PyObject *names = NULL;
3953 PyObject *varnames = NULL;
3954 PyObject *filename = NULL;
3955 PyObject *name = NULL;
3956 PyObject *freevars = NULL;
3957 PyObject *cellvars = NULL;
3958 PyObject *bytecode = NULL;
3959 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 tmp = dict_keys_inorder(c->u->u_consts, 0);
3962 if (!tmp)
3963 goto error;
3964 consts = PySequence_List(tmp); /* optimize_code requires a list */
3965 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 names = dict_keys_inorder(c->u->u_names, 0);
3968 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3969 if (!consts || !names || !varnames)
3970 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3973 if (!cellvars)
3974 goto error;
3975 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3976 if (!freevars)
3977 goto error;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00003978 filename = PyUnicode_DecodeFSDefault(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 if (!filename)
3980 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 nlocals = PyDict_Size(c->u->u_varnames);
3983 flags = compute_code_flags(c);
3984 if (flags < 0)
3985 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
3988 if (!bytecode)
3989 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3992 if (!tmp)
3993 goto error;
3994 Py_DECREF(consts);
3995 consts = tmp;
3996
3997 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3998 nlocals, stackdepth(c), flags,
3999 bytecode, consts, names, varnames,
4000 freevars, cellvars,
4001 filename, c->u->u_name,
4002 c->u->u_firstlineno,
4003 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004004 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 Py_XDECREF(consts);
4006 Py_XDECREF(names);
4007 Py_XDECREF(varnames);
4008 Py_XDECREF(filename);
4009 Py_XDECREF(name);
4010 Py_XDECREF(freevars);
4011 Py_XDECREF(cellvars);
4012 Py_XDECREF(bytecode);
4013 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004014}
4015
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004016
4017/* For debugging purposes only */
4018#if 0
4019static void
4020dump_instr(const struct instr *i)
4021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 const char *jrel = i->i_jrel ? "jrel " : "";
4023 const char *jabs = i->i_jabs ? "jabs " : "";
4024 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 *arg = '\0';
4027 if (i->i_hasarg)
4028 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4031 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004032}
4033
4034static void
4035dump_basicblock(const basicblock *b)
4036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 const char *seen = b->b_seen ? "seen " : "";
4038 const char *b_return = b->b_return ? "return " : "";
4039 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4040 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4041 if (b->b_instr) {
4042 int i;
4043 for (i = 0; i < b->b_iused; i++) {
4044 fprintf(stderr, " [%02d] ", i);
4045 dump_instr(b->b_instr + i);
4046 }
4047 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004048}
4049#endif
4050
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004051static PyCodeObject *
4052assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 basicblock *b, *entryblock;
4055 struct assembler a;
4056 int i, j, nblocks;
4057 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 /* Make sure every block that falls off the end returns None.
4060 XXX NEXT_BLOCK() isn't quite right, because if the last
4061 block ends with a jump or return b_next shouldn't set.
4062 */
4063 if (!c->u->u_curblock->b_return) {
4064 NEXT_BLOCK(c);
4065 if (addNone)
4066 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4067 ADDOP(c, RETURN_VALUE);
4068 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 nblocks = 0;
4071 entryblock = NULL;
4072 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4073 nblocks++;
4074 entryblock = b;
4075 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 /* Set firstlineno if it wasn't explicitly set. */
4078 if (!c->u->u_firstlineno) {
4079 if (entryblock && entryblock->b_instr)
4080 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4081 else
4082 c->u->u_firstlineno = 1;
4083 }
4084 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4085 goto error;
4086 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 /* Can't modify the bytecode after computing jump offsets. */
4089 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 /* Emit code in reverse postorder from dfs. */
4092 for (i = a.a_nblocks - 1; i >= 0; i--) {
4093 b = a.a_postorder[i];
4094 for (j = 0; j < b->b_iused; j++)
4095 if (!assemble_emit(&a, &b->b_instr[j]))
4096 goto error;
4097 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4100 goto error;
4101 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4102 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 assemble_free(&a);
4107 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004108}
Georg Brandl8334fd92010-12-04 10:26:46 +00004109
4110#undef PyAST_Compile
4111PyAPI_FUNC(PyCodeObject *)
4112PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4113 PyArena *arena)
4114{
4115 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4116}
4117
4118